git.delta.rocks / unique-network / refs/commits / 800a78ff8f6e

difftreelog

Merge pull request #95 from usetech-llc/feature/transfer-load

Greg Zaitsev2021-02-11parents: #96983dc #0219ca5.patch.diff
in: master
Transfer load testing

3 files changed

modifiedtests/package.jsondiffbeforeafterboth
--- a/tests/package.json
+++ b/tests/package.json
@@ -20,6 +20,7 @@
   "scripts": {
     "test": "mocha --timeout 9999999 -r ts-node/register ./**/*.test.ts",
     "load": "mocha --timeout 9999999 -r ts-node/register ./**/*.load.ts",
+    "loadTransfer": "ts-node src/transfer.nload.ts",
     "testAddCollectionAdmin": "mocha --timeout 9999999 -r ts-node/register ./**/addCollectionAdmin.test.ts",
     "testSetSchemaVersion": "mocha --timeout 9999999 -r ts-node/register ./**/setSchemaVersion.test.ts",
     "testSetVariableMetaData": "mocha --timeout 9999999 -r ts-node/register ./**/setVariableMetaData.test.ts",
addedtests/src/transfer.nload.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/transfer.nload.ts
@@ -0,0 +1,113 @@
+import { ApiPromise } from "@polkadot/api";
+import { IKeyringPair } from '@polkadot/types/types';
+import privateKey from "./substrate/privateKey";
+import usingApi, { submitTransactionAsync } from "./substrate/substrate-api";
+import waitNewBlocks from "./substrate/wait-new-blocks";
+import { findUnusedAddresses } from "./util/helpers";
+import * as cluster from 'cluster';
+import os from 'os';
+
+// Innacurate transfer fee
+const FEE = 10n ** 8n;
+
+let counters: { [key: string]: number } = {};
+function increaseCounter(name: string, amount: number) {
+    if (!counters[name]) {
+        counters[name] = 0;
+    }
+    counters[name] += amount;
+}
+function flushCounterToMaster() {
+    if (Object.keys(counters).length === 0) {
+        return;
+    }
+    process.send!(counters);
+    counters = {};
+}
+
+async function distributeBalance(source: IKeyringPair, api: ApiPromise, totalAmount: bigint, stages: number) {
+    let accounts = [source];
+    // we don't need source in output array
+    const failedAccounts = [0];
+
+    const finalUserAmount = 2 ** stages - 1;
+    accounts.push(...await findUnusedAddresses(api, finalUserAmount));
+    // findUnusedAddresses produces at least 1 request per user
+    increaseCounter('requests', finalUserAmount);
+
+    for (let stage = 0; stage < stages; stage++) {
+        let usersWithBalance = 2 ** stage;
+        let amount = totalAmount / (2n ** BigInt(stage)) - FEE * BigInt(stage);
+        // console.log(`Stage ${stage}/${stages}, ${usersWithBalance} => ${usersWithBalance * 2} = ${amount}`);
+        let txs = [];
+        for (let i = 0; i < usersWithBalance; i++) {
+            let newUser = accounts[i + usersWithBalance];
+            // console.log(`${accounts[i].address} => ${newUser.address} = ${amountToSplit}`);
+            const tx = api.tx.balances.transfer(newUser.address, amount);
+            txs.push(submitTransactionAsync(accounts[i], tx).catch(e => {
+                failedAccounts.push(i + usersWithBalance);
+                increaseCounter('txFailed', 1);
+            }));
+            increaseCounter('tx', 1);
+        }
+        await Promise.all(txs);
+    }
+
+    for (let account of failedAccounts.reverse()) {
+        accounts.splice(account, 1);
+    }
+    return accounts;
+}
+
+if (cluster.isMaster) {
+    let testDone = false;
+    usingApi(async (api) => {
+        let prevCounters: { [key: string]: number } = {};
+        while (!testDone) {
+            for (let name in counters) {
+                if (!(name in prevCounters)) {
+                    prevCounters[name] = 0;
+                }
+                if(counters[name] === prevCounters[name]) {
+                    continue;
+                }
+                console.log(`${name.padEnd(15)} = ${counters[name] - prevCounters[name]}`);
+                prevCounters[name] = counters[name];
+            }
+            await waitNewBlocks(api, 1);
+        }
+    });
+    let waiting: Promise<void>[] = [];
+    console.log(`Starting ${os.cpus().length} workers`);
+    usingApi(async (api) => {
+        const alice = privateKey('//Alice');
+        for (let id in os.cpus()) {
+            const WORKER_NAME = `//LoadWorker${id}_${Date.now()}`;
+            const workerAccount = privateKey(WORKER_NAME);
+            const tx = api.tx.balances.transfer(workerAccount.address, 400n * 10n ** 23n);
+            await submitTransactionAsync(alice, tx);
+
+            let worker = cluster.fork({
+                WORKER_NAME,
+                STAGES: id + 2
+            });
+            worker.on('message', msg => {
+                for (let key in msg) {
+                    increaseCounter(key, msg[key]);
+                }
+            });
+            waiting.push(new Promise(res => worker.on('exit', res)));
+        }
+        await Promise.all(waiting);
+        testDone = true;
+    })
+} else {
+    increaseCounter('startedWorkers', 1);
+    usingApi(async (api) => {
+        await distributeBalance(privateKey(process.env.WORKER_NAME as string), api, 400n * 10n ** 22n, 10);
+    });
+    const interval = setInterval(() => {
+        flushCounterToMaster();
+    }, 100);
+    interval.unref();
+}
\ No newline at end of file
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 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}5354export interface 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}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: null};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: null};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}240241export async function findNotExistingCollection(api: ApiPromise): Promise<number> {242  const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;243  const newCollection: number = totalNumber + 1;244  return newCollection;245}246247function getDestroyResult(events: EventRecord[]): boolean {248  let success: boolean = false;249  events.forEach(({ phase, event: { data, method, section } }) => {250    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);251    if (method == 'ExtrinsicSuccess') {252      success = true;253    }254  });255  return success;256}257258export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {259  await usingApi(async (api) => {260    // Run the DestroyCollection transaction261    const alicePrivateKey = privateKey(senderSeed);262    const tx = api.tx.nft.destroyCollection(collectionId);263    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;264  });265}266267export async function destroyCollectionExpectSuccess(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    const events = await submitTransactionAsync(alicePrivateKey, tx);273    const result = getDestroyResult(events);274275    // Get the collection276    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();277278    // What to expect279    expect(result).to.be.true;280    expect(collection).to.be.not.null;281    expect(collection.Owner).to.be.equal(nullPublicKey);282  });283}284285export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {286  await usingApi(async (api) => {287288    // Run the transaction289    const alicePrivateKey = privateKey('//Alice');290    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);291    const events = await submitTransactionAsync(alicePrivateKey, tx);292    const result = getGenericResult(events);293294    // Get the collection295    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();296297    // What to expect298    expect(result.success).to.be.true;299    expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());300    expect(collection.SponsorConfirmed).to.be.false;301  });302}303304export async function removeCollectionSponsorExpectSuccess(collectionId: number) {305  await usingApi(async (api) => {306307    // Run the transaction308    const alicePrivateKey = privateKey('//Alice');309    const tx = api.tx.nft.removeCollectionSponsor(collectionId);310    const events = await submitTransactionAsync(alicePrivateKey, tx);311    const result = getGenericResult(events);312313    // Get the collection314    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();315316    // What to expect317    expect(result.success).to.be.true;318    expect(collection.Sponsor).to.be.equal(nullPublicKey);319    expect(collection.SponsorConfirmed).to.be.false;320  });321}322323export async function removeCollectionSponsorExpectFailure(collectionId: number) {324  await usingApi(async (api) => {325326    // Run the transaction327    const alicePrivateKey = privateKey('//Alice');328    const tx = api.tx.nft.removeCollectionSponsor(collectionId);329    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;330  });331}332333export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {334  await usingApi(async (api) => {335336    // Run the transaction337    const alicePrivateKey = privateKey(senderSeed);338    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);339    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;340  });341}342343export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {344  await usingApi(async (api) => {345346    // Run the transaction347    const sender = privateKey(senderSeed);348    const tx = api.tx.nft.confirmSponsorship(collectionId);349    const events = await submitTransactionAsync(sender, tx);350    const result = getGenericResult(events);351352    // Get the collection353    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();354355    // What to expect356    expect(result.success).to.be.true;357    expect(collection.Sponsor).to.be.equal(sender.address);358    expect(collection.SponsorConfirmed).to.be.true;359  });360}361362363export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {364  await usingApi(async (api) => {365366    // Run the transaction367    const sender = privateKey(senderSeed);368    const tx = api.tx.nft.confirmSponsorship(collectionId);369    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;370  });371}372373export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {374  await usingApi(async (api) => {375    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);376    const events = await submitTransactionAsync(sender, tx);377    const result = getGenericResult(events);378379    expect(result.success).to.be.true;380  });381}382383export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {384  await usingApi(async (api) => {385    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);386    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;387    const result = getGenericResult(events);388389    expect(result.success).to.be.false;390  });391}392393export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {394  await usingApi(async (api) => {395    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);396    const events = await submitTransactionAsync(sender, tx);397    const result = getGenericResult(events);398399    expect(result.success).to.be.true;400  });401}402403export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {404  await usingApi(async (api) => {405    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);406    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;407    const result = getGenericResult(events);408409    expect(result.success).to.be.false;410  });411}412413export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {414  await usingApi(async (api) => {415    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);416    const events = await submitTransactionAsync(sender, tx);417    const result = getGenericResult(events);418419    expect(result.success).to.be.true;420  });421}422423export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {424  let whitelisted: boolean = false;425  await usingApi(async (api) => {426    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;427  });428  return whitelisted;429}430431export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {432  await usingApi(async (api) => {433    const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);434    const events = await submitTransactionAsync(sender, tx);435    const result = getGenericResult(events);436437    expect(result.success).to.be.true;438  });439}440441export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {442  await usingApi(async (api) => {443    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);444    const events = await submitTransactionAsync(sender, tx);445    const result = getGenericResult(events);446447    expect(result.success).to.be.true;448  });449}450451export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {452  await usingApi(async (api) => {453    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);454    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;455    const result = getGenericResult(events);456457    expect(result.success).to.be.false;458  });459}460461export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {462  await usingApi(async (api) => {463    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));464    const events = await submitTransactionAsync(sender, tx);465    const result = getGenericResult(events);466467    expect(result.success).to.be.true;468  });469}470471export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {472  await usingApi(async (api) => {473    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));474    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;475  });476}477478export interface CreateFungibleData extends Struct {479  readonly value: u128;480}481482export interface CreateReFungibleData extends Struct {}483export interface CreateNftData extends Struct {}484485export interface CreateItemData extends Enum {486  NFT: CreateNftData;487  Fungible: CreateFungibleData;488  ReFungible: CreateReFungibleData;489}490491export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {492  await usingApi(async (api) => {493    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);494    const events = await submitTransactionAsync(owner, tx);495    const result = getGenericResult(events);496    // Get the item497    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();498    // What to expect499    // tslint:disable-next-line:no-unused-expression500    expect(result.success).to.be.true;501    // tslint:disable-next-line:no-unused-expression502    expect(item).to.be.not.null;503    expect(item.Owner).to.be.equal(nullPublicKey);504  });505}506507export async function508approveExpectSuccess(collectionId: number,509                     tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number = 1) { //alice,bob510  await usingApi(async (api: ApiPromise) => {511    const allowanceBefore =512      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;513    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);514    const events = await submitTransactionAsync(owner, approveNftTx);515    const result = getCreateItemResult(events);516    // tslint:disable-next-line:no-unused-expression517    expect(result.success).to.be.true;518    const allowanceAfter =519      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;520    expect(allowanceAfter.toNumber() - allowanceBefore.toNumber()).to.be.equal(amount);521  });522}523524export async function525transferFromExpectSuccess(collectionId: number,526                          tokenId: number,527                          accountApproved: IKeyringPair, //bob528                          accountFrom: IKeyringPair, //alice529                          accountTo: IKeyringPair, //charlie530                          value: number = 1,531                          type: string = 'NFT') {532  await usingApi(async (api: ApiPromise) => {533    let balanceBefore = new BN(0);534    if (type === 'Fungible') {535      balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;536    }537    const transferFromTx = await api.tx.nft.transferFrom(538      accountFrom.address, accountTo.address, collectionId, tokenId, value);539    const events = await submitTransactionAsync(accountApproved, transferFromTx);540    const result = getCreateItemResult(events);541    // tslint:disable-next-line:no-unused-expression542    expect(result.success).to.be.true;543    if (type === 'NFT') {544      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;545      expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);546    }547    if (type === 'Fungible') {548      const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;549      expect(balanceAfter.sub(balanceBefore).toNumber()).to.be.equal(value);550    }551    if (type === 'ReFungible') {552      const nftItemData =553        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;554      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);555      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);556    }557  });558}559560export async function561transferFromExpectFail(collectionId: number,562                       tokenId: number,563                       accountApproved: IKeyringPair,564                       accountFrom: IKeyringPair,565                       accountTo: IKeyringPair,566                       value: number = 1) {567  await usingApi(async (api: ApiPromise) => {568    const transferFromTx = await api.tx.nft.transferFrom(569      accountFrom.address, accountTo.address, collectionId, tokenId, value);570    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;571    const result = getCreateCollectionResult(events);572    // tslint:disable-next-line:no-unused-expression573    expect(result.success).to.be.false;574  });575}576577export async function578transferExpectSuccess(collectionId: number,579                      tokenId: number,580                      sender: IKeyringPair,581                      recipient: IKeyringPair,582                      value: number = 1,583                      type: string = 'NFT') {584  await usingApi(async (api: ApiPromise) => {585    let balanceBefore = new BN(0);586    if (type === 'Fungible') {587      balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;588    }589    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);590    const events = await submitTransactionAsync(sender, transferTx);591    const result = getCreateItemResult(events);592    // tslint:disable-next-line:no-unused-expression593    expect(result.success).to.be.true;594    if (type === 'NFT') {595      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;596      expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);597    }598    if (type === 'Fungible') {599      const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;600      expect(balanceAfter.sub(balanceBefore).toNumber()).to.be.equal(value);601    }602    if (type === 'ReFungible') {603      const nftItemData =604        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;605      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);606      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);607    }608  });609}610611export async function612transferExpectFail(collectionId: number,613                   tokenId: number,614                   sender: IKeyringPair,615                   recipient: IKeyringPair,616                   value: number = 1,617                   type: string = 'NFT') {618  await usingApi(async (api: ApiPromise) => {619    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);620    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;621    if (events && Array.isArray(events)) {622      const result = getCreateCollectionResult(events);623      // tslint:disable-next-line:no-unused-expression624      expect(result.success).to.be.false;625    }626  });627}628629export async function630approveExpectFail(collectionId: number,631                  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number = 1) {632  await usingApi(async (api: ApiPromise) => {633    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);634    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;635    const result = getCreateCollectionResult(events);636    // tslint:disable-next-line:no-unused-expression637    expect(result.success).to.be.false;638  });639}640641export async function createItemExpectSuccess(642  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {643  let newItemId: number = 0;644  await usingApi(async (api) => {645    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);646    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();647    const AItemBalance = new BigNumber(Aitem.Value);648649    if (owner === '') {650      owner = sender.address;651    }652653    let tx;654    if (createMode === 'Fungible') {655      const createData = {fungible: {value: 10}};656      tx = api.tx.nft.createItem(collectionId, owner, createData);657    } else if (createMode === 'ReFungible') {658      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};659      tx = api.tx.nft.createItem(collectionId, owner, createData);660    } else {661      tx = api.tx.nft.createItem(collectionId, owner, createMode);662    }663    const events = await submitTransactionAsync(sender, tx);664    const result = getCreateItemResult(events);665666    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);667    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();668    const BItemBalance = new BigNumber(Bitem.Value);669670    // What to expect671    // tslint:disable-next-line:no-unused-expression672    expect(result.success).to.be.true;673    if (createMode === 'Fungible') {674      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);675    } else {676      expect(BItemCount).to.be.equal(AItemCount + 1);677    }678    expect(collectionId).to.be.equal(result.collectionId);679    expect(BItemCount).to.be.equal(result.itemId);680    newItemId = result.itemId;681  });682  return newItemId;683}684685export async function createItemExpectFailure(686  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {687  await usingApi(async (api) => {688    const tx = api.tx.nft.createItem(collectionId, owner, createMode);689    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;690    const result = getCreateItemResult(events);691692    expect(result.success).to.be.false;693  });694}695696export async function setPublicAccessModeExpectSuccess(697  sender: IKeyringPair, collectionId: number,698  accessMode: 'Normal' | 'WhiteList',699) {700  await usingApi(async (api) => {701702    // Run the transaction703    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);704    const events = await submitTransactionAsync(sender, tx);705    const result = getGenericResult(events);706707    // Get the collection708    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();709710    // What to expect711    // tslint:disable-next-line:no-unused-expression712    expect(result.success).to.be.true;713    expect(collection.Access).to.be.equal(accessMode);714  });715}716717export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {718  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');719}720721export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {722  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');723}724725export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {726  await usingApi(async (api) => {727728    // Run the transaction729    const tx = api.tx.nft.setMintPermission(collectionId, enabled);730    const events = await submitTransactionAsync(sender, tx);731    const result = getGenericResult(events);732733    // Get the collection734    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();735736    // What to expect737    // tslint:disable-next-line:no-unused-expression738    expect(result.success).to.be.true;739    expect(collection.MintMode).to.be.equal(enabled);740  });741}742743export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {744  await setMintPermissionExpectSuccess(sender, collectionId, true);745}746747export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {748  await usingApi(async (api) => {749    // Run the transaction750    const tx = api.tx.nft.setMintPermission(collectionId, enabled);751    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;752    const result = getCreateCollectionResult(events);753    // tslint:disable-next-line:no-unused-expression754    expect(result.success).to.be.false;755  });756}757758export async function isWhitelisted(collectionId: number, address: string) {759  let whitelisted: boolean = false;760  await usingApi(async (api) => {761    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;762  });763  return whitelisted;764}765766export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {767  await usingApi(async (api) => {768769    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();770771    // Run the transaction772    const tx = api.tx.nft.addToWhiteList(collectionId, address);773    const events = await submitTransactionAsync(sender, tx);774    const result = getGenericResult(events);775776    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();777778    // What to expect779    // tslint:disable-next-line:no-unused-expression780    expect(result.success).to.be.true;781    // tslint:disable-next-line: no-unused-expression782    expect(whiteListedBefore).to.be.false;783    // tslint:disable-next-line: no-unused-expression784    expect(whiteListedAfter).to.be.true;785  });786}787788export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {789  await usingApi(async (api) => {790    // Run the transaction791    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);792    const events = await submitTransactionAsync(sender, tx);793    const result = getGenericResult(events);794795    // What to expect796    // tslint:disable-next-line:no-unused-expression797    expect(result.success).to.be.true;798  });799}800801export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {802  await usingApi(async (api) => {803    // Run the transaction804    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);805    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;806    const result = getGenericResult(events);807808    // What to expect809    // tslint:disable-next-line:no-unused-expression810    expect(result.success).to.be.false;811  });812}813814export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)815  : Promise<ICollectionInterface | null> => {816  return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;817};818819export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {820  // set global object - collectionsCount821  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();822};
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}5354export interface 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}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: null};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: null};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, seedAddition = ''): Promise<IKeyringPair> {230  let bal = new BigNumber(0);231  let unused;232  do {233    const randomSeed = 'seed' +  Math.floor(Math.random() * Math.floor(10000)) + seedAddition;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}240241export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {242  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));243}244245export async function findNotExistingCollection(api: ApiPromise): Promise<number> {246  const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;247  const newCollection: number = totalNumber + 1;248  return newCollection;249}250251function getDestroyResult(events: EventRecord[]): boolean {252  let success: boolean = false;253  events.forEach(({ phase, event: { data, method, section } }) => {254    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);255    if (method == 'ExtrinsicSuccess') {256      success = true;257    }258  });259  return success;260}261262export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {263  await usingApi(async (api) => {264    // Run the DestroyCollection transaction265    const alicePrivateKey = privateKey(senderSeed);266    const tx = api.tx.nft.destroyCollection(collectionId);267    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;268  });269}270271export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {272  await usingApi(async (api) => {273    // Run the DestroyCollection transaction274    const alicePrivateKey = privateKey(senderSeed);275    const tx = api.tx.nft.destroyCollection(collectionId);276    const events = await submitTransactionAsync(alicePrivateKey, tx);277    const result = getDestroyResult(events);278279    // Get the collection280    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();281282    // What to expect283    expect(result).to.be.true;284    expect(collection).to.be.not.null;285    expect(collection.Owner).to.be.equal(nullPublicKey);286  });287}288289export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {290  await usingApi(async (api) => {291292    // Run the transaction293    const alicePrivateKey = privateKey('//Alice');294    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);295    const events = await submitTransactionAsync(alicePrivateKey, tx);296    const result = getGenericResult(events);297298    // Get the collection299    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();300301    // What to expect302    expect(result.success).to.be.true;303    expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());304    expect(collection.SponsorConfirmed).to.be.false;305  });306}307308export async function removeCollectionSponsorExpectSuccess(collectionId: number) {309  await usingApi(async (api) => {310311    // Run the transaction312    const alicePrivateKey = privateKey('//Alice');313    const tx = api.tx.nft.removeCollectionSponsor(collectionId);314    const events = await submitTransactionAsync(alicePrivateKey, tx);315    const result = getGenericResult(events);316317    // Get the collection318    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();319320    // What to expect321    expect(result.success).to.be.true;322    expect(collection.Sponsor).to.be.equal(nullPublicKey);323    expect(collection.SponsorConfirmed).to.be.false;324  });325}326327export async function removeCollectionSponsorExpectFailure(collectionId: number) {328  await usingApi(async (api) => {329330    // Run the transaction331    const alicePrivateKey = privateKey('//Alice');332    const tx = api.tx.nft.removeCollectionSponsor(collectionId);333    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;334  });335}336337export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {338  await usingApi(async (api) => {339340    // Run the transaction341    const alicePrivateKey = privateKey(senderSeed);342    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);343    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;344  });345}346347export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {348  await usingApi(async (api) => {349350    // Run the transaction351    const sender = privateKey(senderSeed);352    const tx = api.tx.nft.confirmSponsorship(collectionId);353    const events = await submitTransactionAsync(sender, tx);354    const result = getGenericResult(events);355356    // Get the collection357    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();358359    // What to expect360    expect(result.success).to.be.true;361    expect(collection.Sponsor).to.be.equal(sender.address);362    expect(collection.SponsorConfirmed).to.be.true;363  });364}365366367export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {368  await usingApi(async (api) => {369370    // Run the transaction371    const sender = privateKey(senderSeed);372    const tx = api.tx.nft.confirmSponsorship(collectionId);373    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;374  });375}376377export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {378  await usingApi(async (api) => {379    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);380    const events = await submitTransactionAsync(sender, tx);381    const result = getGenericResult(events);382383    expect(result.success).to.be.true;384  });385}386387export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {388  await usingApi(async (api) => {389    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);390    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;391    const result = getGenericResult(events);392393    expect(result.success).to.be.false;394  });395}396397export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {398  await usingApi(async (api) => {399    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);400    const events = await submitTransactionAsync(sender, tx);401    const result = getGenericResult(events);402403    expect(result.success).to.be.true;404  });405}406407export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {408  await usingApi(async (api) => {409    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);410    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;411    const result = getGenericResult(events);412413    expect(result.success).to.be.false;414  });415}416417export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {418  await usingApi(async (api) => {419    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);420    const events = await submitTransactionAsync(sender, tx);421    const result = getGenericResult(events);422423    expect(result.success).to.be.true;424  });425}426427export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {428  let whitelisted: boolean = false;429  await usingApi(async (api) => {430    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;431  });432  return whitelisted;433}434435export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {436  await usingApi(async (api) => {437    const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);438    const events = await submitTransactionAsync(sender, tx);439    const result = getGenericResult(events);440441    expect(result.success).to.be.true;442  });443}444445export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {446  await usingApi(async (api) => {447    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);448    const events = await submitTransactionAsync(sender, tx);449    const result = getGenericResult(events);450451    expect(result.success).to.be.true;452  });453}454455export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {456  await usingApi(async (api) => {457    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);458    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;459    const result = getGenericResult(events);460461    expect(result.success).to.be.false;462  });463}464465export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {466  await usingApi(async (api) => {467    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));468    const events = await submitTransactionAsync(sender, tx);469    const result = getGenericResult(events);470471    expect(result.success).to.be.true;472  });473}474475export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {476  await usingApi(async (api) => {477    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));478    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;479  });480}481482export interface CreateFungibleData extends Struct {483  readonly value: u128;484}485486export interface CreateReFungibleData extends Struct {}487export interface CreateNftData extends Struct {}488489export interface CreateItemData extends Enum {490  NFT: CreateNftData;491  Fungible: CreateFungibleData;492  ReFungible: CreateReFungibleData;493}494495export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {496  await usingApi(async (api) => {497    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);498    const events = await submitTransactionAsync(owner, tx);499    const result = getGenericResult(events);500    // Get the item501    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();502    // What to expect503    // tslint:disable-next-line:no-unused-expression504    expect(result.success).to.be.true;505    // tslint:disable-next-line:no-unused-expression506    expect(item).to.be.not.null;507    expect(item.Owner).to.be.equal(nullPublicKey);508  });509}510511export async function512approveExpectSuccess(collectionId: number,513                     tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number = 1) { //alice,bob514  await usingApi(async (api: ApiPromise) => {515    const allowanceBefore =516      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;517    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);518    const events = await submitTransactionAsync(owner, approveNftTx);519    const result = getCreateItemResult(events);520    // tslint:disable-next-line:no-unused-expression521    expect(result.success).to.be.true;522    const allowanceAfter =523      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;524    expect(allowanceAfter.toNumber() - allowanceBefore.toNumber()).to.be.equal(amount);525  });526}527528export async function529transferFromExpectSuccess(collectionId: number,530                          tokenId: number,531                          accountApproved: IKeyringPair, //bob532                          accountFrom: IKeyringPair, //alice533                          accountTo: IKeyringPair, //charlie534                          value: number = 1,535                          type: string = 'NFT') {536  await usingApi(async (api: ApiPromise) => {537    let balanceBefore = new BN(0);538    if (type === 'Fungible') {539      balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;540    }541    const transferFromTx = await api.tx.nft.transferFrom(542      accountFrom.address, accountTo.address, collectionId, tokenId, value);543    const events = await submitTransactionAsync(accountApproved, transferFromTx);544    const result = getCreateItemResult(events);545    // tslint:disable-next-line:no-unused-expression546    expect(result.success).to.be.true;547    if (type === 'NFT') {548      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;549      expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);550    }551    if (type === 'Fungible') {552      const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;553      expect(balanceAfter.sub(balanceBefore).toNumber()).to.be.equal(value);554    }555    if (type === 'ReFungible') {556      const nftItemData =557        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;558      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);559      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);560    }561  });562}563564export async function565transferFromExpectFail(collectionId: number,566                       tokenId: number,567                       accountApproved: IKeyringPair,568                       accountFrom: IKeyringPair,569                       accountTo: IKeyringPair,570                       value: number = 1) {571  await usingApi(async (api: ApiPromise) => {572    const transferFromTx = await api.tx.nft.transferFrom(573      accountFrom.address, accountTo.address, collectionId, tokenId, value);574    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;575    const result = getCreateCollectionResult(events);576    // tslint:disable-next-line:no-unused-expression577    expect(result.success).to.be.false;578  });579}580581export async function582transferExpectSuccess(collectionId: number,583                      tokenId: number,584                      sender: IKeyringPair,585                      recipient: IKeyringPair,586                      value: number = 1,587                      type: string = 'NFT') {588  await usingApi(async (api: ApiPromise) => {589    let balanceBefore = new BN(0);590    if (type === 'Fungible') {591      balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;592    }593    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);594    const events = await submitTransactionAsync(sender, transferTx);595    const result = getCreateItemResult(events);596    // tslint:disable-next-line:no-unused-expression597    expect(result.success).to.be.true;598    if (type === 'NFT') {599      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;600      expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);601    }602    if (type === 'Fungible') {603      const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;604      expect(balanceAfter.sub(balanceBefore).toNumber()).to.be.equal(value);605    }606    if (type === 'ReFungible') {607      const nftItemData =608        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;609      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);610      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);611    }612  });613}614615export async function616transferExpectFail(collectionId: number,617                   tokenId: number,618                   sender: IKeyringPair,619                   recipient: IKeyringPair,620                   value: number = 1,621                   type: string = 'NFT') {622  await usingApi(async (api: ApiPromise) => {623    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);624    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;625    if (events && Array.isArray(events)) {626      const result = getCreateCollectionResult(events);627      // tslint:disable-next-line:no-unused-expression628      expect(result.success).to.be.false;629    }630  });631}632633export async function634approveExpectFail(collectionId: number,635                  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number = 1) {636  await usingApi(async (api: ApiPromise) => {637    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);638    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;639    const result = getCreateCollectionResult(events);640    // tslint:disable-next-line:no-unused-expression641    expect(result.success).to.be.false;642  });643}644645export async function createItemExpectSuccess(646  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {647  let newItemId: number = 0;648  await usingApi(async (api) => {649    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);650    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();651    const AItemBalance = new BigNumber(Aitem.Value);652653    if (owner === '') {654      owner = sender.address;655    }656657    let tx;658    if (createMode === 'Fungible') {659      const createData = {fungible: {value: 10}};660      tx = api.tx.nft.createItem(collectionId, owner, createData);661    } else if (createMode === 'ReFungible') {662      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};663      tx = api.tx.nft.createItem(collectionId, owner, createData);664    } else {665      tx = api.tx.nft.createItem(collectionId, owner, createMode);666    }667    const events = await submitTransactionAsync(sender, tx);668    const result = getCreateItemResult(events);669670    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);671    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();672    const BItemBalance = new BigNumber(Bitem.Value);673674    // What to expect675    // tslint:disable-next-line:no-unused-expression676    expect(result.success).to.be.true;677    if (createMode === 'Fungible') {678      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);679    } else {680      expect(BItemCount).to.be.equal(AItemCount + 1);681    }682    expect(collectionId).to.be.equal(result.collectionId);683    expect(BItemCount).to.be.equal(result.itemId);684    newItemId = result.itemId;685  });686  return newItemId;687}688689export async function createItemExpectFailure(690  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {691  await usingApi(async (api) => {692    const tx = api.tx.nft.createItem(collectionId, owner, createMode);693    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;694    const result = getCreateItemResult(events);695696    expect(result.success).to.be.false;697  });698}699700export async function setPublicAccessModeExpectSuccess(701  sender: IKeyringPair, collectionId: number,702  accessMode: 'Normal' | 'WhiteList',703) {704  await usingApi(async (api) => {705706    // Run the transaction707    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);708    const events = await submitTransactionAsync(sender, tx);709    const result = getGenericResult(events);710711    // Get the collection712    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();713714    // What to expect715    // tslint:disable-next-line:no-unused-expression716    expect(result.success).to.be.true;717    expect(collection.Access).to.be.equal(accessMode);718  });719}720721export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {722  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');723}724725export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {726  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');727}728729export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {730  await usingApi(async (api) => {731732    // Run the transaction733    const tx = api.tx.nft.setMintPermission(collectionId, enabled);734    const events = await submitTransactionAsync(sender, tx);735    const result = getGenericResult(events);736737    // Get the collection738    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();739740    // What to expect741    // tslint:disable-next-line:no-unused-expression742    expect(result.success).to.be.true;743    expect(collection.MintMode).to.be.equal(enabled);744  });745}746747export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {748  await setMintPermissionExpectSuccess(sender, collectionId, true);749}750751export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {752  await usingApi(async (api) => {753    // Run the transaction754    const tx = api.tx.nft.setMintPermission(collectionId, enabled);755    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;756    const result = getCreateCollectionResult(events);757    // tslint:disable-next-line:no-unused-expression758    expect(result.success).to.be.false;759  });760}761762export async function isWhitelisted(collectionId: number, address: string) {763  let whitelisted: boolean = false;764  await usingApi(async (api) => {765    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;766  });767  return whitelisted;768}769770export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {771  await usingApi(async (api) => {772773    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();774775    // Run the transaction776    const tx = api.tx.nft.addToWhiteList(collectionId, address);777    const events = await submitTransactionAsync(sender, tx);778    const result = getGenericResult(events);779780    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();781782    // What to expect783    // tslint:disable-next-line:no-unused-expression784    expect(result.success).to.be.true;785    // tslint:disable-next-line: no-unused-expression786    expect(whiteListedBefore).to.be.false;787    // tslint:disable-next-line: no-unused-expression788    expect(whiteListedAfter).to.be.true;789  });790}791792export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {793  await usingApi(async (api) => {794    // Run the transaction795    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);796    const events = await submitTransactionAsync(sender, tx);797    const result = getGenericResult(events);798799    // What to expect800    // tslint:disable-next-line:no-unused-expression801    expect(result.success).to.be.true;802  });803}804805export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {806  await usingApi(async (api) => {807    // Run the transaction808    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);809    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;810    const result = getGenericResult(events);811812    // What to expect813    // tslint:disable-next-line:no-unused-expression814    expect(result.success).to.be.false;815  });816}817818export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)819  : Promise<ICollectionInterface | null> => {820  return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;821};822823export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {824  // set global object - collectionsCount825  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();826};