git.delta.rocks / unique-network / refs/commits / 0f94a81d220c

difftreelog

source

tests/src/util/helpers.ts33.9 KiBsourcehistory
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 setVariableMetaDataSponsoringRateLimitExpectSuccess(sender: IKeyringPair, collectionId: number, rateLimit: number) {492  await usingApi(async (api) => {493    const tx = api.tx.nft.setVariableMetaDataSponsoringRateLimit(collectionId, rateLimit);494    const events = await submitTransactionAsync(sender, tx);495    const result = getGenericResult(events);496497    expect(result.success).to.be.true;498  });499}500501export async function setVariableMetaDataSponsoringRateLimitExpectFailure(sender: IKeyringPair, collectionId: number, rateLimit: number) {502  await usingApi(async (api) => {503    const tx = api.tx.nft.setVariableMetaDataSponsoringRateLimit(collectionId, rateLimit);504    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;505    const result = getGenericResult(events);506507    expect(result.success).to.be.false;508  });509}510511export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {512  await usingApi(async (api) => {513    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));514    const events = await submitTransactionAsync(sender, tx);515    const result = getGenericResult(events);516517    expect(result.success).to.be.true;518  });519}520521export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {522  await usingApi(async (api) => {523    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));524    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;525  });526}527528export interface CreateFungibleData {529  readonly Value: bigint;530}531532export interface CreateReFungibleData { }533export interface CreateNftData { }534535export type CreateItemData = {536  NFT: CreateNftData;537} | {538  Fungible: CreateFungibleData;539} | {540  ReFungible: CreateReFungibleData;541};542543export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {544  await usingApi(async (api) => {545    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);546    const events = await submitTransactionAsync(owner, tx);547    const result = getGenericResult(events);548    // Get the item549    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();550    // What to expect551    // tslint:disable-next-line:no-unused-expression552    expect(result.success).to.be.true;553    // tslint:disable-next-line:no-unused-expression554    expect(item).to.be.not.null;555    expect(item.Owner).to.be.equal(nullPublicKey);556  });557}558559export async function560approveExpectSuccess(collectionId: number,561                     tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {562  await usingApi(async (api: ApiPromise) => {563    const allowanceBefore =564      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;565    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);566    const events = await submitTransactionAsync(owner, approveNftTx);567    const result = getCreateItemResult(events);568    // tslint:disable-next-line:no-unused-expression569    expect(result.success).to.be.true;570    const allowanceAfter =571      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;572    expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());573  });574}575576export async function577transferFromExpectSuccess(collectionId: number,578                          tokenId: number,579                          accountApproved: IKeyringPair,580                          accountFrom: IKeyringPair,581                          accountTo: IKeyringPair,582                          value: number | bigint = 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, accountTo.address) as unknown as BN;588    }589    const transferFromTx = await api.tx.nft.transferFrom(590      accountFrom.address, accountTo.address, collectionId, tokenId, value);591    const events = await submitTransactionAsync(accountApproved, transferFromTx);592    const result = getCreateItemResult(events);593    // tslint:disable-next-line:no-unused-expression594    expect(result.success).to.be.true;595    if (type === 'NFT') {596      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;597      expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);598    }599    if (type === 'Fungible') {600      const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;601      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());602    }603    if (type === 'ReFungible') {604      const nftItemData =605        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;606      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);607      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);608    }609  });610}611612export async function613transferFromExpectFail(collectionId: number,614                       tokenId: number,615                       accountApproved: IKeyringPair,616                       accountFrom: IKeyringPair,617                       accountTo: IKeyringPair,618                       value: number | bigint = 1) {619  await usingApi(async (api: ApiPromise) => {620    const transferFromTx = await api.tx.nft.transferFrom(621      accountFrom.address, accountTo.address, collectionId, tokenId, value);622    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;623    const result = getCreateCollectionResult(events);624    // tslint:disable-next-line:no-unused-expression625    expect(result.success).to.be.false;626  });627}628629export async function630transferExpectSuccess(collectionId: number,631                      tokenId: number,632                      sender: IKeyringPair,633                      recipient: IKeyringPair,634                      value: number | bigint = 1,635                      type: string = 'NFT') {636  await usingApi(async (api: ApiPromise) => {637    let balanceBefore = new BN(0);638    if (type === 'Fungible') {639      balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;640    }641    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);642    const events = await submitTransactionAsync(sender, transferTx);643    const result = getCreateItemResult(events);644    // tslint:disable-next-line:no-unused-expression645    expect(result.success).to.be.true;646    if (type === 'NFT') {647      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;648      expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);649    }650    if (type === 'Fungible') {651      const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;652      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());653    }654    if (type === 'ReFungible') {655      const nftItemData =656        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;657      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);658      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);659    }660  });661}662663export async function664transferExpectFail(collectionId: number,665                   tokenId: number,666                   sender: IKeyringPair,667                   recipient: IKeyringPair,668                   value: number | bigint = 1,669                   type: string = 'NFT') {670  await usingApi(async (api: ApiPromise) => {671    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);672    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;673    if (events && Array.isArray(events)) {674      const result = getCreateCollectionResult(events);675      // tslint:disable-next-line:no-unused-expression676      expect(result.success).to.be.false;677    }678  });679}680681export async function682approveExpectFail(collectionId: number,683                  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {684  await usingApi(async (api: ApiPromise) => {685    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);686    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;687    const result = getCreateCollectionResult(events);688    // tslint:disable-next-line:no-unused-expression689    expect(result.success).to.be.false;690  });691}692693export async function getFungibleBalance(694  collectionId: number,695  owner: string,696) {697  return await usingApi(async (api) => {698    const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};699    return BigInt(response.Value);700  });701}702703export async function createFungibleItemExpectSuccess(704  sender: IKeyringPair,705  collectionId: number,706  data: CreateFungibleData,707  owner: string = sender.address,708) {709  return await usingApi(async (api) => {710    const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });711712    const events = await submitTransactionAsync(sender, tx);713    const result = getCreateItemResult(events);714715    expect(result.success).to.be.true;716    return result.itemId;717  });718}719720export async function createItemExpectSuccess(721  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {722  let newItemId: number = 0;723  await usingApi(async (api) => {724    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);725    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();726    const AItemBalance = new BigNumber(Aitem.Value);727728    if (owner === '') {729      owner = sender.address;730    }731732    let tx;733    if (createMode === 'Fungible') {734      const createData = {fungible: {value: 10}};735      tx = api.tx.nft.createItem(collectionId, owner, createData);736    } else if (createMode === 'ReFungible') {737      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};738      tx = api.tx.nft.createItem(collectionId, owner, createData);739    } else {740      tx = api.tx.nft.createItem(collectionId, owner, createMode);741    }742    const events = await submitTransactionAsync(sender, tx);743    const result = getCreateItemResult(events);744745    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);746    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();747    const BItemBalance = new BigNumber(Bitem.Value);748749    // What to expect750    // tslint:disable-next-line:no-unused-expression751    expect(result.success).to.be.true;752    if (createMode === 'Fungible') {753      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);754    } else {755      expect(BItemCount).to.be.equal(AItemCount + 1);756    }757    expect(collectionId).to.be.equal(result.collectionId);758    expect(BItemCount).to.be.equal(result.itemId);759    newItemId = result.itemId;760  });761  return newItemId;762}763764export async function createItemExpectFailure(765  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {766  await usingApi(async (api) => {767    const tx = api.tx.nft.createItem(collectionId, owner, createMode);768    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;769    const result = getCreateItemResult(events);770771    expect(result.success).to.be.false;772  });773}774775export async function setPublicAccessModeExpectSuccess(776  sender: IKeyringPair, collectionId: number,777  accessMode: 'Normal' | 'WhiteList',778) {779  await usingApi(async (api) => {780781    // Run the transaction782    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);783    const events = await submitTransactionAsync(sender, tx);784    const result = getGenericResult(events);785786    // Get the collection787    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();788789    // What to expect790    // tslint:disable-next-line:no-unused-expression791    expect(result.success).to.be.true;792    expect(collection.Access).to.be.equal(accessMode);793  });794}795796export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {797  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');798}799800export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {801  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');802}803804export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {805  await usingApi(async (api) => {806807    // Run the transaction808    const tx = api.tx.nft.setMintPermission(collectionId, enabled);809    const events = await submitTransactionAsync(sender, tx);810    const result = getGenericResult(events);811812    // Get the collection813    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();814815    // What to expect816    // tslint:disable-next-line:no-unused-expression817    expect(result.success).to.be.true;818    expect(collection.MintMode).to.be.equal(enabled);819  });820}821822export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {823  await setMintPermissionExpectSuccess(sender, collectionId, true);824}825826export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {827  await usingApi(async (api) => {828    // Run the transaction829    const tx = api.tx.nft.setMintPermission(collectionId, enabled);830    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;831    const result = getCreateCollectionResult(events);832    // tslint:disable-next-line:no-unused-expression833    expect(result.success).to.be.false;834  });835}836837export async function isWhitelisted(collectionId: number, address: string) {838  let whitelisted: boolean = false;839  await usingApi(async (api) => {840    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;841  });842  return whitelisted;843}844845export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {846  await usingApi(async (api) => {847848    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();849850    // Run the transaction851    const tx = api.tx.nft.addToWhiteList(collectionId, address);852    const events = await submitTransactionAsync(sender, tx);853    const result = getGenericResult(events);854855    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();856857    // What to expect858    // tslint:disable-next-line:no-unused-expression859    expect(result.success).to.be.true;860    // tslint:disable-next-line: no-unused-expression861    expect(whiteListedBefore).to.be.false;862    // tslint:disable-next-line: no-unused-expression863    expect(whiteListedAfter).to.be.true;864  });865}866867export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {868  await usingApi(async (api) => {869    // Run the transaction870    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);871    const events = await submitTransactionAsync(sender, tx);872    const result = getGenericResult(events);873874    // What to expect875    // tslint:disable-next-line:no-unused-expression876    expect(result.success).to.be.true;877  });878}879880export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {881  await usingApi(async (api) => {882    // Run the transaction883    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);884    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;885    const result = getGenericResult(events);886887    // What to expect888    // tslint:disable-next-line:no-unused-expression889    expect(result.success).to.be.false;890  });891}892893export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)894  : Promise<ICollectionInterface | null> => {895  return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;896};897898export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {899  // set global object - collectionsCount900  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();901};902903export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {904  return await usingApi(async (api) => {905    return (await api.query.nft.collection(collectionId)) as unknown as ICollectionInterface;906  });907}