git.delta.rocks / unique-network / refs/commits / 900ad3076e16

difftreelog

tests: add transfer result parser

Yaroslav Bolyukin2021-02-17parent: #44bf7a8.patch.diff
in: master

1 file changed

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;2324export const U128_MAX = (1n << 128n) - 1n;2526type GenericResult = {27  success: boolean,28};2930interface CreateCollectionResult {31  success: boolean;32  collectionId: number;33}3435interface CreateItemResult {36  success: boolean;37  collectionId: number;38  itemId: number;39}4041interface IReFungibleOwner {42  Fraction: BN;43  Owner: number[];44}4546interface ITokenDataType {47  Owner: number[];48  ConstData: number[];49  VariableData: number[];50}5152interface IFungibleTokenDataType {53  Value: BN;54}5556export interface IReFungibleTokenDataType {57  Owner: IReFungibleOwner[];58  ConstData: number[];59  VariableData: number[];60}6162export function getGenericResult(events: EventRecord[]): GenericResult {63  const result: GenericResult = {64    success: false,65  };66  events.forEach(({ phase, event: { data, method, section } }) => {67    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);68    if (method === 'ExtrinsicSuccess') {69      result.success = true;70    }71  });72  return result;73}7475export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {76  let success = false;77  let collectionId: number = 0;78  events.forEach(({ phase, event: { data, method, section } }) => {79    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);80    if (method == 'ExtrinsicSuccess') {81      success = true;82    } else if ((section == 'nft') && (method == 'Created')) {83      collectionId = parseInt(data[0].toString());84    }85  });86  const result: CreateCollectionResult = {87    success,88    collectionId,89  };90  return result;91}9293export function getCreateItemResult(events: EventRecord[]): CreateItemResult {94  let success = false;95  let collectionId: number = 0;96  let itemId: number = 0;97  events.forEach(({ phase, event: { data, method, section } }) => {98    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);99    if (method == 'ExtrinsicSuccess') {100      success = true;101    } else if ((section == 'nft') && (method == 'ItemCreated')) {102      collectionId = parseInt(data[0].toString());103      itemId = parseInt(data[1].toString());104    }105  });106  const result: CreateItemResult = {107    success,108    collectionId,109    itemId,110  };111  return result;112}113114interface Invalid {115  type: 'Invalid';116}117118interface Nft {119  type: 'NFT';120}121122interface Fungible {123  type: 'Fungible';124  decimalPoints: number;125}126127interface ReFungible {128  type: 'ReFungible';129}130131type CollectionMode = Nft | Fungible | ReFungible | Invalid;132133export type CreateCollectionParams = {134  mode: CollectionMode,135  name: string,136  description: string,137  tokenPrefix: string,138};139140const defaultCreateCollectionParams: CreateCollectionParams = {141  description: 'description',142  mode: { type: 'NFT' },143  name: 'name',144  tokenPrefix: 'prefix',145}146147export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {148  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};149150  let collectionId: number = 0;151  await usingApi(async (api) => {152    // Get number of collections before the transaction153    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);154155    // Run the CreateCollection transaction156    const alicePrivateKey = privateKey('//Alice');157158    let modeprm = {};159    if (mode.type === 'NFT') {160      modeprm = {nft: null};161    } else if (mode.type === 'Fungible') {162      modeprm = {fungible: mode.decimalPoints};163    } else if (mode.type === 'ReFungible') {164      modeprm = {refungible: null};165    } else if (mode.type === 'Invalid') {166      modeprm = {invalid: null};167    }168169    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);170    const events = await submitTransactionAsync(alicePrivateKey, tx);171    const result = getCreateCollectionResult(events);172173    // Get number of collections after the transaction174    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);175176    // Get the collection177    const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();178179    // What to expect180    // tslint:disable-next-line:no-unused-expression181    expect(result.success).to.be.true;182    expect(result.collectionId).to.be.equal(BcollectionCount);183    // tslint:disable-next-line:no-unused-expression184    expect(collection).to.be.not.null;185    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');186    expect(collection.Owner).to.be.equal(alicesPublicKey);187    expect(utf16ToStr(collection.Name)).to.be.equal(name);188    expect(utf16ToStr(collection.Description)).to.be.equal(description);189    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);190191    collectionId = result.collectionId;192  });193194  return collectionId;195}196197export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {198  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};199200  let modeprm = {};201  if (mode.type === 'NFT') {202    modeprm = {nft: null};203  } else if (mode.type === 'Fungible') {204    modeprm = {fungible: mode.decimalPoints};205  } else if (mode.type === 'ReFungible') {206    modeprm = {refungible: null};207  } else if (mode.type === 'Invalid') {208    modeprm = {invalid: null};209  }210211  await usingApi(async (api) => {212    // Get number of collections before the transaction213    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());214215    // Run the CreateCollection transaction216    const alicePrivateKey = privateKey('//Alice');217    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);218    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;219    const result = getCreateCollectionResult(events);220221    // Get number of collections after the transaction222    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());223224    // What to expect225    // tslint:disable-next-line:no-unused-expression226    expect(result.success).to.be.false;227    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');228  });229}230231export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {232  let bal = new BigNumber(0);233  let unused;234  do {235    const randomSeed = 'seed' +  Math.floor(Math.random() * Math.floor(10000)) + seedAddition;236    const keyring = new Keyring({ type: 'sr25519' });237    unused = keyring.addFromUri(`//${randomSeed}`);238    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());239  } while (bal.toFixed() != '0');240  return unused;241}242243export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {244  return await usingApi(async (api) => {245    const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;246    return BigInt(bn.toString());247  });248}249250export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {251  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));252}253254export async function findNotExistingCollection(api: ApiPromise): Promise<number> {255  const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;256  const newCollection: number = totalNumber + 1;257  return newCollection;258}259260function getDestroyResult(events: EventRecord[]): boolean {261  let success: boolean = false;262  events.forEach(({ phase, event: { data, method, section } }) => {263    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);264    if (method == 'ExtrinsicSuccess') {265      success = true;266    }267  });268  return success;269}270271export async function destroyCollectionExpectFailure(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    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;277  });278}279280export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {281  await usingApi(async (api) => {282    // Run the DestroyCollection transaction283    const alicePrivateKey = privateKey(senderSeed);284    const tx = api.tx.nft.destroyCollection(collectionId);285    const events = await submitTransactionAsync(alicePrivateKey, tx);286    const result = getDestroyResult(events);287288    // Get the collection289    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();290291    // What to expect292    expect(result).to.be.true;293    expect(collection).to.be.not.null;294    expect(collection.Owner).to.be.equal(nullPublicKey);295  });296}297298export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {299  await usingApi(async (api) => {300301    // Run the transaction302    const alicePrivateKey = privateKey('//Alice');303    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);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.toString()).to.be.equal(sponsor.toString());313    expect(collection.SponsorConfirmed).to.be.false;314  });315}316317export async function removeCollectionSponsorExpectSuccess(collectionId: number) {318  await usingApi(async (api) => {319320    // Run the transaction321    const alicePrivateKey = privateKey('//Alice');322    const tx = api.tx.nft.removeCollectionSponsor(collectionId);323    const events = await submitTransactionAsync(alicePrivateKey, tx);324    const result = getGenericResult(events);325326    // Get the collection327    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();328329    // What to expect330    expect(result.success).to.be.true;331    expect(collection.Sponsor).to.be.equal(nullPublicKey);332    expect(collection.SponsorConfirmed).to.be.false;333  });334}335336export async function removeCollectionSponsorExpectFailure(collectionId: number) {337  await usingApi(async (api) => {338339    // Run the transaction340    const alicePrivateKey = privateKey('//Alice');341    const tx = api.tx.nft.removeCollectionSponsor(collectionId);342    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;343  });344}345346export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {347  await usingApi(async (api) => {348349    // Run the transaction350    const alicePrivateKey = privateKey(senderSeed);351    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);352    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;353  });354}355356export async function confirmSponsorshipExpectSuccess(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    const events = await submitTransactionAsync(sender, tx);363    const result = getGenericResult(events);364365    // Get the collection366    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();367368    // What to expect369    expect(result.success).to.be.true;370    expect(collection.Sponsor).to.be.equal(sender.address);371    expect(collection.SponsorConfirmed).to.be.true;372  });373}374375376export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {377  await usingApi(async (api) => {378379    // Run the transaction380    const sender = privateKey(senderSeed);381    const tx = api.tx.nft.confirmSponsorship(collectionId);382    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;383  });384}385386export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {387  await usingApi(async (api) => {388    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);389    const events = await submitTransactionAsync(sender, tx);390    const result = getGenericResult(events);391392    expect(result.success).to.be.true;393  });394}395396export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {397  await usingApi(async (api) => {398    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);399    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;400    const result = getGenericResult(events);401402    expect(result.success).to.be.false;403  });404}405406export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {407  await usingApi(async (api) => {408    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);409    const events = await submitTransactionAsync(sender, tx);410    const result = getGenericResult(events);411412    expect(result.success).to.be.true;413  });414}415416export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {417  await usingApi(async (api) => {418    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);419    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;420    const result = getGenericResult(events);421422    expect(result.success).to.be.false;423  });424}425426export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {427  await usingApi(async (api) => {428    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);429    const events = await submitTransactionAsync(sender, tx);430    const result = getGenericResult(events);431432    expect(result.success).to.be.true;433  });434}435436export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {437  let whitelisted: boolean = false;438  await usingApi(async (api) => {439    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;440  });441  return whitelisted;442}443444export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {445  await usingApi(async (api) => {446    const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);447    const events = await submitTransactionAsync(sender, tx);448    const result = getGenericResult(events);449450    expect(result.success).to.be.true;451  });452}453454export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {455  await usingApi(async (api) => {456    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);457    const events = await submitTransactionAsync(sender, tx);458    const result = getGenericResult(events);459460    expect(result.success).to.be.true;461  });462}463464export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {465  await usingApi(async (api) => {466    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);467    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;468    const result = getGenericResult(events);469470    expect(result.success).to.be.false;471  });472}473474export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {475  await usingApi(async (api) => {476    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));477    const events = await submitTransactionAsync(sender, tx);478    const result = getGenericResult(events);479480    expect(result.success).to.be.true;481  });482}483484export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {485  await usingApi(async (api) => {486    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));487    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;488  });489}490491export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {492  await usingApi(async (api) => {493    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));494    const events = await submitTransactionAsync(sender, tx);495    const result = getGenericResult(events);496497    expect(result.success).to.be.true;498  });499}500501export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {502  await usingApi(async (api) => {503    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));504    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;505  });506}507508export interface CreateFungibleData {509  readonly Value: bigint;510}511512export interface CreateReFungibleData { }513export interface CreateNftData { }514515export type CreateItemData = {516  NFT: CreateNftData;517} | {518  Fungible: CreateFungibleData;519} | {520  ReFungible: CreateReFungibleData;521};522523export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {524  await usingApi(async (api) => {525    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);526    const events = await submitTransactionAsync(owner, tx);527    const result = getGenericResult(events);528    // Get the item529    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();530    // What to expect531    // tslint:disable-next-line:no-unused-expression532    expect(result.success).to.be.true;533    // tslint:disable-next-line:no-unused-expression534    expect(item).to.be.not.null;535    expect(item.Owner).to.be.equal(nullPublicKey);536  });537}538539export async function540approveExpectSuccess(collectionId: number,541                     tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {542  await usingApi(async (api: ApiPromise) => {543    const allowanceBefore =544      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;545    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);546    const events = await submitTransactionAsync(owner, approveNftTx);547    const result = getCreateItemResult(events);548    // tslint:disable-next-line:no-unused-expression549    expect(result.success).to.be.true;550    const allowanceAfter =551      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;552    expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());553  });554}555556export async function557transferFromExpectSuccess(collectionId: number,558                          tokenId: number,559                          accountApproved: IKeyringPair,560                          accountFrom: IKeyringPair,561                          accountTo: IKeyringPair,562                          value: number | bigint = 1,563                          type: string = 'NFT') {564  await usingApi(async (api: ApiPromise) => {565    let balanceBefore = new BN(0);566    if (type === 'Fungible') {567      balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;568    }569    const transferFromTx = await api.tx.nft.transferFrom(570      accountFrom.address, accountTo.address, collectionId, tokenId, value);571    const events = await submitTransactionAsync(accountApproved, transferFromTx);572    const result = getCreateItemResult(events);573    // tslint:disable-next-line:no-unused-expression574    expect(result.success).to.be.true;575    if (type === 'NFT') {576      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;577      expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);578    }579    if (type === 'Fungible') {580      const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;581      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());582    }583    if (type === 'ReFungible') {584      const nftItemData =585        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;586      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);587      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);588    }589  });590}591592export async function593transferFromExpectFail(collectionId: number,594                       tokenId: number,595                       accountApproved: IKeyringPair,596                       accountFrom: IKeyringPair,597                       accountTo: IKeyringPair,598                       value: number | bigint = 1) {599  await usingApi(async (api: ApiPromise) => {600    const transferFromTx = await api.tx.nft.transferFrom(601      accountFrom.address, accountTo.address, collectionId, tokenId, value);602    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;603    const result = getCreateCollectionResult(events);604    // tslint:disable-next-line:no-unused-expression605    expect(result.success).to.be.false;606  });607}608609export async function610transferExpectSuccess(collectionId: number,611                      tokenId: number,612                      sender: IKeyringPair,613                      recipient: IKeyringPair,614                      value: number | bigint = 1,615                      type: string = 'NFT') {616  await usingApi(async (api: ApiPromise) => {617    let balanceBefore = new BN(0);618    if (type === 'Fungible') {619      balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;620    }621    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);622    const events = await submitTransactionAsync(sender, transferTx);623    const result = getCreateItemResult(events);624    // tslint:disable-next-line:no-unused-expression625    expect(result.success).to.be.true;626    if (type === 'NFT') {627      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;628      expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);629    }630    if (type === 'Fungible') {631      const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;632      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());633    }634    if (type === 'ReFungible') {635      const nftItemData =636        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;637      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);638      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);639    }640  });641}642643export async function644transferExpectFail(collectionId: number,645                   tokenId: number,646                   sender: IKeyringPair,647                   recipient: IKeyringPair,648                   value: number | bigint = 1,649                   type: string = 'NFT') {650  await usingApi(async (api: ApiPromise) => {651    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);652    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;653    if (events && Array.isArray(events)) {654      const result = getCreateCollectionResult(events);655      // tslint:disable-next-line:no-unused-expression656      expect(result.success).to.be.false;657    }658  });659}660661export async function662approveExpectFail(collectionId: number,663                  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {664  await usingApi(async (api: ApiPromise) => {665    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);666    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;667    const result = getCreateCollectionResult(events);668    // tslint:disable-next-line:no-unused-expression669    expect(result.success).to.be.false;670  });671}672673export async function getFungibleBalance(674  collectionId: number,675  owner: string,676) {677  return await usingApi(async (api) => {678    const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};679    return BigInt(response.Value);680  });681}682683export async function createFungibleItemExpectSuccess(684  sender: IKeyringPair,685  collectionId: number,686  data: CreateFungibleData,687  owner: string = sender.address,688) {689  return await usingApi(async (api) => {690    const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });691692    const events = await submitTransactionAsync(sender, tx);693    const result = getCreateItemResult(events);694695    expect(result.success).to.be.true;696    return result.itemId;697  });698}699700export async function createItemExpectSuccess(701  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {702  let newItemId: number = 0;703  await usingApi(async (api) => {704    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);705    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();706    const AItemBalance = new BigNumber(Aitem.Value);707708    if (owner === '') {709      owner = sender.address;710    }711712    let tx;713    if (createMode === 'Fungible') {714      const createData = {fungible: {value: 10}};715      tx = api.tx.nft.createItem(collectionId, owner, createData);716    } else if (createMode === 'ReFungible') {717      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};718      tx = api.tx.nft.createItem(collectionId, owner, createData);719    } else {720      tx = api.tx.nft.createItem(collectionId, owner, createMode);721    }722    const events = await submitTransactionAsync(sender, tx);723    const result = getCreateItemResult(events);724725    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);726    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();727    const BItemBalance = new BigNumber(Bitem.Value);728729    // What to expect730    // tslint:disable-next-line:no-unused-expression731    expect(result.success).to.be.true;732    if (createMode === 'Fungible') {733      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);734    } else {735      expect(BItemCount).to.be.equal(AItemCount + 1);736    }737    expect(collectionId).to.be.equal(result.collectionId);738    expect(BItemCount).to.be.equal(result.itemId);739    newItemId = result.itemId;740  });741  return newItemId;742}743744export async function createItemExpectFailure(745  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {746  await usingApi(async (api) => {747    const tx = api.tx.nft.createItem(collectionId, owner, createMode);748    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;749    const result = getCreateItemResult(events);750751    expect(result.success).to.be.false;752  });753}754755export async function setPublicAccessModeExpectSuccess(756  sender: IKeyringPair, collectionId: number,757  accessMode: 'Normal' | 'WhiteList',758) {759  await usingApi(async (api) => {760761    // Run the transaction762    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);763    const events = await submitTransactionAsync(sender, tx);764    const result = getGenericResult(events);765766    // Get the collection767    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();768769    // What to expect770    // tslint:disable-next-line:no-unused-expression771    expect(result.success).to.be.true;772    expect(collection.Access).to.be.equal(accessMode);773  });774}775776export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {777  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');778}779780export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {781  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');782}783784export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {785  await usingApi(async (api) => {786787    // Run the transaction788    const tx = api.tx.nft.setMintPermission(collectionId, enabled);789    const events = await submitTransactionAsync(sender, tx);790    const result = getGenericResult(events);791792    // Get the collection793    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();794795    // What to expect796    // tslint:disable-next-line:no-unused-expression797    expect(result.success).to.be.true;798    expect(collection.MintMode).to.be.equal(enabled);799  });800}801802export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {803  await setMintPermissionExpectSuccess(sender, collectionId, true);804}805806export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {807  await usingApi(async (api) => {808    // Run the transaction809    const tx = api.tx.nft.setMintPermission(collectionId, enabled);810    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;811    const result = getCreateCollectionResult(events);812    // tslint:disable-next-line:no-unused-expression813    expect(result.success).to.be.false;814  });815}816817export async function isWhitelisted(collectionId: number, address: string) {818  let whitelisted: boolean = false;819  await usingApi(async (api) => {820    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;821  });822  return whitelisted;823}824825export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {826  await usingApi(async (api) => {827828    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();829830    // Run the transaction831    const tx = api.tx.nft.addToWhiteList(collectionId, address);832    const events = await submitTransactionAsync(sender, tx);833    const result = getGenericResult(events);834835    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();836837    // What to expect838    // tslint:disable-next-line:no-unused-expression839    expect(result.success).to.be.true;840    // tslint:disable-next-line: no-unused-expression841    expect(whiteListedBefore).to.be.false;842    // tslint:disable-next-line: no-unused-expression843    expect(whiteListedAfter).to.be.true;844  });845}846847export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {848  await usingApi(async (api) => {849    // Run the transaction850    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);851    const events = await submitTransactionAsync(sender, tx);852    const result = getGenericResult(events);853854    // What to expect855    // tslint:disable-next-line:no-unused-expression856    expect(result.success).to.be.true;857  });858}859860export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {861  await usingApi(async (api) => {862    // Run the transaction863    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);864    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;865    const result = getGenericResult(events);866867    // What to expect868    // tslint:disable-next-line:no-unused-expression869    expect(result.success).to.be.false;870  });871}872873export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)874  : Promise<ICollectionInterface | null> => {875  return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;876};877878export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {879  // set global object - collectionsCount880  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();881};882883export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {884  return await usingApi(async (api) => {885    return (await api.query.nft.collection(collectionId)) as unknown as ICollectionInterface;886  });887}
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;2324export const U128_MAX = (1n << 128n) - 1n;2526type GenericResult = {27  success: boolean,28};2930interface CreateCollectionResult {31  success: boolean;32  collectionId: number;33}3435interface CreateItemResult {36  success: boolean;37  collectionId: number;38  itemId: number;39}4041interface TransferResult {42  success: boolean;43  collectionId: number;44  itemId: number;45  sender: string;46  recipient: string;47  value: bigint;48}4950interface IReFungibleOwner {51  Fraction: BN;52  Owner: number[];53}5455interface ITokenDataType {56  Owner: number[];57  ConstData: number[];58  VariableData: number[];59}6061interface IFungibleTokenDataType {62  Value: BN;63}6465export interface IReFungibleTokenDataType {66  Owner: IReFungibleOwner[];67  ConstData: number[];68  VariableData: number[];69}7071export function getGenericResult(events: EventRecord[]): GenericResult {72  const result: GenericResult = {73    success: false,74  };75  events.forEach(({ phase, event: { data, method, section } }) => {76    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);77    if (method === 'ExtrinsicSuccess') {78      result.success = true;79    }80  });81  return result;82}8384export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {85  let success = false;86  let collectionId: number = 0;87  events.forEach(({ phase, event: { data, method, section } }) => {88    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);89    if (method == 'ExtrinsicSuccess') {90      success = true;91    } else if ((section == 'nft') && (method == 'Created')) {92      collectionId = parseInt(data[0].toString());93    }94  });95  const result: CreateCollectionResult = {96    success,97    collectionId,98  };99  return result;100}101102export function getCreateItemResult(events: EventRecord[]): CreateItemResult {103  let success = false;104  let collectionId: number = 0;105  let itemId: number = 0;106  events.forEach(({ phase, event: { data, method, section } }) => {107    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);108    if (method == 'ExtrinsicSuccess') {109      success = true;110    } else if ((section == 'nft') && (method == 'ItemCreated')) {111      collectionId = parseInt(data[0].toString());112      itemId = parseInt(data[1].toString());113    }114  });115  const result: CreateItemResult = {116    success,117    collectionId,118    itemId,119  };120  return result;121}122123export function getTransferResult(events: EventRecord[]): TransferResult {124  const result: TransferResult = {125    success: false,126    collectionId: 0,127    itemId: 0,128    sender: '',129    recipient: '',130    value: 0n,131  };132133  events.forEach(({event: {data, method, section}}) => {134    if (method === 'ExtrinsicSuccess') {135      result.success = true;136    } else if (section === 'nft' && method === 'Transfer') {137      result.collectionId = +data[0].toString();138      result.itemId = +data[1].toString();139      result.sender = data[2].toString();140      result.recipient = data[3].toString();141      result.value = BigInt(data[4].toString());142    }143  });144145  return result;146}147148interface Invalid {149  type: 'Invalid';150}151152interface Nft {153  type: 'NFT';154}155156interface Fungible {157  type: 'Fungible';158  decimalPoints: number;159}160161interface ReFungible {162  type: 'ReFungible';163}164165type CollectionMode = Nft | Fungible | ReFungible | Invalid;166167export type CreateCollectionParams = {168  mode: CollectionMode,169  name: string,170  description: string,171  tokenPrefix: string,172};173174const defaultCreateCollectionParams: CreateCollectionParams = {175  description: 'description',176  mode: { type: 'NFT' },177  name: 'name',178  tokenPrefix: 'prefix',179}180181export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {182  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};183184  let collectionId: number = 0;185  await usingApi(async (api) => {186    // Get number of collections before the transaction187    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);188189    // Run the CreateCollection transaction190    const alicePrivateKey = privateKey('//Alice');191192    let modeprm = {};193    if (mode.type === 'NFT') {194      modeprm = {nft: null};195    } else if (mode.type === 'Fungible') {196      modeprm = {fungible: mode.decimalPoints};197    } else if (mode.type === 'ReFungible') {198      modeprm = {refungible: null};199    } else if (mode.type === 'Invalid') {200      modeprm = {invalid: null};201    }202203    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);204    const events = await submitTransactionAsync(alicePrivateKey, tx);205    const result = getCreateCollectionResult(events);206207    // Get number of collections after the transaction208    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);209210    // Get the collection211    const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();212213    // What to expect214    // tslint:disable-next-line:no-unused-expression215    expect(result.success).to.be.true;216    expect(result.collectionId).to.be.equal(BcollectionCount);217    // tslint:disable-next-line:no-unused-expression218    expect(collection).to.be.not.null;219    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');220    expect(collection.Owner).to.be.equal(alicesPublicKey);221    expect(utf16ToStr(collection.Name)).to.be.equal(name);222    expect(utf16ToStr(collection.Description)).to.be.equal(description);223    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);224225    collectionId = result.collectionId;226  });227228  return collectionId;229}230231export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {232  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};233234  let modeprm = {};235  if (mode.type === 'NFT') {236    modeprm = {nft: null};237  } else if (mode.type === 'Fungible') {238    modeprm = {fungible: mode.decimalPoints};239  } else if (mode.type === 'ReFungible') {240    modeprm = {refungible: null};241  } else if (mode.type === 'Invalid') {242    modeprm = {invalid: null};243  }244245  await usingApi(async (api) => {246    // Get number of collections before the transaction247    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());248249    // Run the CreateCollection transaction250    const alicePrivateKey = privateKey('//Alice');251    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);252    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;253    const result = getCreateCollectionResult(events);254255    // Get number of collections after the transaction256    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());257258    // What to expect259    // tslint:disable-next-line:no-unused-expression260    expect(result.success).to.be.false;261    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');262  });263}264265export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {266  let bal = new BigNumber(0);267  let unused;268  do {269    const randomSeed = 'seed' +  Math.floor(Math.random() * Math.floor(10000)) + seedAddition;270    const keyring = new Keyring({ type: 'sr25519' });271    unused = keyring.addFromUri(`//${randomSeed}`);272    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());273  } while (bal.toFixed() != '0');274  return unused;275}276277export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {278  return await usingApi(async (api) => {279    const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;280    return BigInt(bn.toString());281  });282}283284export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {285  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));286}287288export async function findNotExistingCollection(api: ApiPromise): Promise<number> {289  const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;290  const newCollection: number = totalNumber + 1;291  return newCollection;292}293294function getDestroyResult(events: EventRecord[]): boolean {295  let success: boolean = false;296  events.forEach(({ phase, event: { data, method, section } }) => {297    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);298    if (method == 'ExtrinsicSuccess') {299      success = true;300    }301  });302  return success;303}304305export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {306  await usingApi(async (api) => {307    // Run the DestroyCollection transaction308    const alicePrivateKey = privateKey(senderSeed);309    const tx = api.tx.nft.destroyCollection(collectionId);310    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;311  });312}313314export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {315  await usingApi(async (api) => {316    // Run the DestroyCollection transaction317    const alicePrivateKey = privateKey(senderSeed);318    const tx = api.tx.nft.destroyCollection(collectionId);319    const events = await submitTransactionAsync(alicePrivateKey, tx);320    const result = getDestroyResult(events);321322    // Get the collection323    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();324325    // What to expect326    expect(result).to.be.true;327    expect(collection).to.be.not.null;328    expect(collection.Owner).to.be.equal(nullPublicKey);329  });330}331332export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {333  await usingApi(async (api) => {334335    // Run the transaction336    const alicePrivateKey = privateKey('//Alice');337    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);338    const events = await submitTransactionAsync(alicePrivateKey, tx);339    const result = getGenericResult(events);340341    // Get the collection342    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();343344    // What to expect345    expect(result.success).to.be.true;346    expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());347    expect(collection.SponsorConfirmed).to.be.false;348  });349}350351export async function removeCollectionSponsorExpectSuccess(collectionId: number) {352  await usingApi(async (api) => {353354    // Run the transaction355    const alicePrivateKey = privateKey('//Alice');356    const tx = api.tx.nft.removeCollectionSponsor(collectionId);357    const events = await submitTransactionAsync(alicePrivateKey, tx);358    const result = getGenericResult(events);359360    // Get the collection361    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();362363    // What to expect364    expect(result.success).to.be.true;365    expect(collection.Sponsor).to.be.equal(nullPublicKey);366    expect(collection.SponsorConfirmed).to.be.false;367  });368}369370export async function removeCollectionSponsorExpectFailure(collectionId: number) {371  await usingApi(async (api) => {372373    // Run the transaction374    const alicePrivateKey = privateKey('//Alice');375    const tx = api.tx.nft.removeCollectionSponsor(collectionId);376    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;377  });378}379380export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {381  await usingApi(async (api) => {382383    // Run the transaction384    const alicePrivateKey = privateKey(senderSeed);385    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);386    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;387  });388}389390export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {391  await usingApi(async (api) => {392393    // Run the transaction394    const sender = privateKey(senderSeed);395    const tx = api.tx.nft.confirmSponsorship(collectionId);396    const events = await submitTransactionAsync(sender, tx);397    const result = getGenericResult(events);398399    // Get the collection400    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();401402    // What to expect403    expect(result.success).to.be.true;404    expect(collection.Sponsor).to.be.equal(sender.address);405    expect(collection.SponsorConfirmed).to.be.true;406  });407}408409410export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {411  await usingApi(async (api) => {412413    // Run the transaction414    const sender = privateKey(senderSeed);415    const tx = api.tx.nft.confirmSponsorship(collectionId);416    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;417  });418}419420export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {421  await usingApi(async (api) => {422    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);423    const events = await submitTransactionAsync(sender, tx);424    const result = getGenericResult(events);425426    expect(result.success).to.be.true;427  });428}429430export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {431  await usingApi(async (api) => {432    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);433    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;434    const result = getGenericResult(events);435436    expect(result.success).to.be.false;437  });438}439440export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {441  await usingApi(async (api) => {442    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);443    const events = await submitTransactionAsync(sender, tx);444    const result = getGenericResult(events);445446    expect(result.success).to.be.true;447  });448}449450export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {451  await usingApi(async (api) => {452    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);453    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;454    const result = getGenericResult(events);455456    expect(result.success).to.be.false;457  });458}459460export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {461  await usingApi(async (api) => {462    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);463    const events = await submitTransactionAsync(sender, tx);464    const result = getGenericResult(events);465466    expect(result.success).to.be.true;467  });468}469470export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {471  let whitelisted: boolean = false;472  await usingApi(async (api) => {473    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;474  });475  return whitelisted;476}477478export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {479  await usingApi(async (api) => {480    const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);481    const events = await submitTransactionAsync(sender, tx);482    const result = getGenericResult(events);483484    expect(result.success).to.be.true;485  });486}487488export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {489  await usingApi(async (api) => {490    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);491    const events = await submitTransactionAsync(sender, tx);492    const result = getGenericResult(events);493494    expect(result.success).to.be.true;495  });496}497498export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {499  await usingApi(async (api) => {500    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);501    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;502    const result = getGenericResult(events);503504    expect(result.success).to.be.false;505  });506}507508export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {509  await usingApi(async (api) => {510    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));511    const events = await submitTransactionAsync(sender, tx);512    const result = getGenericResult(events);513514    expect(result.success).to.be.true;515  });516}517518export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {519  await usingApi(async (api) => {520    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));521    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;522  });523}524525export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {526  await usingApi(async (api) => {527    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));528    const events = await submitTransactionAsync(sender, tx);529    const result = getGenericResult(events);530531    expect(result.success).to.be.true;532  });533}534535export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {536  await usingApi(async (api) => {537    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));538    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;539  });540}541542export interface CreateFungibleData {543  readonly Value: bigint;544}545546export interface CreateReFungibleData { }547export interface CreateNftData { }548549export type CreateItemData = {550  NFT: CreateNftData;551} | {552  Fungible: CreateFungibleData;553} | {554  ReFungible: CreateReFungibleData;555};556557export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {558  await usingApi(async (api) => {559    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);560    const events = await submitTransactionAsync(owner, tx);561    const result = getGenericResult(events);562    // Get the item563    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();564    // What to expect565    // tslint:disable-next-line:no-unused-expression566    expect(result.success).to.be.true;567    // tslint:disable-next-line:no-unused-expression568    expect(item).to.be.not.null;569    expect(item.Owner).to.be.equal(nullPublicKey);570  });571}572573export async function574approveExpectSuccess(collectionId: number,575                     tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {576  await usingApi(async (api: ApiPromise) => {577    const allowanceBefore =578      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;579    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);580    const events = await submitTransactionAsync(owner, approveNftTx);581    const result = getCreateItemResult(events);582    // tslint:disable-next-line:no-unused-expression583    expect(result.success).to.be.true;584    const allowanceAfter =585      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;586    expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());587  });588}589590export async function591transferFromExpectSuccess(collectionId: number,592                          tokenId: number,593                          accountApproved: IKeyringPair,594                          accountFrom: IKeyringPair,595                          accountTo: IKeyringPair,596                          value: number | bigint = 1,597                          type: string = 'NFT') {598  await usingApi(async (api: ApiPromise) => {599    let balanceBefore = new BN(0);600    if (type === 'Fungible') {601      balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;602    }603    const transferFromTx = await api.tx.nft.transferFrom(604      accountFrom.address, accountTo.address, collectionId, tokenId, value);605    const events = await submitTransactionAsync(accountApproved, transferFromTx);606    const result = getCreateItemResult(events);607    // tslint:disable-next-line:no-unused-expression608    expect(result.success).to.be.true;609    if (type === 'NFT') {610      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;611      expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);612    }613    if (type === 'Fungible') {614      const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;615      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());616    }617    if (type === 'ReFungible') {618      const nftItemData =619        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;620      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);621      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);622    }623  });624}625626export async function627transferFromExpectFail(collectionId: number,628                       tokenId: number,629                       accountApproved: IKeyringPair,630                       accountFrom: IKeyringPair,631                       accountTo: IKeyringPair,632                       value: number | bigint = 1) {633  await usingApi(async (api: ApiPromise) => {634    const transferFromTx = await api.tx.nft.transferFrom(635      accountFrom.address, accountTo.address, collectionId, tokenId, value);636    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;637    const result = getCreateCollectionResult(events);638    // tslint:disable-next-line:no-unused-expression639    expect(result.success).to.be.false;640  });641}642643export async function644transferExpectSuccess(collectionId: number,645                      tokenId: number,646                      sender: IKeyringPair,647                      recipient: IKeyringPair,648                      value: number | bigint = 1,649                      type: string = 'NFT') {650  await usingApi(async (api: ApiPromise) => {651    let balanceBefore = new BN(0);652    if (type === 'Fungible') {653      balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;654    }655    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);656    const events = await submitTransactionAsync(sender, transferTx);657    const result = getCreateItemResult(events);658    // tslint:disable-next-line:no-unused-expression659    expect(result.success).to.be.true;660    if (type === 'NFT') {661      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;662      expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);663    }664    if (type === 'Fungible') {665      const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;666      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());667    }668    if (type === 'ReFungible') {669      const nftItemData =670        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;671      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);672      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);673    }674  });675}676677export async function678transferExpectFail(collectionId: number,679                   tokenId: number,680                   sender: IKeyringPair,681                   recipient: IKeyringPair,682                   value: number | bigint = 1,683                   type: string = 'NFT') {684  await usingApi(async (api: ApiPromise) => {685    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);686    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;687    if (events && Array.isArray(events)) {688      const result = getCreateCollectionResult(events);689      // tslint:disable-next-line:no-unused-expression690      expect(result.success).to.be.false;691    }692  });693}694695export async function696approveExpectFail(collectionId: number,697                  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {698  await usingApi(async (api: ApiPromise) => {699    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);700    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;701    const result = getCreateCollectionResult(events);702    // tslint:disable-next-line:no-unused-expression703    expect(result.success).to.be.false;704  });705}706707export async function getFungibleBalance(708  collectionId: number,709  owner: string,710) {711  return await usingApi(async (api) => {712    const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};713    return BigInt(response.Value);714  });715}716717export async function createFungibleItemExpectSuccess(718  sender: IKeyringPair,719  collectionId: number,720  data: CreateFungibleData,721  owner: string = sender.address,722) {723  return await usingApi(async (api) => {724    const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });725726    const events = await submitTransactionAsync(sender, tx);727    const result = getCreateItemResult(events);728729    expect(result.success).to.be.true;730    return result.itemId;731  });732}733734export async function createItemExpectSuccess(735  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {736  let newItemId: number = 0;737  await usingApi(async (api) => {738    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);739    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();740    const AItemBalance = new BigNumber(Aitem.Value);741742    if (owner === '') {743      owner = sender.address;744    }745746    let tx;747    if (createMode === 'Fungible') {748      const createData = {fungible: {value: 10}};749      tx = api.tx.nft.createItem(collectionId, owner, createData);750    } else if (createMode === 'ReFungible') {751      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};752      tx = api.tx.nft.createItem(collectionId, owner, createData);753    } else {754      tx = api.tx.nft.createItem(collectionId, owner, createMode);755    }756    const events = await submitTransactionAsync(sender, tx);757    const result = getCreateItemResult(events);758759    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);760    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();761    const BItemBalance = new BigNumber(Bitem.Value);762763    // What to expect764    // tslint:disable-next-line:no-unused-expression765    expect(result.success).to.be.true;766    if (createMode === 'Fungible') {767      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);768    } else {769      expect(BItemCount).to.be.equal(AItemCount + 1);770    }771    expect(collectionId).to.be.equal(result.collectionId);772    expect(BItemCount).to.be.equal(result.itemId);773    newItemId = result.itemId;774  });775  return newItemId;776}777778export async function createItemExpectFailure(779  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {780  await usingApi(async (api) => {781    const tx = api.tx.nft.createItem(collectionId, owner, createMode);782    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;783    const result = getCreateItemResult(events);784785    expect(result.success).to.be.false;786  });787}788789export async function setPublicAccessModeExpectSuccess(790  sender: IKeyringPair, collectionId: number,791  accessMode: 'Normal' | 'WhiteList',792) {793  await usingApi(async (api) => {794795    // Run the transaction796    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);797    const events = await submitTransactionAsync(sender, tx);798    const result = getGenericResult(events);799800    // Get the collection801    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();802803    // What to expect804    // tslint:disable-next-line:no-unused-expression805    expect(result.success).to.be.true;806    expect(collection.Access).to.be.equal(accessMode);807  });808}809810export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {811  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');812}813814export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {815  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');816}817818export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {819  await usingApi(async (api) => {820821    // Run the transaction822    const tx = api.tx.nft.setMintPermission(collectionId, enabled);823    const events = await submitTransactionAsync(sender, tx);824    const result = getGenericResult(events);825826    // Get the collection827    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();828829    // What to expect830    // tslint:disable-next-line:no-unused-expression831    expect(result.success).to.be.true;832    expect(collection.MintMode).to.be.equal(enabled);833  });834}835836export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {837  await setMintPermissionExpectSuccess(sender, collectionId, true);838}839840export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {841  await usingApi(async (api) => {842    // Run the transaction843    const tx = api.tx.nft.setMintPermission(collectionId, enabled);844    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;845    const result = getCreateCollectionResult(events);846    // tslint:disable-next-line:no-unused-expression847    expect(result.success).to.be.false;848  });849}850851export async function isWhitelisted(collectionId: number, address: string) {852  let whitelisted: boolean = false;853  await usingApi(async (api) => {854    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;855  });856  return whitelisted;857}858859export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {860  await usingApi(async (api) => {861862    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();863864    // Run the transaction865    const tx = api.tx.nft.addToWhiteList(collectionId, address);866    const events = await submitTransactionAsync(sender, tx);867    const result = getGenericResult(events);868869    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();870871    // What to expect872    // tslint:disable-next-line:no-unused-expression873    expect(result.success).to.be.true;874    // tslint:disable-next-line: no-unused-expression875    expect(whiteListedBefore).to.be.false;876    // tslint:disable-next-line: no-unused-expression877    expect(whiteListedAfter).to.be.true;878  });879}880881export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {882  await usingApi(async (api) => {883    // Run the transaction884    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);885    const events = await submitTransactionAsync(sender, tx);886    const result = getGenericResult(events);887888    // What to expect889    // tslint:disable-next-line:no-unused-expression890    expect(result.success).to.be.true;891  });892}893894export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {895  await usingApi(async (api) => {896    // Run the transaction897    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);898    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;899    const result = getGenericResult(events);900901    // What to expect902    // tslint:disable-next-line:no-unused-expression903    expect(result.success).to.be.false;904  });905}906907export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)908  : Promise<ICollectionInterface | null> => {909  return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;910};911912export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {913  // set global object - collectionsCount914  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();915};916917export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {918  return await usingApi(async (api) => {919    return (await api.query.nft.collection(collectionId)) as unknown as ICollectionInterface;920  });921}