git.delta.rocks / unique-network / refs/commits / 04b203b44245

difftreelog

source

tests/src/util/helpers.ts34.1 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 TransferResult {42  success: boolean;43  collectionId: number;44  itemId: number;45  sender: string;46  recipient: string;47  value: bigint;48}4950interface IReFungibleOwner {51  Fraction: BN;52  Owner: number[];53}5455interface ITokenDataType {56  Owner: number[];57  ConstData: number[];58  VariableData: number[];59}6061interface IFungibleTokenDataType {62  Value: BN;63}6465export interface IReFungibleTokenDataType {66  Owner: IReFungibleOwner[];67  ConstData: number[];68  VariableData: number[];69}7071export function getGenericResult(events: EventRecord[]): GenericResult {72  const result: GenericResult = {73    success: false,74  };75  events.forEach(({ phase, event: { data, method, section } }) => {76    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);77    if (method === 'ExtrinsicSuccess') {78      result.success = true;79    }80  });81  return result;82}8384export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {85  let success = false;86  let collectionId: number = 0;87  events.forEach(({ phase, event: { data, method, section } }) => {88    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);89    if (method == 'ExtrinsicSuccess') {90      success = true;91    } else if ((section == 'nft') && (method == 'Created')) {92      collectionId = parseInt(data[0].toString());93    }94  });95  const result: CreateCollectionResult = {96    success,97    collectionId,98  };99  return result;100}101102export function getCreateItemResult(events: EventRecord[]): CreateItemResult {103  let success = false;104  let collectionId: number = 0;105  let itemId: number = 0;106  events.forEach(({ phase, event: { data, method, section } }) => {107    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);108    if (method == 'ExtrinsicSuccess') {109      success = true;110    } else if ((section == 'nft') && (method == 'ItemCreated')) {111      collectionId = parseInt(data[0].toString());112      itemId = parseInt(data[1].toString());113    }114  });115  const result: CreateItemResult = {116    success,117    collectionId,118    itemId,119  };120  return result;121}122123export function getTransferResult(events: EventRecord[]): TransferResult {124  const result: TransferResult = {125    success: false,126    collectionId: 0,127    itemId: 0,128    sender: '',129    recipient: '',130    value: 0n,131  };132133  events.forEach(({event: {data, method, section}}) => {134    if (method === 'ExtrinsicSuccess') {135      result.success = true;136    } else if (section === 'nft' && method === 'Transfer') {137      result.collectionId = +data[0].toString();138      result.itemId = +data[1].toString();139      result.sender = data[2].toString();140      result.recipient = data[3].toString();141      result.value = BigInt(data[4].toString());142    }143  });144145  return result;146}147148interface Invalid {149  type: 'Invalid';150}151152interface Nft {153  type: 'NFT';154}155156interface Fungible {157  type: 'Fungible';158  decimalPoints: number;159}160161interface ReFungible {162  type: 'ReFungible';163}164165type CollectionMode = Nft | Fungible | ReFungible | Invalid;166167export type CreateCollectionParams = {168  mode: CollectionMode,169  name: string,170  description: string,171  tokenPrefix: string,172};173174const defaultCreateCollectionParams: CreateCollectionParams = {175  description: 'description',176  mode: { type: 'NFT' },177  name: 'name',178  tokenPrefix: 'prefix',179}180181export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {182  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};183184  let collectionId: number = 0;185  await usingApi(async (api) => {186    // Get number of collections before the transaction187    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);188189    // Run the CreateCollection transaction190    const alicePrivateKey = privateKey('//Alice');191192    let modeprm = {};193    if (mode.type === 'NFT') {194      modeprm = {nft: null};195    } else if (mode.type === 'Fungible') {196      modeprm = {fungible: mode.decimalPoints};197    } else if (mode.type === 'ReFungible') {198      modeprm = {refungible: null};199    } else if (mode.type === 'Invalid') {200      modeprm = {invalid: null};201    }202203    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);204    const events = await submitTransactionAsync(alicePrivateKey, tx);205    const result = getCreateCollectionResult(events);206207    // Get number of collections after the transaction208    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);209210    // Get the collection211    const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();212213    // What to expect214    // tslint:disable-next-line:no-unused-expression215    expect(result.success).to.be.true;216    expect(result.collectionId).to.be.equal(BcollectionCount);217    // tslint:disable-next-line:no-unused-expression218    expect(collection).to.be.not.null;219    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');220    expect(collection.Owner).to.be.equal(alicesPublicKey);221    expect(utf16ToStr(collection.Name)).to.be.equal(name);222    expect(utf16ToStr(collection.Description)).to.be.equal(description);223    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);224225    collectionId = result.collectionId;226  });227228  return collectionId;229}230231export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {232  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};233234  let modeprm = {};235  if (mode.type === 'NFT') {236    modeprm = {nft: null};237  } else if (mode.type === 'Fungible') {238    modeprm = {fungible: mode.decimalPoints};239  } else if (mode.type === 'ReFungible') {240    modeprm = {refungible: null};241  } else if (mode.type === 'Invalid') {242    modeprm = {invalid: null};243  }244245  await usingApi(async (api) => {246    // Get number of collections before the transaction247    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());248249    // Run the CreateCollection transaction250    const alicePrivateKey = privateKey('//Alice');251    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);252    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;253    const result = getCreateCollectionResult(events);254255    // Get number of collections after the transaction256    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());257258    // What to expect259    // tslint:disable-next-line:no-unused-expression260    expect(result.success).to.be.false;261    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');262  });263}264265export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {266  let bal = new BigNumber(0);267  let unused;268  do {269    const randomSeed = 'seed' +  Math.floor(Math.random() * Math.floor(10000)) + seedAddition;270    const keyring = new Keyring({ type: 'sr25519' });271    unused = keyring.addFromUri(`//${randomSeed}`);272    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());273  } while (bal.toFixed() != '0');274  return unused;275}276277export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {278  return await usingApi(async (api) => {279    const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;280    return BigInt(bn.toString());281  });282}283284export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {285  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));286}287288export async function findNotExistingCollection(api: ApiPromise): Promise<number> {289  const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;290  const newCollection: number = totalNumber + 1;291  return newCollection;292}293294function getDestroyResult(events: EventRecord[]): boolean {295  let success: boolean = false;296  events.forEach(({ phase, event: { data, method, section } }) => {297    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);298    if (method == 'ExtrinsicSuccess') {299      success = true;300    }301  });302  return success;303}304305export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {306  await usingApi(async (api) => {307    // Run the DestroyCollection transaction308    const alicePrivateKey = privateKey(senderSeed);309    const tx = api.tx.nft.destroyCollection(collectionId);310    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;311  });312}313314export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {315  await usingApi(async (api) => {316    // Run the DestroyCollection transaction317    const alicePrivateKey = privateKey(senderSeed);318    const tx = api.tx.nft.destroyCollection(collectionId);319    const events = await submitTransactionAsync(alicePrivateKey, tx);320    const result = getDestroyResult(events);321322    // Get the collection323    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();324325    // What to expect326    expect(result).to.be.true;327    expect(collection).to.be.not.null;328    expect(collection.Owner).to.be.equal(nullPublicKey);329  });330}331332export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {333  await usingApi(async (api) => {334335    // Run the transaction336    const alicePrivateKey = privateKey('//Alice');337    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);338    const events = await submitTransactionAsync(alicePrivateKey, tx);339    const result = getGenericResult(events);340341    // Get the collection342    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();343344    // What to expect345    expect(result.success).to.be.true;346    expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());347    expect(collection.SponsorConfirmed).to.be.false;348  });349}350351export async function removeCollectionSponsorExpectSuccess(collectionId: number) {352  await usingApi(async (api) => {353354    // Run the transaction355    const alicePrivateKey = privateKey('//Alice');356    const tx = api.tx.nft.removeCollectionSponsor(collectionId);357    const events = await submitTransactionAsync(alicePrivateKey, tx);358    const result = getGenericResult(events);359360    // Get the collection361    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();362363    // What to expect364    expect(result.success).to.be.true;365    expect(collection.Sponsor).to.be.equal(nullPublicKey);366    expect(collection.SponsorConfirmed).to.be.false;367  });368}369370export async function removeCollectionSponsorExpectFailure(collectionId: number) {371  await usingApi(async (api) => {372373    // Run the transaction374    const alicePrivateKey = privateKey('//Alice');375    const tx = api.tx.nft.removeCollectionSponsor(collectionId);376    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;377  });378}379380export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {381  await usingApi(async (api) => {382383    // Run the transaction384    const alicePrivateKey = privateKey(senderSeed);385    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);386    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;387  });388}389390export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {391  await usingApi(async (api) => {392393    // Run the transaction394    const sender = privateKey(senderSeed);395    const tx = api.tx.nft.confirmSponsorship(collectionId);396    const events = await submitTransactionAsync(sender, tx);397    const result = getGenericResult(events);398399    // Get the collection400    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();401402    // What to expect403    expect(result.success).to.be.true;404    expect(collection.Sponsor).to.be.equal(sender.address);405    expect(collection.SponsorConfirmed).to.be.true;406  });407}408409410export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {411  await usingApi(async (api) => {412413    // Run the transaction414    const sender = privateKey(senderSeed);415    const tx = api.tx.nft.confirmSponsorship(collectionId);416    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;417  });418}419420export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {421  await usingApi(async (api) => {422    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);423    const events = await submitTransactionAsync(sender, tx);424    const result = getGenericResult(events);425426    expect(result.success).to.be.true;427  });428}429430export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {431  await usingApi(async (api) => {432    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);433    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;434    const result = getGenericResult(events);435436    expect(result.success).to.be.false;437  });438}439440export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {441  await usingApi(async (api) => {442    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);443    const events = await submitTransactionAsync(sender, tx);444    const result = getGenericResult(events);445446    expect(result.success).to.be.true;447  });448}449450export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {451  await usingApi(async (api) => {452    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);453    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;454    const result = getGenericResult(events);455456    expect(result.success).to.be.false;457  });458}459460export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {461  await usingApi(async (api) => {462    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);463    const events = await submitTransactionAsync(sender, tx);464    const result = getGenericResult(events);465466    expect(result.success).to.be.true;467  });468}469470export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {471  let whitelisted: boolean = false;472  await usingApi(async (api) => {473    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;474  });475  return whitelisted;476}477478export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {479  await usingApi(async (api) => {480    const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);481    const events = await submitTransactionAsync(sender, tx);482    const result = getGenericResult(events);483484    expect(result.success).to.be.true;485  });486}487488export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {489  await usingApi(async (api) => {490    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);491    const events = await submitTransactionAsync(sender, tx);492    const result = getGenericResult(events);493494    expect(result.success).to.be.true;495  });496}497498export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {499  await usingApi(async (api) => {500    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);501    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;502    const result = getGenericResult(events);503504    expect(result.success).to.be.false;505  });506}507508export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {509  await usingApi(async (api) => {510    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));511    const events = await submitTransactionAsync(sender, tx);512    const result = getGenericResult(events);513514    expect(result.success).to.be.true;515  });516}517518export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {519  await usingApi(async (api) => {520    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));521    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;522  });523}524525export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {526  await usingApi(async (api) => {527    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));528    const events = await submitTransactionAsync(sender, tx);529    const result = getGenericResult(events);530531    expect(result.success).to.be.true;532  });533}534535export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {536  await usingApi(async (api) => {537    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));538    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;539  });540}541542export interface CreateFungibleData {543  readonly Value: bigint;544}545546export interface CreateReFungibleData { }547export interface CreateNftData { }548549export type CreateItemData = {550  NFT: CreateNftData;551} | {552  Fungible: CreateFungibleData;553} | {554  ReFungible: CreateReFungibleData;555};556557export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {558  await usingApi(async (api) => {559    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);560    const events = await submitTransactionAsync(owner, tx);561    const result = getGenericResult(events);562    // Get the item563    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();564    // What to expect565    // tslint:disable-next-line:no-unused-expression566    expect(result.success).to.be.true;567    // tslint:disable-next-line:no-unused-expression568    expect(item).to.be.not.null;569    expect(item.Owner).to.be.equal(nullPublicKey);570  });571}572573export async function574approveExpectSuccess(collectionId: number,575                     tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {576  await usingApi(async (api: ApiPromise) => {577    const allowanceBefore =578      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;579    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);580    const events = await submitTransactionAsync(owner, approveNftTx);581    const result = getCreateItemResult(events);582    // tslint:disable-next-line:no-unused-expression583    expect(result.success).to.be.true;584    const allowanceAfter =585      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;586    expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());587  });588}589590export async function591transferFromExpectSuccess(collectionId: number,592                          tokenId: number,593                          accountApproved: IKeyringPair,594                          accountFrom: IKeyringPair,595                          accountTo: IKeyringPair,596                          value: number | bigint = 1,597                          type: string = 'NFT') {598  await usingApi(async (api: ApiPromise) => {599    let balanceBefore = new BN(0);600    if (type === 'Fungible') {601      balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;602    }603    const transferFromTx = await api.tx.nft.transferFrom(604      accountFrom.address, accountTo.address, collectionId, tokenId, value);605    const events = await submitTransactionAsync(accountApproved, transferFromTx);606    const result = getCreateItemResult(events);607    // tslint:disable-next-line:no-unused-expression608    expect(result.success).to.be.true;609    if (type === 'NFT') {610      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;611      expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);612    }613    if (type === 'Fungible') {614      const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;615      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());616    }617    if (type === 'ReFungible') {618      const nftItemData =619        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;620      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);621      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);622    }623  });624}625626export async function627transferFromExpectFail(collectionId: number,628                       tokenId: number,629                       accountApproved: IKeyringPair,630                       accountFrom: IKeyringPair,631                       accountTo: IKeyringPair,632                       value: number | bigint = 1) {633  await usingApi(async (api: ApiPromise) => {634    const transferFromTx = await api.tx.nft.transferFrom(635      accountFrom.address, accountTo.address, collectionId, tokenId, value);636    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;637    const result = getCreateCollectionResult(events);638    // tslint:disable-next-line:no-unused-expression639    expect(result.success).to.be.false;640  });641}642643export async function644transferExpectSuccess(collectionId: number,645                      tokenId: number,646                      sender: IKeyringPair,647                      recipient: IKeyringPair,648                      value: number | bigint = 1,649                      type: string = 'NFT') {650  await usingApi(async (api: ApiPromise) => {651    let balanceBefore = new BN(0);652    if (type === 'Fungible') {653      balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;654    }655    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);656    const events = await submitTransactionAsync(sender, transferTx);657    const result = getTransferResult(events);658    // tslint:disable-next-line:no-unused-expression659    expect(result.success).to.be.true;660    expect(result.collectionId).to.be.equal(collectionId);661    expect(result.itemId).to.be.equal(tokenId);662    expect(result.sender).to.be.equal(sender.address);663    expect(result.recipient).to.be.equal(recipient.address);664    expect(result.value.toString()).to.be.equal(value.toString());665    if (type === 'NFT') {666      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;667      expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);668    }669    if (type === 'Fungible') {670      const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;671      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());672    }673    if (type === 'ReFungible') {674      const nftItemData =675        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;676      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);677      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);678    }679  });680}681682export async function683transferExpectFail(collectionId: number,684                   tokenId: number,685                   sender: IKeyringPair,686                   recipient: IKeyringPair,687                   value: number | bigint = 1,688                   type: string = 'NFT') {689  await usingApi(async (api: ApiPromise) => {690    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);691    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;692    if (events && Array.isArray(events)) {693      const result = getCreateCollectionResult(events);694      // tslint:disable-next-line:no-unused-expression695      expect(result.success).to.be.false;696    }697  });698}699700export async function701approveExpectFail(collectionId: number,702                  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {703  await usingApi(async (api: ApiPromise) => {704    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);705    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;706    const result = getCreateCollectionResult(events);707    // tslint:disable-next-line:no-unused-expression708    expect(result.success).to.be.false;709  });710}711712export async function getFungibleBalance(713  collectionId: number,714  owner: string,715) {716  return await usingApi(async (api) => {717    const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};718    return BigInt(response.Value);719  });720}721722export async function createFungibleItemExpectSuccess(723  sender: IKeyringPair,724  collectionId: number,725  data: CreateFungibleData,726  owner: string = sender.address,727) {728  return await usingApi(async (api) => {729    const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });730731    const events = await submitTransactionAsync(sender, tx);732    const result = getCreateItemResult(events);733734    expect(result.success).to.be.true;735    return result.itemId;736  });737}738739export async function createItemExpectSuccess(740  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {741  let newItemId: number = 0;742  await usingApi(async (api) => {743    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);744    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();745    const AItemBalance = new BigNumber(Aitem.Value);746747    if (owner === '') {748      owner = sender.address;749    }750751    let tx;752    if (createMode === 'Fungible') {753      const createData = {fungible: {value: 10}};754      tx = api.tx.nft.createItem(collectionId, owner, createData);755    } else if (createMode === 'ReFungible') {756      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};757      tx = api.tx.nft.createItem(collectionId, owner, createData);758    } else {759      tx = api.tx.nft.createItem(collectionId, owner, createMode);760    }761    const events = await submitTransactionAsync(sender, tx);762    const result = getCreateItemResult(events);763764    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);765    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();766    const BItemBalance = new BigNumber(Bitem.Value);767768    // What to expect769    // tslint:disable-next-line:no-unused-expression770    expect(result.success).to.be.true;771    if (createMode === 'Fungible') {772      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);773    } else {774      expect(BItemCount).to.be.equal(AItemCount + 1);775    }776    expect(collectionId).to.be.equal(result.collectionId);777    expect(BItemCount).to.be.equal(result.itemId);778    newItemId = result.itemId;779  });780  return newItemId;781}782783export async function createItemExpectFailure(784  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {785  await usingApi(async (api) => {786    const tx = api.tx.nft.createItem(collectionId, owner, createMode);787    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;788    const result = getCreateItemResult(events);789790    expect(result.success).to.be.false;791  });792}793794export async function setPublicAccessModeExpectSuccess(795  sender: IKeyringPair, collectionId: number,796  accessMode: 'Normal' | 'WhiteList',797) {798  await usingApi(async (api) => {799800    // Run the transaction801    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);802    const events = await submitTransactionAsync(sender, tx);803    const result = getGenericResult(events);804805    // Get the collection806    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();807808    // What to expect809    // tslint:disable-next-line:no-unused-expression810    expect(result.success).to.be.true;811    expect(collection.Access).to.be.equal(accessMode);812  });813}814815export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {816  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');817}818819export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {820  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');821}822823export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {824  await usingApi(async (api) => {825826    // Run the transaction827    const tx = api.tx.nft.setMintPermission(collectionId, enabled);828    const events = await submitTransactionAsync(sender, tx);829    const result = getGenericResult(events);830831    // Get the collection832    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();833834    // What to expect835    // tslint:disable-next-line:no-unused-expression836    expect(result.success).to.be.true;837    expect(collection.MintMode).to.be.equal(enabled);838  });839}840841export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {842  await setMintPermissionExpectSuccess(sender, collectionId, true);843}844845export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {846  await usingApi(async (api) => {847    // Run the transaction848    const tx = api.tx.nft.setMintPermission(collectionId, enabled);849    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;850    const result = getCreateCollectionResult(events);851    // tslint:disable-next-line:no-unused-expression852    expect(result.success).to.be.false;853  });854}855856export async function isWhitelisted(collectionId: number, address: string) {857  let whitelisted: boolean = false;858  await usingApi(async (api) => {859    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;860  });861  return whitelisted;862}863864export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {865  await usingApi(async (api) => {866867    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();868869    // Run the transaction870    const tx = api.tx.nft.addToWhiteList(collectionId, address);871    const events = await submitTransactionAsync(sender, tx);872    const result = getGenericResult(events);873874    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();875876    // What to expect877    // tslint:disable-next-line:no-unused-expression878    expect(result.success).to.be.true;879    // tslint:disable-next-line: no-unused-expression880    expect(whiteListedBefore).to.be.false;881    // tslint:disable-next-line: no-unused-expression882    expect(whiteListedAfter).to.be.true;883  });884}885886export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {887  await usingApi(async (api) => {888    // Run the transaction889    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);890    const events = await submitTransactionAsync(sender, tx);891    const result = getGenericResult(events);892893    // What to expect894    // tslint:disable-next-line:no-unused-expression895    expect(result.success).to.be.true;896  });897}898899export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {900  await usingApi(async (api) => {901    // Run the transaction902    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);903    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;904    const result = getGenericResult(events);905906    // What to expect907    // tslint:disable-next-line:no-unused-expression908    expect(result.success).to.be.false;909  });910}911912export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)913  : Promise<ICollectionInterface | null> => {914  return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;915};916917export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {918  // set global object - collectionsCount919  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();920};921922export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {923  return await usingApi(async (api) => {924    return (await api.query.nft.collection(collectionId)) as unknown as ICollectionInterface;925  });926}