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

difftreelog

source

tests/src/util/helpers.ts35.4 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  recipient: string;40}4142interface TransferResult {43  success: boolean;44  collectionId: number;45  itemId: number;46  sender: string;47  recipient: string;48  value: bigint;49}5051interface IReFungibleOwner {52  Fraction: BN;53  Owner: number[];54}5556interface ITokenDataType {57  Owner: number[];58  ConstData: number[];59  VariableData: number[];60}6162interface IFungibleTokenDataType {63  Value: BN;64}6566export interface IReFungibleTokenDataType {67  Owner: IReFungibleOwner[];68  ConstData: number[];69  VariableData: number[];70}7172export function getGenericResult(events: EventRecord[]): GenericResult {73  const result: GenericResult = {74    success: false,75  };76  events.forEach(({ phase, event: { data, method, section } }) => {77    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);78    if (method === 'ExtrinsicSuccess') {79      result.success = true;80    }81  });82  return result;83}8485export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {86  let success = false;87  let collectionId: number = 0;88  events.forEach(({ phase, event: { data, method, section } }) => {89    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);90    if (method == 'ExtrinsicSuccess') {91      success = true;92    } else if ((section == 'nft') && (method == 'Created')) {93      collectionId = parseInt(data[0].toString());94    }95  });96  const result: CreateCollectionResult = {97    success,98    collectionId,99  };100  return result;101}102103export function getCreateItemResult(events: EventRecord[]): CreateItemResult {104  let success = false;105  let collectionId: number = 0;106  let itemId: number = 0;107  let recipient: string = '';108  events.forEach(({ phase, event: { data, method, section } }) => {109    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);110    if (method == 'ExtrinsicSuccess') {111      success = true;112    } else if ((section == 'nft') && (method == 'ItemCreated')) {113      collectionId = parseInt(data[0].toString());114      itemId = parseInt(data[1].toString());115      recipient = data[2].toString();116    }117  });118  const result: CreateItemResult = {119    success,120    collectionId,121    itemId,122    recipient,123  };124  return result;125}126127export function getTransferResult(events: EventRecord[]): TransferResult {128  const result: TransferResult = {129    success: false,130    collectionId: 0,131    itemId: 0,132    sender: '',133    recipient: '',134    value: 0n,135  };136137  events.forEach(({event: {data, method, section}}) => {138    if (method === 'ExtrinsicSuccess') {139      result.success = true;140    } else if (section === 'nft' && method === 'Transfer') {141      result.collectionId = +data[0].toString();142      result.itemId = +data[1].toString();143      result.sender = data[2].toString();144      result.recipient = data[3].toString();145      result.value = BigInt(data[4].toString());146    }147  });148149  return result;150}151152interface Invalid {153  type: 'Invalid';154}155156interface Nft {157  type: 'NFT';158}159160interface Fungible {161  type: 'Fungible';162  decimalPoints: number;163}164165interface ReFungible {166  type: 'ReFungible';167}168169type CollectionMode = Nft | Fungible | ReFungible | Invalid;170171export type CreateCollectionParams = {172  mode: CollectionMode,173  name: string,174  description: string,175  tokenPrefix: string,176};177178const defaultCreateCollectionParams: CreateCollectionParams = {179  description: 'description',180  mode: { type: 'NFT' },181  name: 'name',182  tokenPrefix: 'prefix',183}184185export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {186  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};187188  let collectionId: number = 0;189  await usingApi(async (api) => {190    // Get number of collections before the transaction191    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);192193    // Run the CreateCollection transaction194    const alicePrivateKey = privateKey('//Alice');195196    let modeprm = {};197    if (mode.type === 'NFT') {198      modeprm = {nft: null};199    } else if (mode.type === 'Fungible') {200      modeprm = {fungible: mode.decimalPoints};201    } else if (mode.type === 'ReFungible') {202      modeprm = {refungible: null};203    } else if (mode.type === 'Invalid') {204      modeprm = {invalid: null};205    }206207    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);208    const events = await submitTransactionAsync(alicePrivateKey, tx);209    const result = getCreateCollectionResult(events);210211    // Get number of collections after the transaction212    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);213214    // Get the collection215    const collection: any = (await api.query.nft.collectionById(result.collectionId)).toJSON();216217    // What to expect218    // tslint:disable-next-line:no-unused-expression219    expect(result.success).to.be.true;220    expect(result.collectionId).to.be.equal(BcollectionCount);221    // tslint:disable-next-line:no-unused-expression222    expect(collection).to.be.not.null;223    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');224    expect(collection.Owner).to.be.equal(alicesPublicKey);225    expect(utf16ToStr(collection.Name)).to.be.equal(name);226    expect(utf16ToStr(collection.Description)).to.be.equal(description);227    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);228229    collectionId = result.collectionId;230  });231232  return collectionId;233}234235export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {236  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};237238  let modeprm = {};239  if (mode.type === 'NFT') {240    modeprm = {nft: null};241  } else if (mode.type === 'Fungible') {242    modeprm = {fungible: mode.decimalPoints};243  } else if (mode.type === 'ReFungible') {244    modeprm = {refungible: null};245  } else if (mode.type === 'Invalid') {246    modeprm = {invalid: null};247  }248249  await usingApi(async (api) => {250    // Get number of collections before the transaction251    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());252253    // Run the CreateCollection transaction254    const alicePrivateKey = privateKey('//Alice');255    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);256    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;257    const result = getCreateCollectionResult(events);258259    // Get number of collections after the transaction260    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());261262    // What to expect263    // tslint:disable-next-line:no-unused-expression264    expect(result.success).to.be.false;265    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');266  });267}268269export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {270  let bal = new BigNumber(0);271  let unused;272  do {273    const randomSeed = 'seed' +  Math.floor(Math.random() * Math.floor(10000)) + seedAddition;274    const keyring = new Keyring({ type: 'sr25519' });275    unused = keyring.addFromUri(`//${randomSeed}`);276    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());277  } while (bal.toFixed() != '0');278  return unused;279}280281export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {282  return await usingApi(async (api) => {283    const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;284    return BigInt(bn.toString());285  });286}287288export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {289  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));290}291292export async function findNotExistingCollection(api: ApiPromise): Promise<number> {293  const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;294  const newCollection: number = totalNumber + 1;295  return newCollection;296}297298function getDestroyResult(events: EventRecord[]): boolean {299  let success: boolean = false;300  events.forEach(({ phase, event: { data, method, section } }) => {301    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);302    if (method == 'ExtrinsicSuccess') {303      success = true;304    }305  });306  return success;307}308309export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {310  await usingApi(async (api) => {311    // Run the DestroyCollection transaction312    const alicePrivateKey = privateKey(senderSeed);313    const tx = api.tx.nft.destroyCollection(collectionId);314    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;315  });316}317318export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {319  await usingApi(async (api) => {320    // Run the DestroyCollection transaction321    const alicePrivateKey = privateKey(senderSeed);322    const tx = api.tx.nft.destroyCollection(collectionId);323    const events = await submitTransactionAsync(alicePrivateKey, tx);324    const result = getDestroyResult(events);325326    // Get the collection327    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();328329    // What to expect330    expect(result).to.be.true;331    expect(collection).to.be.null;332  });333}334335export async function queryCollectionLimits(collectionId: number) {336  return await usingApi(async (api) => {337    return ((await api.query.nft.collectionById(collectionId)).toJSON() as any).Limits;338  });339}340341export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {342  await usingApi(async (api) => {343    const oldLimits = await queryCollectionLimits(collectionId);344    const newLimits = { ...oldLimits as any, ...limits };345    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);346    const events = await submitTransactionAsync(sender, tx);347    const result = getGenericResult(events);348349    expect(result.success).to.be.true;350  });351}352353export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {354  await usingApi(async (api) => {355    const oldLimits = await queryCollectionLimits(collectionId);356    const newLimits = { ...oldLimits as any, ...limits };357    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);358    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;359    const result = getGenericResult(events);360361    expect(result.success).to.be.false;362  });363}364365export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {366  await usingApi(async (api) => {367368    // Run the transaction369    const alicePrivateKey = privateKey('//Alice');370    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);371    const events = await submitTransactionAsync(alicePrivateKey, tx);372    const result = getGenericResult(events);373374    // Get the collection375    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();376377    // What to expect378    expect(result.success).to.be.true;379    expect(collection.Sponsorship).to.deep.equal({380      Unconfirmed: sponsor.toString(),381    });382  });383}384385export async function removeCollectionSponsorExpectSuccess(collectionId: number) {386  await usingApi(async (api) => {387388    // Run the transaction389    const alicePrivateKey = privateKey('//Alice');390    const tx = api.tx.nft.removeCollectionSponsor(collectionId);391    const events = await submitTransactionAsync(alicePrivateKey, tx);392    const result = getGenericResult(events);393394    // Get the collection395    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();396397    // What to expect398    expect(result.success).to.be.true;399    expect(collection.Sponsorship).to.be.deep.equal({ Disabled: null });400  });401}402403export async function removeCollectionSponsorExpectFailure(collectionId: number) {404  await usingApi(async (api) => {405406    // Run the transaction407    const alicePrivateKey = privateKey('//Alice');408    const tx = api.tx.nft.removeCollectionSponsor(collectionId);409    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;410  });411}412413export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {414  await usingApi(async (api) => {415416    // Run the transaction417    const alicePrivateKey = privateKey(senderSeed);418    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);419    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;420  });421}422423export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {424  await usingApi(async (api) => {425426    // Run the transaction427    const sender = privateKey(senderSeed);428    const tx = api.tx.nft.confirmSponsorship(collectionId);429    const events = await submitTransactionAsync(sender, tx);430    const result = getGenericResult(events);431432    // Get the collection433    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();434435    // What to expect436    expect(result.success).to.be.true;437    expect(collection.Sponsorship).to.be.deep.equal({438      Confirmed: sender.address,439    });440  });441}442443444export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {445  await usingApi(async (api) => {446447    // Run the transaction448    const sender = privateKey(senderSeed);449    const tx = api.tx.nft.confirmSponsorship(collectionId);450    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;451  });452}453454export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {455  await usingApi(async (api) => {456    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);457    const events = await submitTransactionAsync(sender, tx);458    const result = getGenericResult(events);459460    expect(result.success).to.be.true;461  });462}463464export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {465  await usingApi(async (api) => {466    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);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 setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {475  await usingApi(async (api) => {476    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);477    const events = await submitTransactionAsync(sender, tx);478    const result = getGenericResult(events);479480    expect(result.success).to.be.true;481  });482}483484export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {485  await usingApi(async (api) => {486    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);487    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;488    const result = getGenericResult(events);489490    expect(result.success).to.be.false;491  });492}493494export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {495  await usingApi(async (api) => {496    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);497    const events = await submitTransactionAsync(sender, tx);498    const result = getGenericResult(events);499500    expect(result.success).to.be.true;501  });502}503504export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {505  let whitelisted: boolean = false;506  await usingApi(async (api) => {507    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;508  });509  return whitelisted;510}511512export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {513  await usingApi(async (api) => {514    const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);515    const events = await submitTransactionAsync(sender, tx);516    const result = getGenericResult(events);517518    expect(result.success).to.be.true;519  });520}521522export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {523  await usingApi(async (api) => {524    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);525    const events = await submitTransactionAsync(sender, tx);526    const result = getGenericResult(events);527528    expect(result.success).to.be.true;529  });530}531532export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {533  await usingApi(async (api) => {534    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);535    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;536    const result = getGenericResult(events);537538    expect(result.success).to.be.false;539  });540}541542export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {543  await usingApi(async (api) => {544    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));545    const events = await submitTransactionAsync(sender, tx);546    const result = getGenericResult(events);547548    expect(result.success).to.be.true;549  });550}551552export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {553  await usingApi(async (api) => {554    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));555    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;556  });557}558559export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {560  await usingApi(async (api) => {561    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));562    const events = await submitTransactionAsync(sender, tx);563    const result = getGenericResult(events);564565    expect(result.success).to.be.true;566  });567}568569export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {570  await usingApi(async (api) => {571    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));572    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;573  });574}575576export interface CreateFungibleData {577  readonly Value: bigint;578}579580export interface CreateReFungibleData { }581export interface CreateNftData { }582583export type CreateItemData = {584  NFT: CreateNftData;585} | {586  Fungible: CreateFungibleData;587} | {588  ReFungible: CreateReFungibleData;589};590591export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {592  await usingApi(async (api) => {593    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);594    const events = await submitTransactionAsync(owner, tx);595    const result = getGenericResult(events);596    // Get the item597    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();598    // What to expect599    // tslint:disable-next-line:no-unused-expression600    expect(result.success).to.be.true;601    // tslint:disable-next-line:no-unused-expression602    expect(item).to.be.not.null;603    expect(item.Owner).to.be.equal(nullPublicKey);604  });605}606607export async function608approveExpectSuccess(collectionId: number,609                     tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {610  await usingApi(async (api: ApiPromise) => {611    const allowanceBefore =612      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;613    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);614    const events = await submitTransactionAsync(owner, approveNftTx);615    const result = getCreateItemResult(events);616    // tslint:disable-next-line:no-unused-expression617    expect(result.success).to.be.true;618    const allowanceAfter =619      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;620    expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());621  });622}623624export async function625transferFromExpectSuccess(collectionId: number,626                          tokenId: number,627                          accountApproved: IKeyringPair,628                          accountFrom: IKeyringPair,629                          accountTo: IKeyringPair,630                          value: number | bigint = 1,631                          type: string = 'NFT') {632  await usingApi(async (api: ApiPromise) => {633    let balanceBefore = new BN(0);634    if (type === 'Fungible') {635      balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;636    }637    const transferFromTx = await api.tx.nft.transferFrom(638      accountFrom.address, accountTo.address, collectionId, tokenId, value);639    const events = await submitTransactionAsync(accountApproved, transferFromTx);640    const result = getCreateItemResult(events);641    // tslint:disable-next-line:no-unused-expression642    expect(result.success).to.be.true;643    if (type === 'NFT') {644      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;645      expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);646    }647    if (type === 'Fungible') {648      const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;649      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());650    }651    if (type === 'ReFungible') {652      const nftItemData =653        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;654      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);655      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);656    }657  });658}659660export async function661transferFromExpectFail(collectionId: number,662                       tokenId: number,663                       accountApproved: IKeyringPair,664                       accountFrom: IKeyringPair,665                       accountTo: IKeyringPair,666                       value: number | bigint = 1) {667  await usingApi(async (api: ApiPromise) => {668    const transferFromTx = await api.tx.nft.transferFrom(669      accountFrom.address, accountTo.address, collectionId, tokenId, value);670    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;671    const result = getCreateCollectionResult(events);672    // tslint:disable-next-line:no-unused-expression673    expect(result.success).to.be.false;674  });675}676677export async function678transferExpectSuccess(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    let balanceBefore = new BN(0);686    if (type === 'Fungible') {687      balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;688    }689    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);690    const events = await submitTransactionAsync(sender, transferTx);691    const result = getTransferResult(events);692    // tslint:disable-next-line:no-unused-expression693    expect(result.success).to.be.true;694    expect(result.collectionId).to.be.equal(collectionId);695    expect(result.itemId).to.be.equal(tokenId);696    expect(result.sender).to.be.equal(sender.address);697    expect(result.recipient).to.be.equal(recipient.address);698    expect(result.value.toString()).to.be.equal(value.toString());699    if (type === 'NFT') {700      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;701      expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);702    }703    if (type === 'Fungible') {704      const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;705      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());706    }707    if (type === 'ReFungible') {708      const nftItemData =709        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;710      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);711      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);712    }713  });714}715716export async function717transferExpectFail(collectionId: number,718                   tokenId: number,719                   sender: IKeyringPair,720                   recipient: IKeyringPair,721                   value: number | bigint = 1,722                   type: string = 'NFT') {723  await usingApi(async (api: ApiPromise) => {724    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);725    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;726    if (events && Array.isArray(events)) {727      const result = getCreateCollectionResult(events);728      // tslint:disable-next-line:no-unused-expression729      expect(result.success).to.be.false;730    }731  });732}733734export async function735approveExpectFail(collectionId: number,736                  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {737  await usingApi(async (api: ApiPromise) => {738    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);739    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;740    const result = getCreateCollectionResult(events);741    // tslint:disable-next-line:no-unused-expression742    expect(result.success).to.be.false;743  });744}745746export async function getFungibleBalance(747  collectionId: number,748  owner: string,749) {750  return await usingApi(async (api) => {751    const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};752    return BigInt(response.Value);753  });754}755756export async function createFungibleItemExpectSuccess(757  sender: IKeyringPair,758  collectionId: number,759  data: CreateFungibleData,760  owner: string = sender.address,761) {762  return await usingApi(async (api) => {763    const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });764765    const events = await submitTransactionAsync(sender, tx);766    const result = getCreateItemResult(events);767768    expect(result.success).to.be.true;769    return result.itemId;770  });771}772773export async function createItemExpectSuccess(774  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {775  let newItemId: number = 0;776  await usingApi(async (api) => {777    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);778    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();779    const AItemBalance = new BigNumber(Aitem.Value);780781    if (owner === '') {782      owner = sender.address;783    }784785    let tx;786    if (createMode === 'Fungible') {787      const createData = {fungible: {value: 10}};788      tx = api.tx.nft.createItem(collectionId, owner, createData);789    } else if (createMode === 'ReFungible') {790      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};791      tx = api.tx.nft.createItem(collectionId, owner, createData);792    } else {793      tx = api.tx.nft.createItem(collectionId, owner, createMode);794    }795    const events = await submitTransactionAsync(sender, tx);796    const result = getCreateItemResult(events);797798    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);799    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();800    const BItemBalance = new BigNumber(Bitem.Value);801802    // What to expect803    // tslint:disable-next-line:no-unused-expression804    expect(result.success).to.be.true;805    if (createMode === 'Fungible') {806      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);807    } else {808      expect(BItemCount).to.be.equal(AItemCount + 1);809    }810    expect(collectionId).to.be.equal(result.collectionId);811    expect(BItemCount).to.be.equal(result.itemId);812    expect(owner).to.be.equal(result.recipient);813    newItemId = result.itemId;814  });815  return newItemId;816}817818export async function createItemExpectFailure(819  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {820  await usingApi(async (api) => {821    const tx = api.tx.nft.createItem(collectionId, owner, createMode);822    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;823    const result = getCreateItemResult(events);824825    expect(result.success).to.be.false;826  });827}828829export async function setPublicAccessModeExpectSuccess(830  sender: IKeyringPair, collectionId: number,831  accessMode: 'Normal' | 'WhiteList',832) {833  await usingApi(async (api) => {834835    // Run the transaction836    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);837    const events = await submitTransactionAsync(sender, tx);838    const result = getGenericResult(events);839840    // Get the collection841    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();842843    // What to expect844    // tslint:disable-next-line:no-unused-expression845    expect(result.success).to.be.true;846    expect(collection.Access).to.be.equal(accessMode);847  });848}849850export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {851  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');852}853854export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {855  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');856}857858export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {859  await usingApi(async (api) => {860861    // Run the transaction862    const tx = api.tx.nft.setMintPermission(collectionId, enabled);863    const events = await submitTransactionAsync(sender, tx);864    const result = getGenericResult(events);865866    // Get the collection867    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();868869    // What to expect870    // tslint:disable-next-line:no-unused-expression871    expect(result.success).to.be.true;872    expect(collection.MintMode).to.be.equal(enabled);873  });874}875876export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {877  await setMintPermissionExpectSuccess(sender, collectionId, true);878}879880export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {881  await usingApi(async (api) => {882    // Run the transaction883    const tx = api.tx.nft.setMintPermission(collectionId, enabled);884    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;885    const result = getCreateCollectionResult(events);886    // tslint:disable-next-line:no-unused-expression887    expect(result.success).to.be.false;888  });889}890891export async function isWhitelisted(collectionId: number, address: string) {892  let whitelisted: boolean = false;893  await usingApi(async (api) => {894    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;895  });896  return whitelisted;897}898899export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {900  await usingApi(async (api) => {901902    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();903904    // Run the transaction905    const tx = api.tx.nft.addToWhiteList(collectionId, address);906    const events = await submitTransactionAsync(sender, tx);907    const result = getGenericResult(events);908909    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();910911    // What to expect912    // tslint:disable-next-line:no-unused-expression913    expect(result.success).to.be.true;914    // tslint:disable-next-line: no-unused-expression915    expect(whiteListedBefore).to.be.false;916    // tslint:disable-next-line: no-unused-expression917    expect(whiteListedAfter).to.be.true;918  });919}920921export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {922  await usingApi(async (api) => {923    // Run the transaction924    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);925    const events = await submitTransactionAsync(sender, tx);926    const result = getGenericResult(events);927928    // What to expect929    // tslint:disable-next-line:no-unused-expression930    expect(result.success).to.be.true;931  });932}933934export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {935  await usingApi(async (api) => {936    // Run the transaction937    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);938    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;939    const result = getGenericResult(events);940941    // What to expect942    // tslint:disable-next-line:no-unused-expression943    expect(result.success).to.be.false;944  });945}946947export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)948  : Promise<ICollectionInterface | null> => {949  return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;950};951952export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {953  // set global object - collectionsCount954  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();955};956957export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {958  return await usingApi(async (api) => {959    return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;960  });961}