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

difftreelog

source

tests/src/util/helpers.ts34.2 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 queryCollectionLimits(collectionId: number) {299  return await usingApi(async (api) => {300    return ((await api.query.nft.collection(collectionId)).toJSON() as any).Limits;301  });302}303304export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {305  await usingApi(async (api) => {306    const oldLimits = await queryCollectionLimits(collectionId);307    const newLimits = { ...oldLimits as any, ...limits };308    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);309    const events = await submitTransactionAsync(sender, tx);310    const result = getGenericResult(events);311312    expect(result.success).to.be.true;313  });314}315316export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {317  await usingApi(async (api) => {318    const oldLimits = await queryCollectionLimits(collectionId);319    const newLimits = { ...oldLimits as any, ...limits };320    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);321    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;322    const result = getGenericResult(events);323324    expect(result.success).to.be.false;325  });326}327328export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {329  await usingApi(async (api) => {330331    // Run the transaction332    const alicePrivateKey = privateKey('//Alice');333    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);334    const events = await submitTransactionAsync(alicePrivateKey, tx);335    const result = getGenericResult(events);336337    // Get the collection338    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();339340    // What to expect341    expect(result.success).to.be.true;342    expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());343    expect(collection.SponsorConfirmed).to.be.false;344  });345}346347export async function removeCollectionSponsorExpectSuccess(collectionId: number) {348  await usingApi(async (api) => {349350    // Run the transaction351    const alicePrivateKey = privateKey('//Alice');352    const tx = api.tx.nft.removeCollectionSponsor(collectionId);353    const events = await submitTransactionAsync(alicePrivateKey, tx);354    const result = getGenericResult(events);355356    // Get the collection357    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();358359    // What to expect360    expect(result.success).to.be.true;361    expect(collection.Sponsor).to.be.equal(nullPublicKey);362    expect(collection.SponsorConfirmed).to.be.false;363  });364}365366export async function removeCollectionSponsorExpectFailure(collectionId: number) {367  await usingApi(async (api) => {368369    // Run the transaction370    const alicePrivateKey = privateKey('//Alice');371    const tx = api.tx.nft.removeCollectionSponsor(collectionId);372    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;373  });374}375376export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {377  await usingApi(async (api) => {378379    // Run the transaction380    const alicePrivateKey = privateKey(senderSeed);381    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);382    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;383  });384}385386export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {387  await usingApi(async (api) => {388389    // Run the transaction390    const sender = privateKey(senderSeed);391    const tx = api.tx.nft.confirmSponsorship(collectionId);392    const events = await submitTransactionAsync(sender, tx);393    const result = getGenericResult(events);394395    // Get the collection396    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();397398    // What to expect399    expect(result.success).to.be.true;400    expect(collection.Sponsor).to.be.equal(sender.address);401    expect(collection.SponsorConfirmed).to.be.true;402  });403}404405406export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {407  await usingApi(async (api) => {408409    // Run the transaction410    const sender = privateKey(senderSeed);411    const tx = api.tx.nft.confirmSponsorship(collectionId);412    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;413  });414}415416export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {417  await usingApi(async (api) => {418    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);419    const events = await submitTransactionAsync(sender, tx);420    const result = getGenericResult(events);421422    expect(result.success).to.be.true;423  });424}425426export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {427  await usingApi(async (api) => {428    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);429    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;430    const result = getGenericResult(events);431432    expect(result.success).to.be.false;433  });434}435436export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {437  await usingApi(async (api) => {438    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);439    const events = await submitTransactionAsync(sender, tx);440    const result = getGenericResult(events);441442    expect(result.success).to.be.true;443  });444}445446export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {447  await usingApi(async (api) => {448    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);449    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;450    const result = getGenericResult(events);451452    expect(result.success).to.be.false;453  });454}455456export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {457  await usingApi(async (api) => {458    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);459    const events = await submitTransactionAsync(sender, tx);460    const result = getGenericResult(events);461462    expect(result.success).to.be.true;463  });464}465466export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {467  let whitelisted: boolean = false;468  await usingApi(async (api) => {469    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;470  });471  return whitelisted;472}473474export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {475  await usingApi(async (api) => {476    const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);477    const events = await submitTransactionAsync(sender, tx);478    const result = getGenericResult(events);479480    expect(result.success).to.be.true;481  });482}483484export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {485  await usingApi(async (api) => {486    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);487    const events = await submitTransactionAsync(sender, tx);488    const result = getGenericResult(events);489490    expect(result.success).to.be.true;491  });492}493494export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {495  await usingApi(async (api) => {496    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);497    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;498    const result = getGenericResult(events);499500    expect(result.success).to.be.false;501  });502}503504export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {505  await usingApi(async (api) => {506    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));507    const events = await submitTransactionAsync(sender, tx);508    const result = getGenericResult(events);509510    expect(result.success).to.be.true;511  });512}513514export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {515  await usingApi(async (api) => {516    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));517    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;518  });519}520521export async function setOffchainSchemaExpectSuccess(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    const events = await submitTransactionAsync(sender, tx);525    const result = getGenericResult(events);526527    expect(result.success).to.be.true;528  });529}530531export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {532  await usingApi(async (api) => {533    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));534    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;535  });536}537538export interface CreateFungibleData {539  readonly Value: bigint;540}541542export interface CreateReFungibleData { }543export interface CreateNftData { }544545export type CreateItemData = {546  NFT: CreateNftData;547} | {548  Fungible: CreateFungibleData;549} | {550  ReFungible: CreateReFungibleData;551};552553export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {554  await usingApi(async (api) => {555    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);556    const events = await submitTransactionAsync(owner, tx);557    const result = getGenericResult(events);558    // Get the item559    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();560    // What to expect561    // tslint:disable-next-line:no-unused-expression562    expect(result.success).to.be.true;563    // tslint:disable-next-line:no-unused-expression564    expect(item).to.be.not.null;565    expect(item.Owner).to.be.equal(nullPublicKey);566  });567}568569export async function570approveExpectSuccess(collectionId: number,571                     tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {572  await usingApi(async (api: ApiPromise) => {573    const allowanceBefore =574      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;575    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);576    const events = await submitTransactionAsync(owner, approveNftTx);577    const result = getCreateItemResult(events);578    // tslint:disable-next-line:no-unused-expression579    expect(result.success).to.be.true;580    const allowanceAfter =581      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;582    expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());583  });584}585586export async function587transferFromExpectSuccess(collectionId: number,588                          tokenId: number,589                          accountApproved: IKeyringPair,590                          accountFrom: IKeyringPair,591                          accountTo: IKeyringPair,592                          value: number | bigint = 1,593                          type: string = 'NFT') {594  await usingApi(async (api: ApiPromise) => {595    let balanceBefore = new BN(0);596    if (type === 'Fungible') {597      balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;598    }599    const transferFromTx = await api.tx.nft.transferFrom(600      accountFrom.address, accountTo.address, collectionId, tokenId, value);601    const events = await submitTransactionAsync(accountApproved, transferFromTx);602    const result = getCreateItemResult(events);603    // tslint:disable-next-line:no-unused-expression604    expect(result.success).to.be.true;605    if (type === 'NFT') {606      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;607      expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);608    }609    if (type === 'Fungible') {610      const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;611      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());612    }613    if (type === 'ReFungible') {614      const nftItemData =615        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;616      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);617      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);618    }619  });620}621622export async function623transferFromExpectFail(collectionId: number,624                       tokenId: number,625                       accountApproved: IKeyringPair,626                       accountFrom: IKeyringPair,627                       accountTo: IKeyringPair,628                       value: number | bigint = 1) {629  await usingApi(async (api: ApiPromise) => {630    const transferFromTx = await api.tx.nft.transferFrom(631      accountFrom.address, accountTo.address, collectionId, tokenId, value);632    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;633    const result = getCreateCollectionResult(events);634    // tslint:disable-next-line:no-unused-expression635    expect(result.success).to.be.false;636  });637}638639export async function640transferExpectSuccess(collectionId: number,641                      tokenId: number,642                      sender: IKeyringPair,643                      recipient: IKeyringPair,644                      value: number | bigint = 1,645                      type: string = 'NFT') {646  await usingApi(async (api: ApiPromise) => {647    let balanceBefore = new BN(0);648    if (type === 'Fungible') {649      balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;650    }651    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);652    const events = await submitTransactionAsync(sender, transferTx);653    const result = getCreateItemResult(events);654    // tslint:disable-next-line:no-unused-expression655    expect(result.success).to.be.true;656    if (type === 'NFT') {657      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;658      expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);659    }660    if (type === 'Fungible') {661      const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;662      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());663    }664    if (type === 'ReFungible') {665      const nftItemData =666        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;667      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);668      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);669    }670  });671}672673export async function674transferExpectFail(collectionId: number,675                   tokenId: number,676                   sender: IKeyringPair,677                   recipient: IKeyringPair,678                   value: number | bigint = 1,679                   type: string = 'NFT') {680  await usingApi(async (api: ApiPromise) => {681    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);682    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;683    if (events && Array.isArray(events)) {684      const result = getCreateCollectionResult(events);685      // tslint:disable-next-line:no-unused-expression686      expect(result.success).to.be.false;687    }688  });689}690691export async function692approveExpectFail(collectionId: number,693                  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {694  await usingApi(async (api: ApiPromise) => {695    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);696    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;697    const result = getCreateCollectionResult(events);698    // tslint:disable-next-line:no-unused-expression699    expect(result.success).to.be.false;700  });701}702703export async function getFungibleBalance(704  collectionId: number,705  owner: string,706) {707  return await usingApi(async (api) => {708    const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};709    return BigInt(response.Value);710  });711}712713export async function createFungibleItemExpectSuccess(714  sender: IKeyringPair,715  collectionId: number,716  data: CreateFungibleData,717  owner: string = sender.address,718) {719  return await usingApi(async (api) => {720    const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });721722    const events = await submitTransactionAsync(sender, tx);723    const result = getCreateItemResult(events);724725    expect(result.success).to.be.true;726    return result.itemId;727  });728}729730export async function createItemExpectSuccess(731  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {732  let newItemId: number = 0;733  await usingApi(async (api) => {734    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);735    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();736    const AItemBalance = new BigNumber(Aitem.Value);737738    if (owner === '') {739      owner = sender.address;740    }741742    let tx;743    if (createMode === 'Fungible') {744      const createData = {fungible: {value: 10}};745      tx = api.tx.nft.createItem(collectionId, owner, createData);746    } else if (createMode === 'ReFungible') {747      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};748      tx = api.tx.nft.createItem(collectionId, owner, createData);749    } else {750      tx = api.tx.nft.createItem(collectionId, owner, createMode);751    }752    const events = await submitTransactionAsync(sender, tx);753    const result = getCreateItemResult(events);754755    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);756    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();757    const BItemBalance = new BigNumber(Bitem.Value);758759    // What to expect760    // tslint:disable-next-line:no-unused-expression761    expect(result.success).to.be.true;762    if (createMode === 'Fungible') {763      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);764    } else {765      expect(BItemCount).to.be.equal(AItemCount + 1);766    }767    expect(collectionId).to.be.equal(result.collectionId);768    expect(BItemCount).to.be.equal(result.itemId);769    newItemId = result.itemId;770  });771  return newItemId;772}773774export async function createItemExpectFailure(775  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {776  await usingApi(async (api) => {777    const tx = api.tx.nft.createItem(collectionId, owner, createMode);778    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;779    const result = getCreateItemResult(events);780781    expect(result.success).to.be.false;782  });783}784785export async function setPublicAccessModeExpectSuccess(786  sender: IKeyringPair, collectionId: number,787  accessMode: 'Normal' | 'WhiteList',788) {789  await usingApi(async (api) => {790791    // Run the transaction792    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);793    const events = await submitTransactionAsync(sender, tx);794    const result = getGenericResult(events);795796    // Get the collection797    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();798799    // What to expect800    // tslint:disable-next-line:no-unused-expression801    expect(result.success).to.be.true;802    expect(collection.Access).to.be.equal(accessMode);803  });804}805806export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {807  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');808}809810export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {811  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');812}813814export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {815  await usingApi(async (api) => {816817    // Run the transaction818    const tx = api.tx.nft.setMintPermission(collectionId, enabled);819    const events = await submitTransactionAsync(sender, tx);820    const result = getGenericResult(events);821822    // Get the collection823    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();824825    // What to expect826    // tslint:disable-next-line:no-unused-expression827    expect(result.success).to.be.true;828    expect(collection.MintMode).to.be.equal(enabled);829  });830}831832export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {833  await setMintPermissionExpectSuccess(sender, collectionId, true);834}835836export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {837  await usingApi(async (api) => {838    // Run the transaction839    const tx = api.tx.nft.setMintPermission(collectionId, enabled);840    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;841    const result = getCreateCollectionResult(events);842    // tslint:disable-next-line:no-unused-expression843    expect(result.success).to.be.false;844  });845}846847export async function isWhitelisted(collectionId: number, address: string) {848  let whitelisted: boolean = false;849  await usingApi(async (api) => {850    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;851  });852  return whitelisted;853}854855export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {856  await usingApi(async (api) => {857858    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();859860    // Run the transaction861    const tx = api.tx.nft.addToWhiteList(collectionId, address);862    const events = await submitTransactionAsync(sender, tx);863    const result = getGenericResult(events);864865    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();866867    // What to expect868    // tslint:disable-next-line:no-unused-expression869    expect(result.success).to.be.true;870    // tslint:disable-next-line: no-unused-expression871    expect(whiteListedBefore).to.be.false;872    // tslint:disable-next-line: no-unused-expression873    expect(whiteListedAfter).to.be.true;874  });875}876877export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {878  await usingApi(async (api) => {879    // Run the transaction880    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);881    const events = await submitTransactionAsync(sender, tx);882    const result = getGenericResult(events);883884    // What to expect885    // tslint:disable-next-line:no-unused-expression886    expect(result.success).to.be.true;887  });888}889890export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {891  await usingApi(async (api) => {892    // Run the transaction893    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);894    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;895    const result = getGenericResult(events);896897    // What to expect898    // tslint:disable-next-line:no-unused-expression899    expect(result.success).to.be.false;900  });901}902903export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)904  : Promise<ICollectionInterface | null> => {905  return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;906};907908export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {909  // set global object - collectionsCount910  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();911};912913export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {914  return await usingApi(async (api) => {915    return (await api.query.nft.collection(collectionId)) as unknown as ICollectionInterface;916  });917}