git.delta.rocks / unique-network / refs/commits / 8d3beac8f1a1

difftreelog

source

tests/src/util/helpers.ts36.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  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}6566interface IGetMessage {67  checkMsgNftMethod: string;68  checkMsgTrsMethod: string;69  checkMsgSysMethod: string;70}7172export interface IReFungibleTokenDataType {73  Owner: IReFungibleOwner[];74  ConstData: number[];75  VariableData: number[];76}7778export function nftEventMessage(events: EventRecord[]): IGetMessage {79  let checkMsgNftMethod: string = '';80  let checkMsgTrsMethod: string = '';81  let checkMsgSysMethod: string = '';82  events.forEach(({ event: { method, section } }) => {83    if (section === 'nft') {84      checkMsgNftMethod = method;85    } else if (section === 'treasury') {86      checkMsgTrsMethod = method;87    } else if (section === 'system') {88      checkMsgSysMethod = method;89    } else { return null; }90  });91  const result: IGetMessage = {92    checkMsgNftMethod,93    checkMsgTrsMethod,94    checkMsgSysMethod,95  };96  return result;97}9899export function getGenericResult(events: EventRecord[]): GenericResult {100  const result: GenericResult = {101    success: false,102  };103  events.forEach(({ phase, event: { data, method, section } }) => {104    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);105    if (method === 'ExtrinsicSuccess') {106      result.success = true;107    }108  });109  return result;110}111112113114export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {115  let success = false;116  let collectionId: number = 0;117  events.forEach(({ phase, event: { data, method, section } }) => {118    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);119    if (method == 'ExtrinsicSuccess') {120      success = true;121    } else if ((section == 'nft') && (method == 'Created')) {122      collectionId = parseInt(data[0].toString());123    }124  });125  const result: CreateCollectionResult = {126    success,127    collectionId,128  };129  return result;130}131132export function getCreateItemResult(events: EventRecord[]): CreateItemResult {133  let success = false;134  let collectionId: number = 0;135  let itemId: number = 0;136  let recipient: string = '';137  events.forEach(({ phase, event: { data, method, section } }) => {138    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);139    if (method == 'ExtrinsicSuccess') {140      success = true;141    } else if ((section == 'nft') && (method == 'ItemCreated')) {142      collectionId = parseInt(data[0].toString());143      itemId = parseInt(data[1].toString());144      recipient = data[2].toString();145    }146  });147  const result: CreateItemResult = {148    success,149    collectionId,150    itemId,151    recipient,152  };153  return result;154}155156export function getTransferResult(events: EventRecord[]): TransferResult {157  const result: TransferResult = {158    success: false,159    collectionId: 0,160    itemId: 0,161    sender: '',162    recipient: '',163    value: 0n,164  };165166  events.forEach(({event: {data, method, section}}) => {167    if (method === 'ExtrinsicSuccess') {168      result.success = true;169    } else if (section === 'nft' && method === 'Transfer') {170      result.collectionId = +data[0].toString();171      result.itemId = +data[1].toString();172      result.sender = data[2].toString();173      result.recipient = data[3].toString();174      result.value = BigInt(data[4].toString());175    }176  });177178  return result;179}180181interface Invalid {182  type: 'Invalid';183}184185interface Nft {186  type: 'NFT';187}188189interface Fungible {190  type: 'Fungible';191  decimalPoints: number;192}193194interface ReFungible {195  type: 'ReFungible';196}197198type CollectionMode = Nft | Fungible | ReFungible | Invalid;199200export type CreateCollectionParams = {201  mode: CollectionMode,202  name: string,203  description: string,204  tokenPrefix: string,205};206207const defaultCreateCollectionParams: CreateCollectionParams = {208  description: 'description',209  mode: { type: 'NFT' },210  name: 'name',211  tokenPrefix: 'prefix',212}213214export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {215  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};216217  let collectionId: number = 0;218  await usingApi(async (api) => {219    // Get number of collections before the transaction220    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);221222    // Run the CreateCollection transaction223    const alicePrivateKey = privateKey('//Alice');224225    let modeprm = {};226    if (mode.type === 'NFT') {227      modeprm = {nft: null};228    } else if (mode.type === 'Fungible') {229      modeprm = {fungible: mode.decimalPoints};230    } else if (mode.type === 'ReFungible') {231      modeprm = {refungible: null};232    } else if (mode.type === 'Invalid') {233      modeprm = {invalid: null};234    }235236    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);237    const events = await submitTransactionAsync(alicePrivateKey, tx);238    const result = getCreateCollectionResult(events);239240    // Get number of collections after the transaction241    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);242243    // Get the collection244    const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();245246    // What to expect247    // tslint:disable-next-line:no-unused-expression248    expect(result.success).to.be.true;249    expect(result.collectionId).to.be.equal(BcollectionCount);250    // tslint:disable-next-line:no-unused-expression251    expect(collection).to.be.not.null;252    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');253    expect(collection.Owner).to.be.equal(alicesPublicKey);254    expect(utf16ToStr(collection.Name)).to.be.equal(name);255    expect(utf16ToStr(collection.Description)).to.be.equal(description);256    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);257258    collectionId = result.collectionId;259  });260261  return collectionId;262}263264export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {265  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};266267  let modeprm = {};268  if (mode.type === 'NFT') {269    modeprm = {nft: null};270  } else if (mode.type === 'Fungible') {271    modeprm = {fungible: mode.decimalPoints};272  } else if (mode.type === 'ReFungible') {273    modeprm = {refungible: null};274  } else if (mode.type === 'Invalid') {275    modeprm = {invalid: null};276  }277278  await usingApi(async (api) => {279    // Get number of collections before the transaction280    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());281282    // Run the CreateCollection transaction283    const alicePrivateKey = privateKey('//Alice');284    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);285    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;286    const result = getCreateCollectionResult(events);287288    // Get number of collections after the transaction289    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());290291    // What to expect292    // tslint:disable-next-line:no-unused-expression293    expect(result.success).to.be.false;294    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');295  });296}297298export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {299  let bal = new BigNumber(0);300  let unused;301  do {302    const randomSeed = 'seed' +  Math.floor(Math.random() * Math.floor(10000)) + seedAddition;303    const keyring = new Keyring({ type: 'sr25519' });304    unused = keyring.addFromUri(`//${randomSeed}`);305    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());306  } while (bal.toFixed() != '0');307  return unused;308}309310export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {311  return await usingApi(async (api) => {312    const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;313    return BigInt(bn.toString());314  });315}316317export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {318  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));319}320321export async function findNotExistingCollection(api: ApiPromise): Promise<number> {322  const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;323  const newCollection: number = totalNumber + 1;324  return newCollection;325}326327function getDestroyResult(events: EventRecord[]): boolean {328  let success: boolean = false;329  events.forEach(({ phase, event: { data, method, section } }) => {330    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);331    if (method == 'ExtrinsicSuccess') {332      success = true;333    }334  });335  return success;336}337338export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {339  await usingApi(async (api) => {340    // Run the DestroyCollection transaction341    const alicePrivateKey = privateKey(senderSeed);342    const tx = api.tx.nft.destroyCollection(collectionId);343    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;344  });345}346347export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {348  await usingApi(async (api) => {349    // Run the DestroyCollection transaction350    const alicePrivateKey = privateKey(senderSeed);351    const tx = api.tx.nft.destroyCollection(collectionId);352    const events = await submitTransactionAsync(alicePrivateKey, tx);353    const result = getDestroyResult(events);354355    // Get the collection356    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();357358    // What to expect359    expect(result).to.be.true;360    expect(collection).to.be.not.null;361    expect(collection.Owner).to.be.equal(nullPublicKey);362  });363}364365export async function queryCollectionLimits(collectionId: number) {366  return await usingApi(async (api) => {367    return ((await api.query.nft.collection(collectionId)).toJSON() as any).Limits;368  });369}370371export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {372  await usingApi(async (api) => {373    const oldLimits = await queryCollectionLimits(collectionId);374    const newLimits = { ...oldLimits as any, ...limits };375    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);376    const events = await submitTransactionAsync(sender, tx);377    const result = getGenericResult(events);378379    expect(result.success).to.be.true;380  });381}382383export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {384  await usingApi(async (api) => {385    const oldLimits = await queryCollectionLimits(collectionId);386    const newLimits = { ...oldLimits as any, ...limits };387    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);388    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;389    const result = getGenericResult(events);390391    expect(result.success).to.be.false;392  });393}394395export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {396  await usingApi(async (api) => {397398    // Run the transaction399    const alicePrivateKey = privateKey('//Alice');400    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);401    const events = await submitTransactionAsync(alicePrivateKey, tx);402    const result = getGenericResult(events);403404    // Get the collection405    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();406407    // What to expect408    expect(result.success).to.be.true;409    expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());410    expect(collection.SponsorConfirmed).to.be.false;411  });412}413414export async function removeCollectionSponsorExpectSuccess(collectionId: number) {415  await usingApi(async (api) => {416417    // Run the transaction418    const alicePrivateKey = privateKey('//Alice');419    const tx = api.tx.nft.removeCollectionSponsor(collectionId);420    const events = await submitTransactionAsync(alicePrivateKey, tx);421    const result = getGenericResult(events);422423    // Get the collection424    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();425426    // What to expect427    expect(result.success).to.be.true;428    expect(collection.Sponsor).to.be.equal(nullPublicKey);429    expect(collection.SponsorConfirmed).to.be.false;430  });431}432433export async function removeCollectionSponsorExpectFailure(collectionId: number) {434  await usingApi(async (api) => {435436    // Run the transaction437    const alicePrivateKey = privateKey('//Alice');438    const tx = api.tx.nft.removeCollectionSponsor(collectionId);439    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;440  });441}442443export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {444  await usingApi(async (api) => {445446    // Run the transaction447    const alicePrivateKey = privateKey(senderSeed);448    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);449    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;450  });451}452453export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {454  await usingApi(async (api) => {455456    // Run the transaction457    const sender = privateKey(senderSeed);458    const tx = api.tx.nft.confirmSponsorship(collectionId);459    const events = await submitTransactionAsync(sender, tx);460    const result = getGenericResult(events);461462    // Get the collection463    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();464465    // What to expect466    expect(result.success).to.be.true;467    expect(collection.Sponsor).to.be.equal(sender.address);468    expect(collection.SponsorConfirmed).to.be.true;469  });470}471472473export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {474  await usingApi(async (api) => {475476    // Run the transaction477    const sender = privateKey(senderSeed);478    const tx = api.tx.nft.confirmSponsorship(collectionId);479    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;480  });481}482483export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {484  await usingApi(async (api) => {485    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);486    const events = await submitTransactionAsync(sender, tx);487    const result = getGenericResult(events);488489    expect(result.success).to.be.true;490  });491}492493export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {494  await usingApi(async (api) => {495    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);496    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;497    const result = getGenericResult(events);498499    expect(result.success).to.be.false;500  });501}502503export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {504  await usingApi(async (api) => {505    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);506    const events = await submitTransactionAsync(sender, tx);507    const result = getGenericResult(events);508509    expect(result.success).to.be.true;510  });511}512513export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {514  await usingApi(async (api) => {515    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);516    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;517    const result = getGenericResult(events);518519    expect(result.success).to.be.false;520  });521}522523export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {524  await usingApi(async (api) => {525    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);526    const events = await submitTransactionAsync(sender, tx);527    const result = getGenericResult(events);528529    expect(result.success).to.be.true;530  });531}532533export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {534  let whitelisted: boolean = false;535  await usingApi(async (api) => {536    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;537  });538  return whitelisted;539}540541export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {542  await usingApi(async (api) => {543    const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);544    const events = await submitTransactionAsync(sender, tx);545    const result = getGenericResult(events);546547    expect(result.success).to.be.true;548  });549}550551export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {552  await usingApi(async (api) => {553    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);554    const events = await submitTransactionAsync(sender, tx);555    const result = getGenericResult(events);556557    expect(result.success).to.be.true;558  });559}560561export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {562  await usingApi(async (api) => {563    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);564    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;565    const result = getGenericResult(events);566567    expect(result.success).to.be.false;568  });569}570571export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {572  await usingApi(async (api) => {573    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));574    const events = await submitTransactionAsync(sender, tx);575    const result = getGenericResult(events);576577    expect(result.success).to.be.true;578  });579}580581export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {582  await usingApi(async (api) => {583    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));584    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;585  });586}587588export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {589  await usingApi(async (api) => {590    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));591    const events = await submitTransactionAsync(sender, tx);592    const result = getGenericResult(events);593594    expect(result.success).to.be.true;595  });596}597598export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {599  await usingApi(async (api) => {600    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));601    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;602  });603}604605export interface CreateFungibleData {606  readonly Value: bigint;607}608609export interface CreateReFungibleData { }610export interface CreateNftData { }611612export type CreateItemData = {613  NFT: CreateNftData;614} | {615  Fungible: CreateFungibleData;616} | {617  ReFungible: CreateReFungibleData;618};619620export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {621  await usingApi(async (api) => {622    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);623    const events = await submitTransactionAsync(owner, tx);624    const result = getGenericResult(events);625    // Get the item626    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();627    // What to expect628    // tslint:disable-next-line:no-unused-expression629    expect(result.success).to.be.true;630    // tslint:disable-next-line:no-unused-expression631    expect(item).to.be.not.null;632    expect(item.Owner).to.be.equal(nullPublicKey);633  });634}635636export async function637approveExpectSuccess(collectionId: number,638                     tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {639  await usingApi(async (api: ApiPromise) => {640    const allowanceBefore =641      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;642    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);643    const events = await submitTransactionAsync(owner, approveNftTx);644    const result = getCreateItemResult(events);645    // tslint:disable-next-line:no-unused-expression646    expect(result.success).to.be.true;647    const allowanceAfter =648      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;649    expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());650  });651}652653export async function654transferFromExpectSuccess(collectionId: number,655                          tokenId: number,656                          accountApproved: IKeyringPair,657                          accountFrom: IKeyringPair,658                          accountTo: IKeyringPair,659                          value: number | bigint = 1,660                          type: string = 'NFT') {661  await usingApi(async (api: ApiPromise) => {662    let balanceBefore = new BN(0);663    if (type === 'Fungible') {664      balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;665    }666    const transferFromTx = await api.tx.nft.transferFrom(667      accountFrom.address, accountTo.address, collectionId, tokenId, value);668    const events = await submitTransactionAsync(accountApproved, transferFromTx);669    const result = getCreateItemResult(events);670    // tslint:disable-next-line:no-unused-expression671    expect(result.success).to.be.true;672    if (type === 'NFT') {673      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;674      expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);675    }676    if (type === 'Fungible') {677      const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;678      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());679    }680    if (type === 'ReFungible') {681      const nftItemData =682        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;683      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);684      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);685    }686  });687}688689export async function690transferFromExpectFail(collectionId: number,691                       tokenId: number,692                       accountApproved: IKeyringPair,693                       accountFrom: IKeyringPair,694                       accountTo: IKeyringPair,695                       value: number | bigint = 1) {696  await usingApi(async (api: ApiPromise) => {697    const transferFromTx = await api.tx.nft.transferFrom(698      accountFrom.address, accountTo.address, collectionId, tokenId, value);699    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;700    const result = getCreateCollectionResult(events);701    // tslint:disable-next-line:no-unused-expression702    expect(result.success).to.be.false;703  });704}705706export async function707transferExpectSuccess(collectionId: number,708                      tokenId: number,709                      sender: IKeyringPair,710                      recipient: IKeyringPair,711                      value: number | bigint = 1,712                      type: string = 'NFT') {713  await usingApi(async (api: ApiPromise) => {714    let balanceBefore = new BN(0);715    if (type === 'Fungible') {716      balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;717    }718    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);719    const events = await submitTransactionAsync(sender, transferTx);720    const result = getTransferResult(events);721    // tslint:disable-next-line:no-unused-expression722    expect(result.success).to.be.true;723    expect(result.collectionId).to.be.equal(collectionId);724    expect(result.itemId).to.be.equal(tokenId);725    expect(result.sender).to.be.equal(sender.address);726    expect(result.recipient).to.be.equal(recipient.address);727    expect(result.value.toString()).to.be.equal(value.toString());728    if (type === 'NFT') {729      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;730      expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);731    }732    if (type === 'Fungible') {733      const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;734      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());735    }736    if (type === 'ReFungible') {737      const nftItemData =738        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;739      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);740      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);741    }742  });743}744745export async function746transferExpectFail(collectionId: number,747                   tokenId: number,748                   sender: IKeyringPair,749                   recipient: IKeyringPair,750                   value: number | bigint = 1,751                   type: string = 'NFT') {752  await usingApi(async (api: ApiPromise) => {753    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);754    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;755    if (events && Array.isArray(events)) {756      const result = getCreateCollectionResult(events);757      // tslint:disable-next-line:no-unused-expression758      expect(result.success).to.be.false;759    }760  });761}762763export async function764approveExpectFail(collectionId: number,765                  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {766  await usingApi(async (api: ApiPromise) => {767    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);768    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;769    const result = getCreateCollectionResult(events);770    // tslint:disable-next-line:no-unused-expression771    expect(result.success).to.be.false;772  });773}774775export async function getFungibleBalance(776  collectionId: number,777  owner: string,778) {779  return await usingApi(async (api) => {780    const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};781    return BigInt(response.Value);782  });783}784785export async function createFungibleItemExpectSuccess(786  sender: IKeyringPair,787  collectionId: number,788  data: CreateFungibleData,789  owner: string = sender.address,790) {791  return await usingApi(async (api) => {792    const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });793794    const events = await submitTransactionAsync(sender, tx);795    const result = getCreateItemResult(events);796797    expect(result.success).to.be.true;798    return result.itemId;799  });800}801802export async function createItemExpectSuccess(803  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {804  let newItemId: number = 0;805  await usingApi(async (api) => {806    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);807    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();808    const AItemBalance = new BigNumber(Aitem.Value);809810    if (owner === '') {811      owner = sender.address;812    }813814    let tx;815    if (createMode === 'Fungible') {816      const createData = {fungible: {value: 10}};817      tx = api.tx.nft.createItem(collectionId, owner, createData);818    } else if (createMode === 'ReFungible') {819      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};820      tx = api.tx.nft.createItem(collectionId, owner, createData);821    } else {822      tx = api.tx.nft.createItem(collectionId, owner, createMode);823    }824    const events = await submitTransactionAsync(sender, tx);825    const result = getCreateItemResult(events);826827    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);828    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();829    const BItemBalance = new BigNumber(Bitem.Value);830831    // What to expect832    // tslint:disable-next-line:no-unused-expression833    expect(result.success).to.be.true;834    if (createMode === 'Fungible') {835      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);836    } else {837      expect(BItemCount).to.be.equal(AItemCount + 1);838    }839    expect(collectionId).to.be.equal(result.collectionId);840    expect(BItemCount).to.be.equal(result.itemId);841    expect(owner).to.be.equal(result.recipient);842    newItemId = result.itemId;843  });844  return newItemId;845}846847export async function createItemExpectFailure(848  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {849  await usingApi(async (api) => {850    const tx = api.tx.nft.createItem(collectionId, owner, createMode);851    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;852    const result = getCreateItemResult(events);853854    expect(result.success).to.be.false;855  });856}857858export async function setPublicAccessModeExpectSuccess(859  sender: IKeyringPair, collectionId: number,860  accessMode: 'Normal' | 'WhiteList',861) {862  await usingApi(async (api) => {863864    // Run the transaction865    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);866    const events = await submitTransactionAsync(sender, tx);867    const result = getGenericResult(events);868869    // Get the collection870    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();871872    // What to expect873    // tslint:disable-next-line:no-unused-expression874    expect(result.success).to.be.true;875    expect(collection.Access).to.be.equal(accessMode);876  });877}878879export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {880  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');881}882883export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {884  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');885}886887export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {888  await usingApi(async (api) => {889890    // Run the transaction891    const tx = api.tx.nft.setMintPermission(collectionId, enabled);892    const events = await submitTransactionAsync(sender, tx);893    const result = getGenericResult(events);894895    // Get the collection896    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();897898    // What to expect899    // tslint:disable-next-line:no-unused-expression900    expect(result.success).to.be.true;901    expect(collection.MintMode).to.be.equal(enabled);902  });903}904905export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {906  await setMintPermissionExpectSuccess(sender, collectionId, true);907}908909export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {910  await usingApi(async (api) => {911    // Run the transaction912    const tx = api.tx.nft.setMintPermission(collectionId, enabled);913    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;914    const result = getCreateCollectionResult(events);915    // tslint:disable-next-line:no-unused-expression916    expect(result.success).to.be.false;917  });918}919920export async function isWhitelisted(collectionId: number, address: string) {921  let whitelisted: boolean = false;922  await usingApi(async (api) => {923    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;924  });925  return whitelisted;926}927928export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {929  await usingApi(async (api) => {930931    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();932933    // Run the transaction934    const tx = api.tx.nft.addToWhiteList(collectionId, address);935    const events = await submitTransactionAsync(sender, tx);936    const result = getGenericResult(events);937938    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();939940    // What to expect941    // tslint:disable-next-line:no-unused-expression942    expect(result.success).to.be.true;943    // tslint:disable-next-line: no-unused-expression944    expect(whiteListedBefore).to.be.false;945    // tslint:disable-next-line: no-unused-expression946    expect(whiteListedAfter).to.be.true;947  });948}949950export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {951  await usingApi(async (api) => {952    // Run the transaction953    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);954    const events = await submitTransactionAsync(sender, tx);955    const result = getGenericResult(events);956957    // What to expect958    // tslint:disable-next-line:no-unused-expression959    expect(result.success).to.be.true;960  });961}962963export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {964  await usingApi(async (api) => {965    // Run the transaction966    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);967    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;968    const result = getGenericResult(events);969970    // What to expect971    // tslint:disable-next-line:no-unused-expression972    expect(result.success).to.be.false;973  });974}975976export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)977  : Promise<ICollectionInterface | null> => {978  return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;979};980981export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {982  // set global object - collectionsCount983  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();984};985986export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {987  return await usingApi(async (api) => {988    return (await api.query.nft.collection(collectionId)) as unknown as ICollectionInterface;989  });990}