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

difftreelog

transferFrom tests

kpozdnikin2021-01-18parent: #f8c3f30.patch.diff
in: master

3 files changed

modifiedtests/src/approve.test.tsdiffbeforeafterboth
--- a/tests/src/approve.test.ts
+++ b/tests/src/approve.test.ts
@@ -7,7 +7,7 @@
 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 { default as usingApi } from './substrate/substrate-api';
 import {
   approveExpectFail,
   approveExpectSuccess,
@@ -29,11 +29,12 @@
       const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
       await approveExpectSuccess(nftCollectionId, newNftTokenId, Alice, Bob);
       // fungible
-      const fungibleCollectionId = await createCollectionExpectSuccess({mode: 'Fungible'});
+      const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
       const newFungibleTokenId = await createItemExpectSuccess(Alice, fungibleCollectionId, 'Fungible');
       await approveExpectSuccess(fungibleCollectionId, newFungibleTokenId, Alice, Bob);
       // reFungible
-      const reFungibleCollectionId = await createCollectionExpectSuccess({mode: 'ReFungible'});
+      const reFungibleCollectionId =
+        await createCollectionExpectSuccess({mode: {type: 'ReFungible', decimalPoints: 0}});
       const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');
       await approveExpectSuccess(reFungibleCollectionId, newReFungibleTokenId, Alice, Bob);
 
@@ -54,12 +55,13 @@
       await approveExpectSuccess(nftCollectionId, newNftTokenId, Alice, Bob, 1);
       await approveExpectSuccess(nftCollectionId, newNftTokenId, Alice, Bob, 0);
       // fungible
-      const fungibleCollectionId = await createCollectionExpectSuccess({mode: 'Fungible'});
+      const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
       const newFungibleTokenId = await createItemExpectSuccess(Alice, fungibleCollectionId, 'Fungible');
       await approveExpectSuccess(fungibleCollectionId, newFungibleTokenId, Alice, Bob, 1);
       await approveExpectSuccess(fungibleCollectionId, newFungibleTokenId, Alice, Bob, 0);
       // reFungible
-      const reFungibleCollectionId = await createCollectionExpectSuccess({mode: 'ReFungible'});
+      const reFungibleCollectionId =
+        await createCollectionExpectSuccess({mode: {type: 'ReFungible', decimalPoints: 0}});
       const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');
       await approveExpectSuccess(reFungibleCollectionId, newReFungibleTokenId, Alice, Bob, 1);
       await approveExpectSuccess(reFungibleCollectionId, newReFungibleTokenId, Alice, Bob, 0);
@@ -81,10 +83,11 @@
       const nftCollectionId = await createCollectionExpectSuccess();
       await approveExpectFail(nftCollectionId + 1, 1, Alice, Bob);
       // fungible
-      const fungibleCollectionId = await createCollectionExpectSuccess({mode: 'Fungible'});
+      const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
       await approveExpectFail(fungibleCollectionId + 1, 1, Alice, Bob);
       // reFungible
-      const reFungibleCollectionId = await createCollectionExpectSuccess({mode: 'ReFungible'});
+      const reFungibleCollectionId =
+        await createCollectionExpectSuccess({mode: {type: 'ReFungible', decimalPoints: 0}});
       await approveExpectFail(reFungibleCollectionId + 1, 1, Alice, Bob);
       // garbage collection :-D
       await destroyCollectionExpectSuccess(nftCollectionId);
@@ -102,11 +105,12 @@
       await destroyCollectionExpectSuccess(nftCollectionId);
       await approveExpectFail(nftCollectionId, 1, Alice, Bob);
       // fungible
-      const fungibleCollectionId = await createCollectionExpectSuccess({mode: 'Fungible'});
+      const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
       await destroyCollectionExpectSuccess(fungibleCollectionId);
       await approveExpectFail(fungibleCollectionId, 1, Alice, Bob);
       // reFungible
-      const reFungibleCollectionId = await createCollectionExpectSuccess({mode: 'ReFungible'});
+      const reFungibleCollectionId =
+        await createCollectionExpectSuccess({mode: {type: 'ReFungible', decimalPoints: 0}});
       await destroyCollectionExpectSuccess(reFungibleCollectionId);
       await approveExpectFail(reFungibleCollectionId, 1, Alice, Bob);
     });
@@ -120,10 +124,11 @@
       const nftCollectionId = await createCollectionExpectSuccess();
       await approveExpectFail(nftCollectionId, 2, Alice, Bob);
       // fungible
-      const fungibleCollectionId = await createCollectionExpectSuccess({mode: 'Fungible'});
+      const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
       await approveExpectFail(fungibleCollectionId, 2, Alice, Bob);
       // reFungible
-      const reFungibleCollectionId = await createCollectionExpectSuccess({mode: 'ReFungible'});
+      const reFungibleCollectionId =
+        await createCollectionExpectSuccess({mode: {type: 'ReFungible', decimalPoints: 0}});
       await approveExpectFail(reFungibleCollectionId, 2, Alice, Bob);
       // garbage collection :-D
       await destroyCollectionExpectSuccess(nftCollectionId);
@@ -141,11 +146,12 @@
       const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
       await approveExpectFail(nftCollectionId, newNftTokenId, Bob, Alice);
       // fungible
-      const fungibleCollectionId = await createCollectionExpectSuccess({mode: 'Fungible'});
+      const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
       const newFungibleTokenId = await createItemExpectSuccess(Alice, fungibleCollectionId, 'Fungible');
       await approveExpectFail(fungibleCollectionId, newFungibleTokenId, Bob, Alice);
       // reFungible
-      const reFungibleCollectionId = await createCollectionExpectSuccess({mode: 'ReFungible'});
+      const reFungibleCollectionId =
+        await createCollectionExpectSuccess({mode: {type: 'ReFungible', decimalPoints: 0}});
       const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');
       await approveExpectFail(reFungibleCollectionId, newReFungibleTokenId, Bob, Alice);
 
modifiedtests/src/transferFrom.test.tsdiffbeforeafterboth
--- a/tests/src/transferFrom.test.ts
+++ b/tests/src/transferFrom.test.ts
@@ -3,19 +3,19 @@
 // file 'LICENSE', which is part of this source code package.
 //
 import { ApiPromise } from '@polkadot/api';
-import BN from 'bn.js';
 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 { default as usingApi } from './substrate/substrate-api';
 import {
+  approveExpectFail,
   approveExpectSuccess,
   createCollectionExpectSuccess,
   createItemExpectSuccess,
   destroyCollectionExpectSuccess,
+  transferFromExpectFail,
   transferFromExpectSuccess,
 } from './util/helpers';
-import {IKeyringPair} from "@polkadot/types/types";
 
 chai.use(chaiAsPromised);
 const expect = chai.expect;
@@ -26,29 +26,30 @@
       const Alice = privateKey('//Alice');
       const Bob = privateKey('//Bob');
       const Charlie = privateKey('//CHARLIE');
+      // nft
       const nftCollectionId = await createCollectionExpectSuccess();
-      console.log('nftCollectionId', nftCollectionId);
-      const collectionInfo = await api.query.nft.collection(nftCollectionId);
-      console.log('collectionInfo', collectionInfo);
-      // nft
       const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
       await approveExpectSuccess(nftCollectionId, newNftTokenId, Alice, Bob);
 
-      await transferFromExpectSuccess(nftCollectionId, newNftTokenId, Alice, Charlie, 1, 'NFT');
+      await transferFromExpectSuccess(nftCollectionId, newNftTokenId, Bob, Alice, Charlie, 1, 'NFT');
 
       // fungible
-      /*const fungibleCollectionId = await createCollectionExpectSuccess({mode: 'Fungible'});
+      const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
       const newFungibleTokenId = await createItemExpectSuccess(Alice, fungibleCollectionId, 'Fungible');
       await approveExpectSuccess(fungibleCollectionId, newFungibleTokenId, Alice, Bob);
+      await transferFromExpectSuccess(fungibleCollectionId, newFungibleTokenId, Bob, Alice, Charlie, 1, 'Fungible');
       // reFungible
-      const reFungibleCollectionId = await createCollectionExpectSuccess({mode: 'ReFungible'});
+      const reFungibleCollectionId = await
+        createCollectionExpectSuccess({mode: {type: 'ReFungible', decimalPoints: 0}});
       const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');
-      await approveExpectSuccess(reFungibleCollectionId, newReFungibleTokenId, Alice, Bob);*/
+      await approveExpectSuccess(reFungibleCollectionId, newReFungibleTokenId, Alice, Bob);
+      await transferFromExpectSuccess(reFungibleCollectionId,
+        newReFungibleTokenId, Bob, Alice, Charlie, 1, 'ReFungible');
 
       // garbage collection :-D
       await destroyCollectionExpectSuccess(nftCollectionId);
-      // await destroyCollectionExpectSuccess(fungibleCollectionId);
-      // await destroyCollectionExpectSuccess(reFungibleCollectionId);
+      await destroyCollectionExpectSuccess(fungibleCollectionId);
+      await destroyCollectionExpectSuccess(reFungibleCollectionId);
     });
   });
 });
@@ -56,43 +57,157 @@
 describe('Negative Integration Test transferFrom(from, recipient, collection_id, item_id, value):', () => {
   it('transferFrom for a collection that does not exist', async () => {
     await usingApi(async (api: ApiPromise) => {
+      const Alice = privateKey('//Alice');
+      const Bob = privateKey('//Bob');
+      const Charlie = privateKey('//CHARLIE');
+      // nft
+      const nftCollectionId = await createCollectionExpectSuccess();
+      await approveExpectFail(nftCollectionId + 1, 1, Alice, Bob);
+
+      await transferFromExpectFail(nftCollectionId + 1, 1, Bob, Alice, Charlie, 1);
+
+      // fungible
+      const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+      await approveExpectFail(fungibleCollectionId + 1, 1, Alice, Bob);
+
+      await transferFromExpectFail(fungibleCollectionId + 1, 1, Bob, Alice, Charlie, 1);
+      // reFungible
+      const reFungibleCollectionId = await
+        createCollectionExpectSuccess({mode: {type: 'ReFungible', decimalPoints: 0}});
+      await approveExpectFail(reFungibleCollectionId + 1, 1, Alice, Bob);
 
+      await transferFromExpectFail(reFungibleCollectionId + 1, 1, Bob, Alice, Charlie, 1);
+
+      // garbage collection :-D
+      await destroyCollectionExpectSuccess(nftCollectionId);
+      await destroyCollectionExpectSuccess(fungibleCollectionId);
+      await destroyCollectionExpectSuccess(reFungibleCollectionId);
     });
   });
 
-  it('transferFrom for a collection that was destroyed', async () => {
+  /* it('transferFrom for a collection that was destroyed', async () => {
     await usingApi(async (api: ApiPromise) => {
-
+      this test copies approve negative test
     });
-  });
+  }); */
 
-  it('transferFrom a token that does not exist', async () => {
+  /* it('transferFrom a token that does not exist', async () => {
     await usingApi(async (api: ApiPromise) => {
-
+      this test copies approve negative test
     });
-  });
+  }); */
 
-  it('transferFrom a token that was deleted', async () => {
+  /* it('transferFrom a token that was deleted', async () => {
     await usingApi(async (api: ApiPromise) => {
-
+      this test copies approve negative test
     });
-  });
+  }); */
 
   it('transferFrom for not approved address', async () => {
     await usingApi(async (api: ApiPromise) => {
+      const Alice = privateKey('//Alice');
+      const Bob = privateKey('//Bob');
+      const Charlie = privateKey('//CHARLIE');
+      // nft
+      const nftCollectionId = await createCollectionExpectSuccess();
+      const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
 
+      await transferFromExpectFail(nftCollectionId, newNftTokenId, Bob, Alice, Charlie, 1);
+
+      // fungible
+      const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+      const newFungibleTokenId = await createItemExpectSuccess(Alice, fungibleCollectionId, 'Fungible');
+      await transferFromExpectFail(fungibleCollectionId, newFungibleTokenId, Bob, Alice, Charlie, 1);
+      // reFungible
+      const reFungibleCollectionId = await
+        createCollectionExpectSuccess({mode: {type: 'ReFungible', decimalPoints: 0}});
+      const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');
+      await transferFromExpectFail(reFungibleCollectionId,
+        newReFungibleTokenId, Bob, Alice, Charlie, 1);
+
+      // garbage collection :-D
+      await destroyCollectionExpectSuccess(nftCollectionId);
+      await destroyCollectionExpectSuccess(fungibleCollectionId);
+      await destroyCollectionExpectSuccess(reFungibleCollectionId);
     });
   });
 
   it('transferFrom incorrect token count', async () => {
     await usingApi(async (api: ApiPromise) => {
+      const Alice = privateKey('//Alice');
+      const Bob = privateKey('//Bob');
+      const Charlie = privateKey('//CHARLIE');
+      // nft
+      const nftCollectionId = await createCollectionExpectSuccess();
+      const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
+      await approveExpectSuccess(nftCollectionId, newNftTokenId, Alice, Bob);
+
+      await transferFromExpectFail(nftCollectionId, newNftTokenId, Bob, Alice, Charlie, 2);
+
+      // fungible
+      const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+      const newFungibleTokenId = await createItemExpectSuccess(Alice, fungibleCollectionId, 'Fungible');
+      await approveExpectSuccess(fungibleCollectionId, newFungibleTokenId, Alice, Bob);
+      await transferFromExpectFail(fungibleCollectionId, newFungibleTokenId, Bob, Alice, Charlie, 2);
+      // reFungible
+      const reFungibleCollectionId = await
+        createCollectionExpectSuccess({mode: {type: 'ReFungible', decimalPoints: 0}});
+      const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');
+      await approveExpectSuccess(reFungibleCollectionId, newReFungibleTokenId, Alice, Bob);
+      await transferFromExpectFail(reFungibleCollectionId,
+        newReFungibleTokenId, Bob, Alice, Charlie, 2);
 
+      // garbage collection :-D
+      await destroyCollectionExpectSuccess(nftCollectionId);
+      await destroyCollectionExpectSuccess(fungibleCollectionId);
+      await destroyCollectionExpectSuccess(reFungibleCollectionId);
     });
   });
 
   it('execute transferFrom from account that is not owner of collection', async () => {
     await usingApi(async (api: ApiPromise) => {
+      const Alice = privateKey('//Alice');
+      const Bob = privateKey('//Bob');
+      const Charlie = privateKey('//CHARLIE');
+      const Dave = privateKey('//DAVE');
+      // nft
+      const nftCollectionId = await createCollectionExpectSuccess();
+      const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
+      try {
+        await approveExpectFail(nftCollectionId, newNftTokenId, Dave, Bob);
+        await transferFromExpectFail(nftCollectionId, newNftTokenId, Dave, Alice, Charlie, 1);
+      } catch (e) {
+        // tslint:disable-next-line:no-unused-expression
+        expect(e).to.be.exist;
+      }
 
+      // await transferFromExpectFail(nftCollectionId, newNftTokenId, Dave, Alice, Charlie, 1);
+
+      // fungible
+      const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+      const newFungibleTokenId = await createItemExpectSuccess(Alice, fungibleCollectionId, 'Fungible');
+      try {
+        await approveExpectFail(fungibleCollectionId, newFungibleTokenId, Dave, Bob);
+        await transferFromExpectFail(fungibleCollectionId, newFungibleTokenId, Dave, Alice, Charlie, 1);
+      } catch (e) {
+        // tslint:disable-next-line:no-unused-expression
+        expect(e).to.be.exist;
+      }
+      // reFungible
+      const reFungibleCollectionId = await
+        createCollectionExpectSuccess({mode: {type: 'ReFungible', decimalPoints: 0}});
+      const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');
+      try {
+        await approveExpectFail(reFungibleCollectionId, newReFungibleTokenId, Dave, Bob);
+        await transferFromExpectFail(reFungibleCollectionId, newReFungibleTokenId, Dave, Alice, Charlie, 1);
+      } catch (e) {
+        // tslint:disable-next-line:no-unused-expression
+        expect(e).to.be.exist;
+      }
+      // garbage collection :-D
+      await destroyCollectionExpectSuccess(nftCollectionId);
+      await destroyCollectionExpectSuccess(fungibleCollectionId);
+      await destroyCollectionExpectSuccess(reFungibleCollectionId);
     });
   });
 });
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
before · tests/src/util/helpers.ts
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import { ApiPromise, Keyring } from '@polkadot/api';7import { Enum, Struct } from '@polkadot/types/codec';8import type { AccountId, EventRecord } from '@polkadot/types/interfaces';9import { u128 } from '@polkadot/types/primitive';10import { IKeyringPair } from '@polkadot/types/types';11import { BigNumber } from 'bignumber.js';12import BN from 'bn.js';13import chai from 'chai';14import chaiAsPromised from 'chai-as-promised';15import { alicesPublicKey, nullPublicKey } from '../accounts';16import privateKey from '../substrate/privateKey';17import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';18import { ICollectionInterface } from '../types';19import { hexToStr, strToUTF16, utf16ToStr } from './util';2021chai.use(chaiAsPromised);22const expect = chai.expect;2324type GenericResult = {25  success: boolean,26};2728interface CreateCollectionResult {29  success: boolean;30  collectionId: number;31}3233interface CreateItemResult {34  success: boolean;35  collectionId: number;36  itemId: number;37}3839interface ITokenDataType {40  Owner: number[];41  ConstData: number[];42  VariableData: number[];43}4445export function getGenericResult(events: EventRecord[]): GenericResult {46  const result: GenericResult = {47    success: false,48  };49  events.forEach(({ phase, event: { data, method, section } }) => {50    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);51    if (method === 'ExtrinsicSuccess') {52      result.success = true;53    }54  });55  return result;56}5758export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {59  let success = false;60  let collectionId: number = 0;61  events.forEach(({ phase, event: { data, method, section } }) => {62    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);63    if (method == 'ExtrinsicSuccess') {64      success = true;65    } else if ((section == 'nft') && (method == 'Created')) {66      collectionId = parseInt(data[0].toString());67    }68  });69  const result: CreateCollectionResult = {70    success,71    collectionId,72  };73  return result;74}7576export function getCreateItemResult(events: EventRecord[]): CreateItemResult {77  let success = false;78  let collectionId: number = 0;79  let itemId: number = 0;80  events.forEach(({ phase, event: { data, method, section } }) => {81    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);82    if (method == 'ExtrinsicSuccess') {83      success = true;84    } else if ((section == 'nft') && (method == 'ItemCreated')) {85      collectionId = parseInt(data[0].toString());86      itemId = parseInt(data[1].toString());87    }88  });89  const result: CreateItemResult = {90    success,91    collectionId,92    itemId,93  };94  return result;95}9697interface Invalid {98  type: 'Invalid';99}100101interface Nft {102  type: 'NFT';103}104105interface Fungible {106  type: 'Fungible';107  decimalPoints: number;108}109110interface ReFungible {111  type: 'ReFungible';112  decimalPoints: number;113}114115interface Nft {116  type: 'NFT'117}118119interface Fungible {120  type: 'Fungible',121  decimalPoints: number122}123124interface ReFungible {125  type: 'ReFungible',126  decimalPoints: number127}128129type CollectionMode = Nft | Fungible | ReFungible | Invalid;130131export type CreateCollectionParams = {132  mode: CollectionMode,133  name: string,134  description: string,135  tokenPrefix: string,136};137138const defaultCreateCollectionParams: CreateCollectionParams = {139  description: 'description',140  mode: { type: 'NFT' },141  name: 'name',142  tokenPrefix: 'prefix',143}144145export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {146  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};147148  let collectionId: number = 0;149  await usingApi(async (api) => {150    // Get number of collections before the transaction151    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);152153    // Run the CreateCollection transaction154    const alicePrivateKey = privateKey('//Alice');155156    let modeprm = {};157    if (mode.type === 'NFT') {158      modeprm = {nft: null};159    } else if (mode.type === 'Fungible') {160      modeprm = {fungible: mode.decimalPoints};161    } else if (mode.type === 'ReFungible') {162      modeprm = {refungible: mode.decimalPoints};163    } else if (mode.type === 'Invalid') {164      modeprm = {invalid: null};165    }166167    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);168    const events = await submitTransactionAsync(alicePrivateKey, tx);169    const result = getCreateCollectionResult(events);170171    // Get number of collections after the transaction172    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);173174    // Get the collection175    const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();176177    // What to expect178    // tslint:disable-next-line:no-unused-expression179    expect(result.success).to.be.true;180    expect(result.collectionId).to.be.equal(BcollectionCount);181    // tslint:disable-next-line:no-unused-expression182    expect(collection).to.be.not.null;183    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');184    expect(collection.Owner).to.be.equal(alicesPublicKey);185    expect(utf16ToStr(collection.Name)).to.be.equal(name);186    expect(utf16ToStr(collection.Description)).to.be.equal(description);187    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);188189    collectionId = result.collectionId;190  });191192  return collectionId;193}194195export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {196  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};197198  let modeprm = {};199  if (mode.type === 'NFT') {200    modeprm = {nft: null};201  } else if (mode.type === 'Fungible') {202    modeprm = {fungible: mode.decimalPoints};203  } else if (mode.type === 'ReFungible') {204    modeprm = {refungible: mode.decimalPoints};205  } else if (mode.type === 'Invalid') {206    modeprm = {invalid: null};207  }208209  await usingApi(async (api) => {210    // Get number of collections before the transaction211    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());212213    // Run the CreateCollection transaction214    const alicePrivateKey = privateKey('//Alice');215    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);216    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;217    const result = getCreateCollectionResult(events);218219    // Get number of collections after the transaction220    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());221222    // What to expect223    // tslint:disable-next-line:no-unused-expression224    expect(result.success).to.be.false;225    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');226  });227}228229export async function findUnusedAddress(api: ApiPromise): Promise<IKeyringPair> {230  let bal = new BigNumber(0);231  let unused;232  do {233    const randomSeed = 'seed' +  Math.floor(Math.random() * Math.floor(10000));234    const keyring = new Keyring({ type: 'sr25519' });235    unused = keyring.addFromUri(`//${randomSeed}`);236    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());237  } while (bal.toFixed() != '0');238  return unused;239}240241function getDestroyResult(events: EventRecord[]): boolean {242  let success: boolean = false;243  events.forEach(({ phase, event: { data, method, section } }) => {244    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);245    if (method == 'ExtrinsicSuccess') {246      success = true;247    }248  });249  return success;250}251252export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {253  await usingApi(async (api) => {254    // Run the DestroyCollection transaction255    const alicePrivateKey = privateKey(senderSeed);256    const tx = api.tx.nft.destroyCollection(collectionId);257    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;258  });259}260261export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {262  await usingApi(async (api) => {263    // Run the DestroyCollection transaction264    const alicePrivateKey = privateKey(senderSeed);265    const tx = api.tx.nft.destroyCollection(collectionId);266    const events = await submitTransactionAsync(alicePrivateKey, tx);267    const result = getDestroyResult(events);268269    // Get the collection270    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();271272    // What to expect273    expect(result).to.be.true;274    expect(collection).to.be.not.null;275    expect(collection.Owner).to.be.equal(nullPublicKey);276  });277}278279export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {280  await usingApi(async (api) => {281282    // Run the transaction283    const alicePrivateKey = privateKey('//Alice');284    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);285    const events = await submitTransactionAsync(alicePrivateKey, tx);286    const result = getGenericResult(events);287288    // Get the collection289    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();290291    // What to expect292    expect(result.success).to.be.true;293    expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());294    expect(collection.SponsorConfirmed).to.be.false;295  });296}297298export async function removeCollectionSponsorExpectSuccess(collectionId: number) {299  await usingApi(async (api) => {300301    // Run the transaction302    const alicePrivateKey = privateKey('//Alice');303    const tx = api.tx.nft.removeCollectionSponsor(collectionId);304    const events = await submitTransactionAsync(alicePrivateKey, tx);305    const result = getGenericResult(events);306307    // Get the collection308    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();309310    // What to expect311    expect(result.success).to.be.true;312    expect(collection.Sponsor).to.be.equal(nullPublicKey);313    expect(collection.SponsorConfirmed).to.be.false;314  });315}316317export async function removeCollectionSponsorExpectFailure(collectionId: number) {318  await usingApi(async (api) => {319320    // Run the transaction321    const alicePrivateKey = privateKey('//Alice');322    const tx = api.tx.nft.removeCollectionSponsor(collectionId);323    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;324  });325}326327export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {328  await usingApi(async (api) => {329330    // Run the transaction331    const alicePrivateKey = privateKey(senderSeed);332    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);333    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;334  });335}336337export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {338  await usingApi(async (api) => {339340    // Run the transaction341    const sender = privateKey(senderSeed);342    const tx = api.tx.nft.confirmSponsorship(collectionId);343    const events = await submitTransactionAsync(sender, tx);344    const result = getGenericResult(events);345346    // Get the collection347    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();348349    // What to expect350    expect(result.success).to.be.true;351    expect(collection.Sponsor).to.be.equal(sender.address);352    expect(collection.SponsorConfirmed).to.be.true;353  });354}355356export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {357  await usingApi(async (api) => {358359    // Run the transaction360    const sender = privateKey(senderSeed);361    const tx = api.tx.nft.confirmSponsorship(collectionId);362    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;363  });364}365366export interface CreateFungibleData extends Struct {367  readonly value: u128;368}369370export interface CreateReFungibleData extends Struct {}371export interface CreateNftData extends Struct {}372373export interface CreateItemData extends Enum {374  NFT: CreateNftData;375  Fungible: CreateFungibleData;376  ReFungible: CreateReFungibleData;377}378379export async function380approveExpectSuccess(collectionId: number,381                     tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number = 1) {382  await usingApi(async (api: ApiPromise) => {383    const allowanceBefore =384      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;385    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);386    const events = await submitTransactionAsync(owner, approveNftTx);387    const result = getCreateItemResult(events);388    // tslint:disable-next-line:no-unused-expression389    expect(result.success).to.be.true;390    const allowanceAfter =391      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;392    expect(allowanceAfter.toNumber() - allowanceBefore.toNumber()).to.be.equal(amount);393  });394}395396export async function397transferFromExpectSuccess(collectionId: number, tokenId: number, accountFrom: IKeyringPair,398                          accountTo: IKeyringPair, value: number = 1, type: string = 'NFT') {399  await usingApi(async (api: ApiPromise) => {400    const transferFromTx = await api.tx.nft.transferFrom(401      accountFrom.address, accountTo.address, collectionId, tokenId, value);402    const events = await submitTransactionAsync(accountFrom, transferFromTx);403    const result = getCreateItemResult(events);404    // tslint:disable-next-line:no-unused-expression405    expect(result.success).to.be.true;406    if (type === 'NFT') {407      const nftItemData = api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;408      console.log('NFT data', nftItemData);409    }410    if (type === 'Fungible') {411      const nftItemData = api.query.nft.fungibleItemList(collectionId, tokenId) as unknown as ITokenDataType;412      console.log('Fungible data', nftItemData);413    }414    if (type === 'ReFungible') {415      const nftItemData = api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as ITokenDataType;416      console.log('reFungibleItemList data', nftItemData);417    }418  });419}420421export async function422approveExpectFail(collectionId: number,423                  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number = 1) {424  await usingApi(async (api: ApiPromise) => {425    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);426    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;427    const result = getCreateCollectionResult(events);428    // tslint:disable-next-line:no-unused-expression429    expect(result.success).to.be.false;430  });431}432433export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {434  let newItemId: number = 0;435  await usingApi(async (api) => {436    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);437    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();438    const AItemBalance = new BigNumber(Aitem.Value);439440    if (owner === '') {441      owner = sender.address;442    }443444    let tx;445    if (createMode === 'Fungible') {446      const createData = {fungible: {value: 10}};447      tx = api.tx.nft.createItem(collectionId, owner, createData);448    } else {449      tx = api.tx.nft.createItem(collectionId, owner, createMode);450    }451    const events = await submitTransactionAsync(sender, tx);452    const result = getCreateItemResult(events);453454    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);455    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();456    const BItemBalance = new BigNumber(Bitem.Value);457458    // What to expect459    // tslint:disable-next-line:no-unused-expression460    expect(result.success).to.be.true;461    if (createMode === 'Fungible') {462      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);463    } else {464      expect(BItemCount).to.be.equal(AItemCount + 1);465    }466    expect(collectionId).to.be.equal(result.collectionId);467    expect(BItemCount).to.be.equal(result.itemId);468    newItemId = result.itemId;469  });470  return newItemId;471}472473export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {474  await usingApi(async (api) => {475476    // Run the transaction477    const tx = api.tx.nft.setPublicAccessMode(collectionId, 'WhiteList');478    const events = await submitTransactionAsync(sender, tx);479    const result = getGenericResult(events);480481    // Get the collection482    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();483484    // What to expect485    expect(result.success).to.be.true;486    expect(collection.Access).to.be.equal('WhiteList');487  });488}489490export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {491  await usingApi(async (api) => {492493    // Run the transaction494    const tx = api.tx.nft.setMintPermission(collectionId, true);495    const events = await submitTransactionAsync(sender, tx);496    const result = getGenericResult(events);497498    // Get the collection499    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();500501    // What to expect502    expect(result.success).to.be.true;503    expect(collection.MintMode).to.be.equal(true);504  });505}506507export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {508  await usingApi(async (api) => {509510    // Run the transaction511    const tx = api.tx.nft.addToWhiteList(collectionId, address);512    const events = await submitTransactionAsync(sender, tx);513    const result = getGenericResult(events);514515    // Get the collection516    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();517518    // What to expect519    expect(result.success).to.be.true;520    expect(collection.MintMode).to.be.equal(true);521  });522}523524export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)525  : Promise<ICollectionInterface | null> => {526  return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;527};528529export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {530  // set global object - collectionsCount531  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();532};
after · tests/src/util/helpers.ts
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import { ApiPromise, Keyring } from '@polkadot/api';7import { Enum, Struct } from '@polkadot/types/codec';8import type { AccountId, EventRecord } from '@polkadot/types/interfaces';9import { u128 } from '@polkadot/types/primitive';10import { IKeyringPair } from '@polkadot/types/types';11import { BigNumber } from 'bignumber.js';12import BN from 'bn.js';13import chai from 'chai';14import chaiAsPromised from 'chai-as-promised';15import { alicesPublicKey, nullPublicKey } from '../accounts';16import privateKey from '../substrate/privateKey';17import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';18import { ICollectionInterface } from '../types';19import { hexToStr, strToUTF16, utf16ToStr } from './util';2021chai.use(chaiAsPromised);22const expect = chai.expect;2324type GenericResult = {25  success: boolean,26};2728interface CreateCollectionResult {29  success: boolean;30  collectionId: number;31}3233interface CreateItemResult {34  success: boolean;35  collectionId: number;36  itemId: number;37}3839interface IReFungibleOwner {40  Fraction: BN;41  Owner: number[];42}4344interface ITokenDataType {45  Owner: number[];46  ConstData: number[];47  VariableData: number[];48}4950interface IFungibleTokenDataType {51  Value: BN;52}5354interface IReFungibleTokenDataType {55  Owner: IReFungibleOwner[];56  ConstData: number[];57  VariableData: number[];58}5960export function getGenericResult(events: EventRecord[]): GenericResult {61  const result: GenericResult = {62    success: false,63  };64  events.forEach(({ phase, event: { data, method, section } }) => {65    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);66    if (method === 'ExtrinsicSuccess') {67      result.success = true;68    }69  });70  return result;71}7273export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {74  let success = false;75  let collectionId: number = 0;76  events.forEach(({ phase, event: { data, method, section } }) => {77    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);78    if (method == 'ExtrinsicSuccess') {79      success = true;80    } else if ((section == 'nft') && (method == 'Created')) {81      collectionId = parseInt(data[0].toString());82    }83  });84  const result: CreateCollectionResult = {85    success,86    collectionId,87  };88  return result;89}9091export function getCreateItemResult(events: EventRecord[]): CreateItemResult {92  let success = false;93  let collectionId: number = 0;94  let itemId: number = 0;95  events.forEach(({ phase, event: { data, method, section } }) => {96    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);97    if (method == 'ExtrinsicSuccess') {98      success = true;99    } else if ((section == 'nft') && (method == 'ItemCreated')) {100      collectionId = parseInt(data[0].toString());101      itemId = parseInt(data[1].toString());102    }103  });104  const result: CreateItemResult = {105    success,106    collectionId,107    itemId,108  };109  return result;110}111112interface Invalid {113  type: 'Invalid';114}115116interface Nft {117  type: 'NFT';118}119120interface Fungible {121  type: 'Fungible';122  decimalPoints: number;123}124125interface ReFungible {126  type: 'ReFungible';127  decimalPoints: number;128}129130interface Nft {131  type: 'NFT'132}133134interface Fungible {135  type: 'Fungible',136  decimalPoints: number137}138139interface ReFungible {140  type: 'ReFungible',141  decimalPoints: number142}143144type CollectionMode = Nft | Fungible | ReFungible | Invalid;145146export type CreateCollectionParams = {147  mode: CollectionMode,148  name: string,149  description: string,150  tokenPrefix: string,151};152153const defaultCreateCollectionParams: CreateCollectionParams = {154  description: 'description',155  mode: { type: 'NFT' },156  name: 'name',157  tokenPrefix: 'prefix',158}159160export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {161  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};162163  let collectionId: number = 0;164  await usingApi(async (api) => {165    // Get number of collections before the transaction166    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);167168    // Run the CreateCollection transaction169    const alicePrivateKey = privateKey('//Alice');170171    let modeprm = {};172    if (mode.type === 'NFT') {173      modeprm = {nft: null};174    } else if (mode.type === 'Fungible') {175      modeprm = {fungible: mode.decimalPoints};176    } else if (mode.type === 'ReFungible') {177      modeprm = {refungible: mode.decimalPoints};178    } else if (mode.type === 'Invalid') {179      modeprm = {invalid: null};180    }181182    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);183    const events = await submitTransactionAsync(alicePrivateKey, tx);184    const result = getCreateCollectionResult(events);185186    // Get number of collections after the transaction187    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);188189    // Get the collection190    const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();191192    // What to expect193    // tslint:disable-next-line:no-unused-expression194    expect(result.success).to.be.true;195    expect(result.collectionId).to.be.equal(BcollectionCount);196    // tslint:disable-next-line:no-unused-expression197    expect(collection).to.be.not.null;198    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');199    expect(collection.Owner).to.be.equal(alicesPublicKey);200    expect(utf16ToStr(collection.Name)).to.be.equal(name);201    expect(utf16ToStr(collection.Description)).to.be.equal(description);202    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);203204    collectionId = result.collectionId;205  });206207  return collectionId;208}209210export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {211  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};212213  let modeprm = {};214  if (mode.type === 'NFT') {215    modeprm = {nft: null};216  } else if (mode.type === 'Fungible') {217    modeprm = {fungible: mode.decimalPoints};218  } else if (mode.type === 'ReFungible') {219    modeprm = {refungible: mode.decimalPoints};220  } else if (mode.type === 'Invalid') {221    modeprm = {invalid: null};222  }223224  await usingApi(async (api) => {225    // Get number of collections before the transaction226    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());227228    // Run the CreateCollection transaction229    const alicePrivateKey = privateKey('//Alice');230    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);231    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;232    const result = getCreateCollectionResult(events);233234    // Get number of collections after the transaction235    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());236237    // What to expect238    // tslint:disable-next-line:no-unused-expression239    expect(result.success).to.be.false;240    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');241  });242}243244export async function findUnusedAddress(api: ApiPromise): Promise<IKeyringPair> {245  let bal = new BigNumber(0);246  let unused;247  do {248    const randomSeed = 'seed' +  Math.floor(Math.random() * Math.floor(10000));249    const keyring = new Keyring({ type: 'sr25519' });250    unused = keyring.addFromUri(`//${randomSeed}`);251    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());252  } while (bal.toFixed() != '0');253  return unused;254}255256function getDestroyResult(events: EventRecord[]): boolean {257  let success: boolean = false;258  events.forEach(({ phase, event: { data, method, section } }) => {259    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);260    if (method == 'ExtrinsicSuccess') {261      success = true;262    }263  });264  return success;265}266267export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {268  await usingApi(async (api) => {269    // Run the DestroyCollection transaction270    const alicePrivateKey = privateKey(senderSeed);271    const tx = api.tx.nft.destroyCollection(collectionId);272    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;273  });274}275276export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {277  await usingApi(async (api) => {278    // Run the DestroyCollection transaction279    const alicePrivateKey = privateKey(senderSeed);280    const tx = api.tx.nft.destroyCollection(collectionId);281    const events = await submitTransactionAsync(alicePrivateKey, tx);282    const result = getDestroyResult(events);283284    // Get the collection285    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();286287    // What to expect288    expect(result).to.be.true;289    expect(collection).to.be.not.null;290    expect(collection.Owner).to.be.equal(nullPublicKey);291  });292}293294export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {295  await usingApi(async (api) => {296297    // Run the transaction298    const alicePrivateKey = privateKey('//Alice');299    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);300    const events = await submitTransactionAsync(alicePrivateKey, tx);301    const result = getGenericResult(events);302303    // Get the collection304    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();305306    // What to expect307    expect(result.success).to.be.true;308    expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());309    expect(collection.SponsorConfirmed).to.be.false;310  });311}312313export async function removeCollectionSponsorExpectSuccess(collectionId: number) {314  await usingApi(async (api) => {315316    // Run the transaction317    const alicePrivateKey = privateKey('//Alice');318    const tx = api.tx.nft.removeCollectionSponsor(collectionId);319    const events = await submitTransactionAsync(alicePrivateKey, tx);320    const result = getGenericResult(events);321322    // Get the collection323    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();324325    // What to expect326    expect(result.success).to.be.true;327    expect(collection.Sponsor).to.be.equal(nullPublicKey);328    expect(collection.SponsorConfirmed).to.be.false;329  });330}331332export async function removeCollectionSponsorExpectFailure(collectionId: number) {333  await usingApi(async (api) => {334335    // Run the transaction336    const alicePrivateKey = privateKey('//Alice');337    const tx = api.tx.nft.removeCollectionSponsor(collectionId);338    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;339  });340}341342export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {343  await usingApi(async (api) => {344345    // Run the transaction346    const alicePrivateKey = privateKey(senderSeed);347    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);348    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;349  });350}351352export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {353  await usingApi(async (api) => {354355    // Run the transaction356    const sender = privateKey(senderSeed);357    const tx = api.tx.nft.confirmSponsorship(collectionId);358    const events = await submitTransactionAsync(sender, tx);359    const result = getGenericResult(events);360361    // Get the collection362    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();363364    // What to expect365    expect(result.success).to.be.true;366    expect(collection.Sponsor).to.be.equal(sender.address);367    expect(collection.SponsorConfirmed).to.be.true;368  });369}370371export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {372  await usingApi(async (api) => {373374    // Run the transaction375    const sender = privateKey(senderSeed);376    const tx = api.tx.nft.confirmSponsorship(collectionId);377    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;378  });379}380381export interface CreateFungibleData extends Struct {382  readonly value: u128;383}384385export interface CreateReFungibleData extends Struct {}386export interface CreateNftData extends Struct {}387388export interface CreateItemData extends Enum {389  NFT: CreateNftData;390  Fungible: CreateFungibleData;391  ReFungible: CreateReFungibleData;392}393394export async function395approveExpectSuccess(collectionId: number,396                     tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number = 1) {397  await usingApi(async (api: ApiPromise) => {398    const allowanceBefore =399      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;400    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);401    const events = await submitTransactionAsync(owner, approveNftTx);402    const result = getCreateItemResult(events);403    // tslint:disable-next-line:no-unused-expression404    expect(result.success).to.be.true;405    const allowanceAfter =406      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;407    expect(allowanceAfter.toNumber() - allowanceBefore.toNumber()).to.be.equal(amount);408  });409}410411export async function412transferFromExpectSuccess(collectionId: number,413                          tokenId: number,414                          accountApproved: IKeyringPair,415                          accountFrom: IKeyringPair,416                          accountTo: IKeyringPair,417                          value: number = 1,418                          type: string = 'NFT') {419  await usingApi(async (api: ApiPromise) => {420    let balanceBefore = new BN(0);421    if (type === 'Fungible') {422      balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;423    }424    const transferFromTx = await api.tx.nft.transferFrom(425      accountFrom.address, accountTo.address, collectionId, tokenId, value);426    const events = await submitTransactionAsync(accountFrom, transferFromTx);427    const result = getCreateItemResult(events);428    // tslint:disable-next-line:no-unused-expression429    expect(result.success).to.be.true;430    if (type === 'NFT') {431      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;432      expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);433    }434    if (type === 'Fungible') {435      const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;436      expect(balanceAfter.sub(balanceBefore).toNumber()).to.be.equal(value);437    }438    if (type === 'ReFungible') {439      const nftItemData =440        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;441      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);442      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);443    }444  });445}446447export async function448transferFromExpectFail(collectionId: number,449                       tokenId: number,450                       accountApproved: IKeyringPair,451                       accountFrom: IKeyringPair,452                       accountTo: IKeyringPair,453                       value: number = 1) {454  await usingApi(async (api: ApiPromise) => {455    const transferFromTx = await api.tx.nft.transferFrom(456      accountFrom.address, accountTo.address, collectionId, tokenId, value);457    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;458    const result = getCreateCollectionResult(events);459    // tslint:disable-next-line:no-unused-expression460    expect(result.success).to.be.false;461  });462}463464export async function465approveExpectFail(collectionId: number,466                  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number = 1) {467  await usingApi(async (api: ApiPromise) => {468    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);469    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;470    const result = getCreateCollectionResult(events);471    // tslint:disable-next-line:no-unused-expression472    expect(result.success).to.be.false;473  });474}475476export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {477  let newItemId: number = 0;478  await usingApi(async (api) => {479    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);480    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();481    const AItemBalance = new BigNumber(Aitem.Value);482483    if (owner === '') {484      owner = sender.address;485    }486487    let tx;488    if (createMode === 'Fungible') {489      const createData = {fungible: {value: 10}};490      tx = api.tx.nft.createItem(collectionId, owner, createData);491    } else {492      tx = api.tx.nft.createItem(collectionId, owner, createMode);493    }494    const events = await submitTransactionAsync(sender, tx);495    const result = getCreateItemResult(events);496497    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);498    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();499    const BItemBalance = new BigNumber(Bitem.Value);500501    // What to expect502    // tslint:disable-next-line:no-unused-expression503    expect(result.success).to.be.true;504    if (createMode === 'Fungible') {505      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);506    } else {507      expect(BItemCount).to.be.equal(AItemCount + 1);508    }509    expect(collectionId).to.be.equal(result.collectionId);510    expect(BItemCount).to.be.equal(result.itemId);511    newItemId = result.itemId;512  });513  return newItemId;514}515516export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {517  await usingApi(async (api) => {518519    // Run the transaction520    const tx = api.tx.nft.setPublicAccessMode(collectionId, 'WhiteList');521    const events = await submitTransactionAsync(sender, tx);522    const result = getGenericResult(events);523524    // Get the collection525    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();526527    // What to expect528    expect(result.success).to.be.true;529    expect(collection.Access).to.be.equal('WhiteList');530  });531}532533export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {534  await usingApi(async (api) => {535536    // Run the transaction537    const tx = api.tx.nft.setMintPermission(collectionId, true);538    const events = await submitTransactionAsync(sender, tx);539    const result = getGenericResult(events);540541    // Get the collection542    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();543544    // What to expect545    expect(result.success).to.be.true;546    expect(collection.MintMode).to.be.equal(true);547  });548}549550export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {551  await usingApi(async (api) => {552553    // Run the transaction554    const tx = api.tx.nft.addToWhiteList(collectionId, address);555    const events = await submitTransactionAsync(sender, tx);556    const result = getGenericResult(events);557558    // Get the collection559    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();560561    // What to expect562    expect(result.success).to.be.true;563    expect(collection.MintMode).to.be.equal(true);564  });565}566567export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)568  : Promise<ICollectionInterface | null> => {569  return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;570};571572export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {573  // set global object - collectionsCount574  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();575};