git.delta.rocks / unique-network / refs/commits / 6090f15f03e0

difftreelog

source

tests/src/util/helpers.ts36.5 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 type CrossAccountId = string | {25  substrate: string,26} | {27  ethereum: string,28};29export function normalizeAccountId(input: CrossAccountId): CrossAccountId {30  if (typeof input === 'string')31    return { substrate: input };32  return input;33}3435export const U128_MAX = (1n << 128n) - 1n;3637type GenericResult = {38  success: boolean,39};4041interface CreateCollectionResult {42  success: boolean;43  collectionId: number;44}4546interface CreateItemResult {47  success: boolean;48  collectionId: number;49  itemId: number;50  recipient?: CrossAccountId;51}5253interface TransferResult {54  success: boolean;55  collectionId: number;56  itemId: number;57  sender?: CrossAccountId;58  recipient?: CrossAccountId;59  value: bigint;60}6162interface IReFungibleOwner {63  Fraction: BN;64  Owner: number[];65}6667interface ITokenDataType {68  Owner: number[];69  ConstData: number[];70  VariableData: number[];71}7273interface IFungibleTokenDataType {74  Value: BN;75}7677interface IGetMessage {78  checkMsgNftMethod: string;79  checkMsgTrsMethod: string;80  checkMsgSysMethod: string;81}8283export interface IReFungibleTokenDataType {84  Owner: IReFungibleOwner[];85  ConstData: number[];86  VariableData: number[];87}8889export function nftEventMessage(events: EventRecord[]): IGetMessage {90  let checkMsgNftMethod: string = '';91  let checkMsgTrsMethod: string = '';92  let checkMsgSysMethod: string = '';93  events.forEach(({ event: { method, section } }) => {94    if (section === 'nft') {95      checkMsgNftMethod = method;96    } else if (section === 'treasury') {97      checkMsgTrsMethod = method;98    } else if (section === 'system') {99      checkMsgSysMethod = method;100    } else { return null; }101  });102  const result: IGetMessage = {103    checkMsgNftMethod,104    checkMsgTrsMethod,105    checkMsgSysMethod,106  };107  return result;108}109110export function getGenericResult(events: EventRecord[]): GenericResult {111  const result: GenericResult = {112    success: false,113  };114  events.forEach(({ phase, event: { data, method, section } }) => {115    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);116    if (method === 'ExtrinsicSuccess') {117      result.success = true;118    }119  });120  return result;121}122123124125export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {126  let success = false;127  let collectionId: number = 0;128  events.forEach(({ phase, event: { data, method, section } }) => {129    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);130    if (method == 'ExtrinsicSuccess') {131      success = true;132    } else if ((section == 'nft') && (method == 'CollectionCreated')) {133      collectionId = parseInt(data[0].toString());134    }135  });136  const result: CreateCollectionResult = {137    success,138    collectionId,139  };140  return result;141}142143export function getCreateItemResult(events: EventRecord[]): CreateItemResult {144  let success = false;145  let collectionId: number = 0;146  let itemId: number = 0;147  let recipient;148  events.forEach(({ phase, event: { data, method, section } }) => {149    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);150    if (method == 'ExtrinsicSuccess') {151      success = true;152    } else if ((section == 'nft') && (method == 'ItemCreated')) {153      collectionId = parseInt(data[0].toString());154      itemId = parseInt(data[1].toString());155      recipient = data[2].toJSON();156    }157  });158  const result: CreateItemResult = {159    success,160    collectionId,161    itemId,162    recipient,163  };164  return result;165}166167export function getTransferResult(events: EventRecord[]): TransferResult {168  const result: TransferResult = {169    success: false,170    collectionId: 0,171    itemId: 0,172    value: 0n,173  };174175  events.forEach(({ event: { data, method, section } }) => {176    if (method === 'ExtrinsicSuccess') {177      result.success = true;178    } else if (section === 'nft' && method === 'Transfer') {179      result.collectionId = +data[0].toString();180      result.itemId = +data[1].toString();181      result.sender = data[2].toJSON() as CrossAccountId;182      result.recipient = data[3].toJSON() as CrossAccountId;183      result.value = BigInt(data[4].toString());184    }185  });186187  return result;188}189190interface Invalid {191  type: 'Invalid';192}193194interface Nft {195  type: 'NFT';196}197198interface Fungible {199  type: 'Fungible';200  decimalPoints: number;201}202203interface ReFungible {204  type: 'ReFungible';205}206207type CollectionMode = Nft | Fungible | ReFungible | Invalid;208209export type CreateCollectionParams = {210  mode: CollectionMode,211  name: string,212  description: string,213  tokenPrefix: string,214};215216const defaultCreateCollectionParams: CreateCollectionParams = {217  description: 'description',218  mode: { type: 'NFT' },219  name: 'name',220  tokenPrefix: 'prefix',221}222223export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {224  const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };225226  let collectionId: number = 0;227  await usingApi(async (api) => {228    // Get number of collections before the transaction229    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);230231    // Run the CreateCollection transaction232    const alicePrivateKey = privateKey('//Alice');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    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);246    const events = await submitTransactionAsync(alicePrivateKey, tx);247    const result = getCreateCollectionResult(events);248249    // Get number of collections after the transaction250    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);251252    // Get the collection253    const collection: any = (await api.query.nft.collectionById(result.collectionId) as any).toJSON();254255    // What to expect256    // tslint:disable-next-line:no-unused-expression257    expect(result.success).to.be.true;258    expect(result.collectionId).to.be.equal(BcollectionCount);259    // tslint:disable-next-line:no-unused-expression260    expect(collection).to.be.not.null;261    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');262    expect(collection.Owner).to.be.deep.equal(normalizeAccountId(alicesPublicKey));263    expect(utf16ToStr(collection.Name)).to.be.equal(name);264    expect(utf16ToStr(collection.Description)).to.be.equal(description);265    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);266267    collectionId = result.collectionId;268  });269270  return collectionId;271}272273export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {274  const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };275276  let modeprm = {};277  if (mode.type === 'NFT') {278    modeprm = { nft: null };279  } else if (mode.type === 'Fungible') {280    modeprm = { fungible: mode.decimalPoints };281  } else if (mode.type === 'ReFungible') {282    modeprm = { refungible: null };283  } else if (mode.type === 'Invalid') {284    modeprm = { invalid: null };285  }286287  await usingApi(async (api) => {288    // Get number of collections before the transaction289    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());290291    // Run the CreateCollection transaction292    const alicePrivateKey = privateKey('//Alice');293    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);294    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;295    const result = getCreateCollectionResult(events);296297    // Get number of collections after the transaction298    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());299300    // What to expect301    // tslint:disable-next-line:no-unused-expression302    expect(result.success).to.be.false;303    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');304  });305}306307export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {308  let bal = new BigNumber(0);309  let unused;310  do {311    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;312    const keyring = new Keyring({ type: 'sr25519' });313    unused = keyring.addFromUri(`//${randomSeed}`);314    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());315  } while (bal.toFixed() != '0');316  return unused;317}318319export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {320  return await usingApi(async (api) => {321    const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;322    return BigInt(bn.toString());323  });324}325326export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {327  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));328}329330export async function findNotExistingCollection(api: ApiPromise): Promise<number> {331  const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;332  const newCollection: number = totalNumber + 1;333  return newCollection;334}335336function getDestroyResult(events: EventRecord[]): boolean {337  let success: boolean = false;338  events.forEach(({ phase, event: { data, method, section } }) => {339    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);340    if (method == 'ExtrinsicSuccess') {341      success = true;342    }343  });344  return success;345}346347export async function destroyCollectionExpectFailure(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    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;353  });354}355356export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {357  await usingApi(async (api) => {358    // Run the DestroyCollection transaction359    const alicePrivateKey = privateKey(senderSeed);360    const tx = api.tx.nft.destroyCollection(collectionId);361    const events = await submitTransactionAsync(alicePrivateKey, tx);362    const result = getDestroyResult(events);363364    // Get the collection365    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();366367    // What to expect368    expect(result).to.be.true;369    expect(collection).to.be.null;370  });371}372373export async function queryCollectionLimits(collectionId: number) {374  return await usingApi(async (api) => {375    return ((await api.query.nft.collectionById(collectionId)).toJSON() as any).Limits;376  });377}378379export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {380  await usingApi(async (api) => {381    const oldLimits = await queryCollectionLimits(collectionId);382    const newLimits = { ...oldLimits as any, ...limits };383    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);384    const events = await submitTransactionAsync(sender, tx);385    const result = getGenericResult(events);386387    expect(result.success).to.be.true;388  });389}390391export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {392  await usingApi(async (api) => {393    const oldLimits = await queryCollectionLimits(collectionId);394    const newLimits = { ...oldLimits as any, ...limits };395    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);396    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;397    const result = getGenericResult(events);398399    expect(result.success).to.be.false;400  });401}402403export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {404  await usingApi(async (api) => {405406    // Run the transaction407    const alicePrivateKey = privateKey('//Alice');408    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);409    const events = await submitTransactionAsync(alicePrivateKey, tx);410    const result = getGenericResult(events);411412    // Get the collection413    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();414415    // What to expect416    expect(result.success).to.be.true;417    expect(collection.Sponsorship).to.deep.equal({418      unconfirmed: sponsor,419    });420  });421}422423export async function removeCollectionSponsorExpectSuccess(collectionId: number) {424  await usingApi(async (api) => {425426    // Run the transaction427    const alicePrivateKey = privateKey('//Alice');428    const tx = api.tx.nft.removeCollectionSponsor(collectionId);429    const events = await submitTransactionAsync(alicePrivateKey, tx);430    const result = getGenericResult(events);431432    // Get the collection433    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();434435    // What to expect436    expect(result.success).to.be.true;437    expect(collection.Sponsorship).to.be.deep.equal({ disabled: null });438  });439}440441export async function removeCollectionSponsorExpectFailure(collectionId: number) {442  await usingApi(async (api) => {443444    // Run the transaction445    const alicePrivateKey = privateKey('//Alice');446    const tx = api.tx.nft.removeCollectionSponsor(collectionId);447    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;448  });449}450451export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {452  await usingApi(async (api) => {453454    // Run the transaction455    const alicePrivateKey = privateKey(senderSeed);456    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);457    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;458  });459}460461export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {462  await usingApi(async (api) => {463464    // Run the transaction465    const sender = privateKey(senderSeed);466    const tx = api.tx.nft.confirmSponsorship(collectionId);467    const events = await submitTransactionAsync(sender, tx);468    const result = getGenericResult(events);469470    // Get the collection471    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();472473    // What to expect474    expect(result.success).to.be.true;475    expect(collection.Sponsorship).to.be.deep.equal({476      confirmed: sender.address,477    });478  });479}480481482export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {483  await usingApi(async (api) => {484485    // Run the transaction486    const sender = privateKey(senderSeed);487    const tx = api.tx.nft.confirmSponsorship(collectionId);488    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;489  });490}491492export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {493  await usingApi(async (api) => {494    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);495    const events = await submitTransactionAsync(sender, tx);496    const result = getGenericResult(events);497498    expect(result.success).to.be.true;499  });500}501502export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {503  await usingApi(async (api) => {504    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);505    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;506    const result = getGenericResult(events);507508    expect(result.success).to.be.false;509  });510}511512export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {513  await usingApi(async (api) => {514    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);515    const events = await submitTransactionAsync(sender, tx);516    const result = getGenericResult(events);517518    expect(result.success).to.be.true;519  });520}521522export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {523  await usingApi(async (api) => {524    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);525    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;526    const result = getGenericResult(events);527528    expect(result.success).to.be.false;529  });530}531532export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {533  await usingApi(async (api) => {534    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);535    const events = await submitTransactionAsync(sender, tx);536    const result = getGenericResult(events);537538    expect(result.success).to.be.true;539  });540}541542export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {543  let whitelisted: boolean = false;544  await usingApi(async (api) => {545    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;546  });547  return whitelisted;548}549550export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {551  await usingApi(async (api) => {552    const tx = api.tx.nft.addToContractWhiteList(contractAddress.toString(), user.toString());553    const events = await submitTransactionAsync(sender, tx);554    const result = getGenericResult(events);555556    expect(result.success).to.be.true;557  });558}559560export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {561  await usingApi(async (api) => {562    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());563    const events = await submitTransactionAsync(sender, tx);564    const result = getGenericResult(events);565566    expect(result.success).to.be.true;567  });568}569570export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {571  await usingApi(async (api) => {572    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());573    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;574    const result = getGenericResult(events);575576    expect(result.success).to.be.false;577  });578}579580export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {581  await usingApi(async (api) => {582    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));583    const events = await submitTransactionAsync(sender, tx);584    const result = getGenericResult(events);585586    expect(result.success).to.be.true;587  });588}589590export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {591  await usingApi(async (api) => {592    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));593    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;594  });595}596597export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {598  await usingApi(async (api) => {599    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));600    const events = await submitTransactionAsync(sender, tx);601    const result = getGenericResult(events);602603    expect(result.success).to.be.true;604  });605}606607export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {608  await usingApi(async (api) => {609    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));610    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;611  });612}613614export interface CreateFungibleData {615  readonly Value: bigint;616}617618export interface CreateReFungibleData { }619export interface CreateNftData { }620621export type CreateItemData = {622  NFT: CreateNftData;623} | {624  Fungible: CreateFungibleData;625} | {626  ReFungible: CreateReFungibleData;627};628629export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {630  await usingApi(async (api) => {631    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);632    const events = await submitTransactionAsync(owner, tx);633    const result = getGenericResult(events);634    // Get the item635    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();636    // What to expect637    // tslint:disable-next-line:no-unused-expression638    expect(result.success).to.be.true;639    // tslint:disable-next-line:no-unused-expression640    expect(item).to.be.null;641  });642}643644export async function645  approveExpectSuccess(collectionId: number,646    tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {647  await usingApi(async (api: ApiPromise) => {648    const allowanceBefore =649      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;650    const approveNftTx = api.tx.nft.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);651    const events = await submitTransactionAsync(owner, approveNftTx);652    const result = getCreateItemResult(events);653    // tslint:disable-next-line:no-unused-expression654    expect(result.success).to.be.true;655    const allowanceAfter =656      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;657    expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());658  });659}660661export async function662  transferFromExpectSuccess(collectionId: number,663    tokenId: number,664    accountApproved: IKeyringPair,665    accountFrom: IKeyringPair,666    accountTo: IKeyringPair,667    value: number | bigint = 1,668    type: string = 'NFT') {669  await usingApi(async (api: ApiPromise) => {670    let balanceBefore = new BN(0);671    if (type === 'Fungible') {672      balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;673    }674    const transferFromTx = api.tx.nft.transferFrom(675      normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);676    const events = await submitTransactionAsync(accountApproved, transferFromTx);677    const result = getCreateItemResult(events);678    // tslint:disable-next-line:no-unused-expression679    expect(result.success).to.be.true;680    if (type === 'NFT') {681      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId) as any).toJSON() as ITokenDataType;682      expect(nftItemData.Owner).to.be.deep.equal(normalizeAccountId(accountTo.address));683    }684    if (type === 'Fungible') {685      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, accountTo.address) as any).Value as unknown as BN;686      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());687    }688    if (type === 'ReFungible') {689      const nftItemData =690        (await api.query.nft.reFungibleItemList(collectionId, tokenId) as any).toJSON() as IReFungibleTokenDataType;691      expect(nftItemData.Owner[0].Owner).to.be.deep.equal(normalizeAccountId(accountTo.address));692      expect(nftItemData.Owner[0].Fraction).to.be.equal(value);693    }694  });695}696697export async function698  transferFromExpectFail(collectionId: number,699    tokenId: number,700    accountApproved: IKeyringPair,701    accountFrom: IKeyringPair,702    accountTo: IKeyringPair,703    value: number | bigint = 1) {704  await usingApi(async (api: ApiPromise) => {705    const transferFromTx = api.tx.nft.transferFrom(706      normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);707    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;708    const result = getCreateCollectionResult(events);709    // tslint:disable-next-line:no-unused-expression710    expect(result.success).to.be.false;711  });712}713714export async function715  transferExpectSuccess(collectionId: number,716    tokenId: number,717    sender: IKeyringPair,718    recipient: IKeyringPair,719    value: number | bigint = 1,720    type: string = 'NFT') {721  await usingApi(async (api: ApiPromise) => {722    let balanceBefore = new BN(0);723    if (type === 'Fungible') {724      balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;725    }726    const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);727    const events = await submitTransactionAsync(sender, transferTx);728    const result = getTransferResult(events);729    // tslint:disable-next-line:no-unused-expression730    expect(result.success).to.be.true;731    expect(result.collectionId).to.be.equal(collectionId);732    expect(result.itemId).to.be.equal(tokenId);733    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));734    expect(result.recipient).to.be.deep.equal(normalizeAccountId(recipient.address));735    expect(result.value.toString()).to.be.equal(value.toString());736    if (type === 'NFT') {737      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;738      expect(nftItemData.Owner).to.be.deep.equal(normalizeAccountId(recipient.address));739    }740    if (type === 'Fungible') {741      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, recipient.address) as any).Value as unknown as BN;742      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());743    }744    if (type === 'ReFungible') {745      const nftItemData =746        (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON() as unknown as IReFungibleTokenDataType;747      expect(nftItemData.Owner[0].Owner).to.be.deep.equal(normalizeAccountId(recipient.address));748      expect(nftItemData.Owner[0].Fraction.toString()).to.be.equal(value.toString());749    }750  });751}752753export async function754  transferExpectFail(collectionId: number,755    tokenId: number,756    sender: IKeyringPair,757    recipient: IKeyringPair,758    value: number | bigint = 1,759    type: string = 'NFT') {760  await usingApi(async (api: ApiPromise) => {761    const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);762    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;763    if (events && Array.isArray(events)) {764      const result = getCreateCollectionResult(events);765      // tslint:disable-next-line:no-unused-expression766      expect(result.success).to.be.false;767    }768  });769}770771export async function772  approveExpectFail(collectionId: number,773    tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {774  await usingApi(async (api: ApiPromise) => {775    const approveNftTx = api.tx.nft.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);776    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;777    const result = getCreateCollectionResult(events);778    // tslint:disable-next-line:no-unused-expression779    expect(result.success).to.be.false;780  });781}782783export async function getFungibleBalance(784  collectionId: number,785  owner: string,786) {787  return await usingApi(async (api) => {788    const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as { Value: string };789    return BigInt(response.Value);790  });791}792793export async function createFungibleItemExpectSuccess(794  sender: IKeyringPair,795  collectionId: number,796  data: CreateFungibleData,797  owner: CrossAccountId = sender.address,798) {799  return await usingApi(async (api) => {800    const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), { Fungible: data });801802    const events = await submitTransactionAsync(sender, tx);803    const result = getCreateItemResult(events);804805    expect(result.success).to.be.true;806    return result.itemId;807  });808}809810export async function createItemExpectSuccess(811  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {812  let newItemId: number = 0;813  await usingApi(async (api) => {814    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);815    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();816    const AItemBalance = new BigNumber(Aitem.Value);817818    let tx;819    if (createMode === 'Fungible') {820      const createData = { fungible: { value: 10 } };821      tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), createData);822    } else if (createMode === 'ReFungible') {823      const createData = { refungible: { const_data: [], variable_data: [], pieces: 100 } };824      tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), createData);825    } else {826      tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), createMode);827    }828829    const events = await submitTransactionAsync(sender, tx);830    const result = getCreateItemResult(events);831832    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);833    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();834    const BItemBalance = new BigNumber(Bitem.Value);835836    // What to expect837    // tslint:disable-next-line:no-unused-expression838    expect(result.success).to.be.true;839    if (createMode === 'Fungible') {840      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);841    } else {842      expect(BItemCount).to.be.equal(AItemCount + 1);843    }844    expect(collectionId).to.be.equal(result.collectionId);845    expect(BItemCount.toString()).to.be.equal(result.itemId.toString());846    expect(normalizeAccountId(owner)).to.be.deep.equal(result.recipient);847    newItemId = result.itemId;848  });849  return newItemId;850}851852export async function createItemExpectFailure(853  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {854  await usingApi(async (api) => {855    const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), createMode);856    857    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;858    const result = getCreateItemResult(events);859860    expect(result.success).to.be.false;861  });862}863864export async function setPublicAccessModeExpectSuccess(865  sender: IKeyringPair, collectionId: number,866  accessMode: 'Normal' | 'WhiteList',867) {868  await usingApi(async (api) => {869870    // Run the transaction871    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);872    const events = await submitTransactionAsync(sender, tx);873    const result = getGenericResult(events);874875    // Get the collection876    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();877878    // What to expect879    // tslint:disable-next-line:no-unused-expression880    expect(result.success).to.be.true;881    expect(collection.Access).to.be.equal(accessMode);882  });883}884885export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {886  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');887}888889export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {890  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');891}892893export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {894  await usingApi(async (api) => {895896    // Run the transaction897    const tx = api.tx.nft.setMintPermission(collectionId, enabled);898    const events = await submitTransactionAsync(sender, tx);899    const result = getGenericResult(events);900901    // Get the collection902    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();903904    // What to expect905    // tslint:disable-next-line:no-unused-expression906    expect(result.success).to.be.true;907    expect(collection.MintMode).to.be.equal(enabled);908  });909}910911export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {912  await setMintPermissionExpectSuccess(sender, collectionId, true);913}914915export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {916  await usingApi(async (api) => {917    // Run the transaction918    const tx = api.tx.nft.setMintPermission(collectionId, enabled);919    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;920    const result = getCreateCollectionResult(events);921    // tslint:disable-next-line:no-unused-expression922    expect(result.success).to.be.false;923  });924}925926export async function isWhitelisted(collectionId: number, address: string) {927  let whitelisted: boolean = false;928  await usingApi(async (api) => {929    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;930  });931  return whitelisted;932}933934export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {935  await usingApi(async (api) => {936937    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();938939    // Run the transaction940    const tx = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(address));941    const events = await submitTransactionAsync(sender, tx);942    const result = getGenericResult(events);943944    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();945946    // What to expect947    // tslint:disable-next-line:no-unused-expression948    expect(result.success).to.be.true;949    // tslint:disable-next-line: no-unused-expression950    expect(whiteListedBefore).to.be.false;951    // tslint:disable-next-line: no-unused-expression952    expect(whiteListedAfter).to.be.true;953  });954}955956export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {957  await usingApi(async (api) => {958    // Run the transaction959    const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));960    const events = await submitTransactionAsync(sender, tx);961    const result = getGenericResult(events);962963    // What to expect964    // tslint:disable-next-line:no-unused-expression965    expect(result.success).to.be.true;966  });967}968969export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {970  await usingApi(async (api) => {971    // Run the transaction972    const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));973    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;974    const result = getGenericResult(events);975976    // What to expect977    // tslint:disable-next-line:no-unused-expression978    expect(result.success).to.be.false;979  });980}981982export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)983  : Promise<ICollectionInterface | null> => {984  return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;985};986987export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {988  // set global object - collectionsCount989  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();990};991992export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {993  return await usingApi(async (api) => {994    return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;995  });996}