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

difftreelog

source

tests/src/util/helpers.ts39.4 KiBsourcehistory
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import { ApiPromise, Keyring } from '@polkadot/api';7import { Enum, Struct } from '@polkadot/types/codec';8import type { AccountId, BlockNumber, Call, 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';20import { Compact, Option, Raw, Vec } from '@polkadot/types/codec';21// import { AccountId, AccountIdOf, AccountIndex, Address, AssetId, Balance, BalanceOf, Block, BlockNumber, Call, ChangesTrieConfiguration, Consensus, ConsensusEngineId, Digest, DigestItem, DispatchClass, DispatchInfo, DispatchInfoTo190, EcdsaSignature, Ed25519Signature, Extrinsic, ExtrinsicEra, ExtrinsicPayload, ExtrinsicPayloadUnknown, ExtrinsicPayloadV1, ExtrinsicPayloadV2, ExtrinsicPayloadV3, ExtrinsicPayloadV4, ExtrinsicSignatureV1, ExtrinsicSignatureV2, ExtrinsicSignatureV3, ExtrinsicSignatureV4, ExtrinsicUnknown, ExtrinsicV1, ExtrinsicV2, ExtrinsicV3, ExtrinsicV4, Hash, Header, ImmortalEra, Index, Justification, KeyTypeId, KeyValue, LockIdentifier, LookupSource, LookupTarget, Moment, MortalEra, MultiSignature, Origin, Perbill, Percent, Permill, Perquintill, Phantom, PhantomData, PreRuntime, Seal, SealV0, Signature, SignedBlock, SignerPayload, Sr25519Signature, ValidatorId, Weight, WeightMultiplier } from '@polkadot/types/interfaces/runtime';2223chai.use(chaiAsPromised);24const expect = chai.expect;2526export const U128_MAX = (1n << 128n) - 1n;2728type GenericResult = {29  success: boolean,30};3132interface CreateCollectionResult {33  success: boolean;34  collectionId: number;35}3637interface CreateItemResult {38  success: boolean;39  collectionId: number;40  itemId: number;41  recipient: string;42}4344interface TransferResult {45  success: boolean;46  collectionId: number;47  itemId: number;48  sender: string;49  recipient: string;50  value: bigint;51}5253interface IReFungibleOwner {54  Fraction: BN;55  Owner: number[];56}5758interface ITokenDataType {59  Owner: number[];60  ConstData: number[];61  VariableData: number[];62}6364interface IFungibleTokenDataType {65  Value: BN;66}6768interface IGetMessage {69  checkMsgNftMethod: string;70  checkMsgTrsMethod: string;71  checkMsgSysMethod: string;72}7374export interface IReFungibleTokenDataType {75  Owner: IReFungibleOwner[];76  ConstData: number[];77  VariableData: number[];78}7980export function nftEventMessage(events: EventRecord[]): IGetMessage {81  let checkMsgNftMethod: string = '';82  let checkMsgTrsMethod: string = '';83  let checkMsgSysMethod: string = '';84  events.forEach(({ event: { method, section } }) => {85    if (section === 'nft') {86      checkMsgNftMethod = method;87    } else if (section === 'treasury') {88      checkMsgTrsMethod = method;89    } else if (section === 'system') {90      checkMsgSysMethod = method;91    } else { return null; }92  });93  const result: IGetMessage = {94    checkMsgNftMethod,95    checkMsgTrsMethod,96    checkMsgSysMethod,97  };98  return result;99}100101export function getGenericResult(events: EventRecord[]): GenericResult {102  const result: GenericResult = {103    success: false,104  };105  events.forEach(({ phase, event: { data, method, section } }) => {106    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);107    if (method === 'ExtrinsicSuccess') {108      result.success = true;109    }110  });111  return result;112}113114115116export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {117  let success = false;118  let collectionId: number = 0;119  events.forEach(({ phase, event: { data, method, section } }) => {120    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);121    if (method == 'ExtrinsicSuccess') {122      success = true;123    } else if ((section == 'nft')  && (method == 'CollectionCreated')) {124      collectionId = parseInt(data[0].toString());125    }126  });127  const result: CreateCollectionResult = {128    success,129    collectionId,130  };131  return result;132}133134export function getCreateItemResult(events: EventRecord[]): CreateItemResult {135  let success = false;136  let collectionId: number = 0;137  let itemId: number = 0;138  let recipient: string = '';139  events.forEach(({ phase, event: { data, method, section } }) => {140    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);141    if (method == 'ExtrinsicSuccess') {142      success = true;143    } else if ((section == 'nft') && (method == 'ItemCreated')) {144      collectionId = parseInt(data[0].toString());145      itemId = parseInt(data[1].toString());146      recipient = data[2].toString();147    }148  });149  const result: CreateItemResult = {150    success,151    collectionId,152    itemId,153    recipient,154  };155  return result;156}157158export function getTransferResult(events: EventRecord[]): TransferResult {159  const result: TransferResult = {160    success: false,161    collectionId: 0,162    itemId: 0,163    sender: '',164    recipient: '',165    value: 0n,166  };167168  events.forEach(({event: {data, method, section}}) => {169    if (method === 'ExtrinsicSuccess') {170      result.success = true;171    } else if (section === 'nft' && method === 'Transfer') {172      result.collectionId = +data[0].toString();173      result.itemId = +data[1].toString();174      result.sender = data[2].toString();175      result.recipient = data[3].toString();176      result.value = BigInt(data[4].toString());177    }178  });179180  return result;181}182183interface Invalid {184  type: 'Invalid';185}186187interface Nft {188  type: 'NFT';189}190191interface Fungible {192  type: 'Fungible';193  decimalPoints: number;194}195196interface ReFungible {197  type: 'ReFungible';198}199200type CollectionMode = Nft | Fungible | ReFungible | Invalid;201202export type CreateCollectionParams = {203  mode: CollectionMode,204  name: string,205  description: string,206  tokenPrefix: string,207};208209const defaultCreateCollectionParams: CreateCollectionParams = {210  description: 'description',211  mode: { type: 'NFT' },212  name: 'name',213  tokenPrefix: 'prefix',214}215216export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {217  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};218219  let collectionId: number = 0;220  await usingApi(async (api) => {221    // Get number of collections before the transaction222    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);223224    // Run the CreateCollection transaction225    const alicePrivateKey = privateKey('//Alice');226227    let modeprm = {};228    if (mode.type === 'NFT') {229      modeprm = {nft: null};230    } else if (mode.type === 'Fungible') {231      modeprm = {fungible: mode.decimalPoints};232    } else if (mode.type === 'ReFungible') {233      modeprm = {refungible: null};234    } else if (mode.type === 'Invalid') {235      modeprm = {invalid: null};236    }237238    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);239    const events = await submitTransactionAsync(alicePrivateKey, tx);240    const result = getCreateCollectionResult(events);241242    // Get number of collections after the transaction243    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);244245    // Get the collection246    const collection: any = (await api.query.nft.collectionById(result.collectionId)).toJSON();247248    // What to expect249    // tslint:disable-next-line:no-unused-expression250    expect(result.success).to.be.true;251    expect(result.collectionId).to.be.equal(BcollectionCount);252    // tslint:disable-next-line:no-unused-expression253    expect(collection).to.be.not.null;254    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');255    expect(collection.Owner).to.be.equal(alicesPublicKey);256    expect(utf16ToStr(collection.Name)).to.be.equal(name);257    expect(utf16ToStr(collection.Description)).to.be.equal(description);258    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);259260    collectionId = result.collectionId;261  });262263  return collectionId;264}265266export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {267  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};268269  let modeprm = {};270  if (mode.type === 'NFT') {271    modeprm = {nft: null};272  } else if (mode.type === 'Fungible') {273    modeprm = {fungible: mode.decimalPoints};274  } else if (mode.type === 'ReFungible') {275    modeprm = {refungible: null};276  } else if (mode.type === 'Invalid') {277    modeprm = {invalid: null};278  }279280  await usingApi(async (api) => {281    // Get number of collections before the transaction282    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());283284    // Run the CreateCollection transaction285    const alicePrivateKey = privateKey('//Alice');286    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);287    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;288    const result = getCreateCollectionResult(events);289290    // Get number of collections after the transaction291    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());292293    // What to expect294    // tslint:disable-next-line:no-unused-expression295    expect(result.success).to.be.false;296    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');297  });298}299300export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {301  let bal = new BigNumber(0);302  let unused;303  do {304    const randomSeed = 'seed' +  Math.floor(Math.random() * Math.floor(10000)) + seedAddition;305    const keyring = new Keyring({ type: 'sr25519' });306    unused = keyring.addFromUri(`//${randomSeed}`);307    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());308  } while (bal.toFixed() != '0');309  return unused;310}311312export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {313  return await usingApi(async (api) => {314    const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;315    return BigInt(bn.toString());316  });317}318319export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {320  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));321}322323export async function findNotExistingCollection(api: ApiPromise): Promise<number> {324  const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;325  const newCollection: number = totalNumber + 1;326  return newCollection;327}328329function getDestroyResult(events: EventRecord[]): boolean {330  let success: boolean = false;331  events.forEach(({ phase, event: { data, method, section } }) => {332    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);333    if (method == 'ExtrinsicSuccess') {334      success = true;335    }336  });337  return success;338}339340export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {341  await usingApi(async (api) => {342    // Run the DestroyCollection transaction343    const alicePrivateKey = privateKey(senderSeed);344    const tx = api.tx.nft.destroyCollection(collectionId);345    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;346  });347}348349export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {350  await usingApi(async (api) => {351    // Run the DestroyCollection transaction352    const alicePrivateKey = privateKey(senderSeed);353    const tx = api.tx.nft.destroyCollection(collectionId);354    const events = await submitTransactionAsync(alicePrivateKey, tx);355    const result = getDestroyResult(events);356357    // Get the collection358    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();359360    // What to expect361    expect(result).to.be.true;362    expect(collection).to.be.null;363  });364}365366export async function queryCollectionLimits(collectionId: number) {367  return await usingApi(async (api) => {368    return ((await api.query.nft.collectionById(collectionId)).toJSON() as any).Limits;369  });370}371372export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {373  await usingApi(async (api) => {374    const oldLimits = await queryCollectionLimits(collectionId);375    const newLimits = { ...oldLimits as any, ...limits };376    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);377    const events = await submitTransactionAsync(sender, tx);378    const result = getGenericResult(events);379380    expect(result.success).to.be.true;381  });382}383384export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {385  await usingApi(async (api) => {386    const oldLimits = await queryCollectionLimits(collectionId);387    const newLimits = { ...oldLimits as any, ...limits };388    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);389    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;390    const result = getGenericResult(events);391392    expect(result.success).to.be.false;393  });394}395396export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {397  await usingApi(async (api) => {398399    // Run the transaction400    const alicePrivateKey = privateKey('//Alice');401    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);402    const events = await submitTransactionAsync(alicePrivateKey, tx);403    const result = getGenericResult(events);404405    // Get the collection406    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();407408    // What to expect409    expect(result.success).to.be.true;410    expect(collection.Sponsorship).to.deep.equal({411      Unconfirmed: sponsor.toString(),412    });413  });414}415416export async function removeCollectionSponsorExpectSuccess(collectionId: number) {417  await usingApi(async (api) => {418419    // Run the transaction420    const alicePrivateKey = privateKey('//Alice');421    const tx = api.tx.nft.removeCollectionSponsor(collectionId);422    const events = await submitTransactionAsync(alicePrivateKey, tx);423    const result = getGenericResult(events);424425    // Get the collection426    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();427428    // What to expect429    expect(result.success).to.be.true;430    expect(collection.Sponsorship).to.be.deep.equal({ Disabled: null });431  });432}433434export async function removeCollectionSponsorExpectFailure(collectionId: number) {435  await usingApi(async (api) => {436437    // Run the transaction438    const alicePrivateKey = privateKey('//Alice');439    const tx = api.tx.nft.removeCollectionSponsor(collectionId);440    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;441  });442}443444export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {445  await usingApi(async (api) => {446447    // Run the transaction448    const alicePrivateKey = privateKey(senderSeed);449    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);450    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;451  });452}453454export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {455  await usingApi(async (api) => {456457    // Run the transaction458    const sender = privateKey(senderSeed);459    const tx = api.tx.nft.confirmSponsorship(collectionId);460    const events = await submitTransactionAsync(sender, tx);461    const result = getGenericResult(events);462463    // Get the collection464    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();465466    // What to expect467    expect(result.success).to.be.true;468    expect(collection.Sponsorship).to.be.deep.equal({469      Confirmed: sender.address,470    });471  });472}473474475export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {476  await usingApi(async (api) => {477478    // Run the transaction479    const sender = privateKey(senderSeed);480    const tx = api.tx.nft.confirmSponsorship(collectionId);481    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;482  });483}484485export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {486  await usingApi(async (api) => {487    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);488    const events = await submitTransactionAsync(sender, tx);489    const result = getGenericResult(events);490491    expect(result.success).to.be.true;492  });493}494495export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {496  await usingApi(async (api) => {497    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);498    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;499    const result = getGenericResult(events);500501    expect(result.success).to.be.false;502  });503}504505export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {506  await usingApi(async (api) => {507    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);508    const events = await submitTransactionAsync(sender, tx);509    const result = getGenericResult(events);510511    expect(result.success).to.be.true;512  });513}514515export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {516  await usingApi(async (api) => {517    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);518    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;519    const result = getGenericResult(events);520521    expect(result.success).to.be.false;522  });523}524525export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {526  await usingApi(async (api) => {527    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);528    const events = await submitTransactionAsync(sender, tx);529    const result = getGenericResult(events);530531    expect(result.success).to.be.true;532  });533}534535export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {536  let whitelisted: boolean = false;537  await usingApi(async (api) => {538    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;539  });540  return whitelisted;541}542543export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {544  await usingApi(async (api) => {545    const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);546    const events = await submitTransactionAsync(sender, tx);547    const result = getGenericResult(events);548549    expect(result.success).to.be.true;550  });551}552553export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {554  await usingApi(async (api) => {555    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);556    const events = await submitTransactionAsync(sender, tx);557    const result = getGenericResult(events);558559    expect(result.success).to.be.true;560  });561}562563export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {564  await usingApi(async (api) => {565    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);566    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;567    const result = getGenericResult(events);568569    expect(result.success).to.be.false;570  });571}572573export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {574  await usingApi(async (api) => {575    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));576    const events = await submitTransactionAsync(sender, tx);577    const result = getGenericResult(events);578579    expect(result.success).to.be.true;580  });581}582583export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {584  await usingApi(async (api) => {585    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));586    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;587  });588}589590export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {591  await usingApi(async (api) => {592    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));593    const events = await submitTransactionAsync(sender, tx);594    const result = getGenericResult(events);595596    expect(result.success).to.be.true;597  });598}599600export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {601  await usingApi(async (api) => {602    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));603    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;604  });605}606607export interface CreateFungibleData {608  readonly Value: bigint;609}610611export interface CreateReFungibleData { }612export interface CreateNftData { }613614export type CreateItemData = {615  NFT: CreateNftData;616} | {617  Fungible: CreateFungibleData;618} | {619  ReFungible: CreateReFungibleData;620};621622export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {623  await usingApi(async (api) => {624    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);625    const events = await submitTransactionAsync(owner, tx);626    const result = getGenericResult(events);627    // Get the item628    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();629    // What to expect630    // tslint:disable-next-line:no-unused-expression631    expect(result.success).to.be.true;632    // tslint:disable-next-line:no-unused-expression633    expect(item).to.be.null;634  });635}636637export async function638approveExpectSuccess(collectionId: number,639                     tokenId: number, owner: IKeyringPair, approved: IKeyringPair | string, amount: number | bigint = 1) {640  if (typeof approved !== 'string')641    approved = approved.address;642  await usingApi(async (api: ApiPromise) => {643    const allowanceBefore =644      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved] as any) as unknown as BN;645    const approveNftTx = await api.tx.nft.approve(approved, collectionId, tokenId, amount);646    const events = await submitTransactionAsync(owner, approveNftTx);647    const result = getCreateItemResult(events);648    // tslint:disable-next-line:no-unused-expression649    expect(result.success).to.be.true;650    const allowanceAfter =651      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved] as any) as unknown as BN;652    expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());653  });654}655656export async function657transferFromExpectSuccess(collectionId: number,658                          tokenId: number,659                          accountApproved: IKeyringPair,660                          accountFrom: IKeyringPair | string,661                          accountTo: IKeyringPair,662                          value: number | bigint = 1,663                          type: string = 'NFT') {664  if (typeof accountFrom !== 'string')665    accountFrom = accountFrom.address;666  await usingApi(async (api: ApiPromise) => {667    let balanceBefore = new BN(0);668    if (type === 'Fungible') {669      balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;670    }671    const transferFromTx = await api.tx.nft.transferFrom(672      accountFrom, accountTo.address, collectionId, tokenId, value);673    const events = await submitTransactionAsync(accountApproved, transferFromTx);674    const result = getCreateItemResult(events);675    // tslint:disable-next-line:no-unused-expression676    expect(result.success).to.be.true;677    if (type === 'NFT') {678      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap() as ITokenDataType;679      expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);680    }681    if (type === 'Fungible') {682      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, accountTo.address) as any).Value as unknown as BN;683      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());684    }685    if (type === 'ReFungible') {686      const nftItemData =687        (await api.query.nft.reFungibleItemList(collectionId, tokenId) as any).unwrap() as IReFungibleTokenDataType;688      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);689      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);690    }691  });692}693694export async function695transferFromExpectFail(collectionId: number,696                       tokenId: number,697                       accountApproved: IKeyringPair,698                       accountFrom: IKeyringPair,699                       accountTo: IKeyringPair,700                       value: number | bigint = 1) {701  await usingApi(async (api: ApiPromise) => {702    const transferFromTx = await api.tx.nft.transferFrom(703      accountFrom.address, accountTo.address, collectionId, tokenId, value);704    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;705    const result = getCreateCollectionResult(events);706    // tslint:disable-next-line:no-unused-expression707    expect(result.success).to.be.false;708  });709}710711async function getBlockNumber(api: ApiPromise): Promise<number> {712  return new Promise<number>(async (resolve, reject) => {713    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {714        unsubscribe();715        resolve(head.number.toNumber());716    });717  });718}719720export async function721scheduleTransferExpectSuccess(collectionId: number,722                      tokenId: number,723                      sender: IKeyringPair,724                      recipient: IKeyringPair,725                      value: number | bigint = 1,726                      type: string = 'NFT') {727  await usingApi(async (api: ApiPromise) => {728    let balanceBefore = new BN(0);729730731    let blockNumber: number | undefined = await getBlockNumber(api);732    let expectedBlockNumber = blockNumber + 2;733734    expect(blockNumber).to.be.greaterThan(0);735    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value); 736    const scheduleTx = await api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx);737738    const events = await submitTransactionAsync(sender, scheduleTx);739740    const sponsorBalanceBefore = new BigNumber((await api.query.system.account(sender.address)).data.free.toString());741    const recipientBalanceBefore = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());742743    const nftItemDataBefore = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;744    expect(nftItemDataBefore.Owner.toString()).to.be.equal(sender.address);745746    // sleep for 2 blocks747    await new Promise(resolve => setTimeout(resolve, 6000 * 2));748749    const sponsorBalanceAfter = new BigNumber((await api.query.system.account(sender.address)).data.free.toString());750    const recipientBalanceAfter = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());751752    const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;753    expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);754    expect(recipientBalanceAfter.toNumber()).to.be.equal(recipientBalanceBefore.toNumber());755  });756}757758759export async function760transferExpectSuccess(collectionId: number,761                      tokenId: number,762                      sender: IKeyringPair,763                      recipient: IKeyringPair,764                      value: number | bigint = 1,765                      type: string = 'NFT') {766  await usingApi(async (api: ApiPromise) => {767    let balanceBefore = new BN(0);768    if (type === 'Fungible') {769      balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;770    }771    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);772    const events = await submitTransactionAsync(sender, transferTx);773    const result = getTransferResult(events);774    // tslint:disable-next-line:no-unused-expression775    expect(result.success).to.be.true;776    expect(result.collectionId).to.be.equal(collectionId);777    expect(result.itemId).to.be.equal(tokenId);778    expect(result.sender).to.be.equal(sender.address);779    expect(result.recipient).to.be.equal(recipient.address);780    expect(result.value.toString()).to.be.equal(value.toString());781    if (type === 'NFT') {782      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;783      expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);784    }785    if (type === 'Fungible') {786      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, recipient.address) as any).Value as unknown as BN;787      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());788    }789    if (type === 'ReFungible') {790      const nftItemData =791        (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON() as unknown as IReFungibleTokenDataType;792      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);793      expect(nftItemData.Owner[0].Fraction.toString()).to.be.equal(value.toString());794    }795  });796}797798export async function799transferExpectFail(collectionId: number,800                   tokenId: number,801                   sender: IKeyringPair,802                   recipient: IKeyringPair,803                   value: number | bigint = 1,804                   type: string = 'NFT') {805  await usingApi(async (api: ApiPromise) => {806    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);807    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;808    if (events && Array.isArray(events)) {809      const result = getCreateCollectionResult(events);810      // tslint:disable-next-line:no-unused-expression811      expect(result.success).to.be.false;812    }813  });814}815816export async function817approveExpectFail(collectionId: number,818                  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {819  await usingApi(async (api: ApiPromise) => {820    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);821    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;822    const result = getCreateCollectionResult(events);823    // tslint:disable-next-line:no-unused-expression824    expect(result.success).to.be.false;825  });826}827828export async function getFungibleBalance(829  collectionId: number,830  owner: string,831) {832  return await usingApi(async (api) => {833    const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};834    return BigInt(response.Value);835  });836}837838export async function createFungibleItemExpectSuccess(839  sender: IKeyringPair,840  collectionId: number,841  data: CreateFungibleData,842  owner: string = sender.address,843) {844  return await usingApi(async (api) => {845    const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });846847    const events = await submitTransactionAsync(sender, tx);848    const result = getCreateItemResult(events);849850    expect(result.success).to.be.true;851    return result.itemId;852  });853}854855export async function createItemExpectSuccess(856  sender: IKeyringPair, collectionId: number, createMode: string, owner: string | AccountId = sender.address) {857  let newItemId: number = 0;858  await usingApi(async (api) => {859    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);860    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();861    const AItemBalance = new BigNumber(Aitem.Value);862863    let tx;864    if (createMode === 'Fungible') {865      const createData = {fungible: {value: 10}};866      tx = api.tx.nft.createItem(collectionId, owner, createData);867    } else if (createMode === 'ReFungible') {868      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};869      tx = api.tx.nft.createItem(collectionId, owner, createData);870    } else {871      tx = api.tx.nft.createItem(collectionId, owner, createMode);872    }873    const events = await submitTransactionAsync(sender, tx);874    const result = getCreateItemResult(events);875876    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);877    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();878    const BItemBalance = new BigNumber(Bitem.Value);879880    // What to expect881    // tslint:disable-next-line:no-unused-expression882    expect(result.success).to.be.true;883    if (createMode === 'Fungible') {884      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);885    } else {886      expect(BItemCount).to.be.equal(AItemCount + 1);887    }888    expect(collectionId).to.be.equal(result.collectionId);889    expect(BItemCount).to.be.equal(result.itemId);890    expect(owner.toString()).to.be.equal(result.recipient);891    newItemId = result.itemId;892  });893  return newItemId;894}895896export async function createItemExpectFailure(897  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {898  await usingApi(async (api) => {899    const tx = api.tx.nft.createItem(collectionId, owner, createMode);900    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;901    const result = getCreateItemResult(events);902903    expect(result.success).to.be.false;904  });905}906907export async function setPublicAccessModeExpectSuccess(908  sender: IKeyringPair, collectionId: number,909  accessMode: 'Normal' | 'WhiteList',910) {911  await usingApi(async (api) => {912913    // Run the transaction914    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);915    const events = await submitTransactionAsync(sender, tx);916    const result = getGenericResult(events);917918    // Get the collection919    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();920921    // What to expect922    // tslint:disable-next-line:no-unused-expression923    expect(result.success).to.be.true;924    expect(collection.Access).to.be.equal(accessMode);925  });926}927928export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {929  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');930}931932export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {933  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');934}935936export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {937  await usingApi(async (api) => {938939    // Run the transaction940    const tx = api.tx.nft.setMintPermission(collectionId, enabled);941    const events = await submitTransactionAsync(sender, tx);942    const result = getGenericResult(events);943944    // Get the collection945    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();946947    // What to expect948    // tslint:disable-next-line:no-unused-expression949    expect(result.success).to.be.true;950    expect(collection.MintMode).to.be.equal(enabled);951  });952}953954export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {955  await setMintPermissionExpectSuccess(sender, collectionId, true);956}957958export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {959  await usingApi(async (api) => {960    // Run the transaction961    const tx = api.tx.nft.setMintPermission(collectionId, enabled);962    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;963    const result = getCreateCollectionResult(events);964    // tslint:disable-next-line:no-unused-expression965    expect(result.success).to.be.false;966  });967}968969export async function isWhitelisted(collectionId: number, address: string) {970  let whitelisted: boolean = false;971  await usingApi(async (api) => {972    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;973  });974  return whitelisted;975}976977export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {978  await usingApi(async (api) => {979980    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();981982    // Run the transaction983    const tx = api.tx.nft.addToWhiteList(collectionId, address);984    const events = await submitTransactionAsync(sender, tx);985    const result = getGenericResult(events);986987    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();988989    // What to expect990    // tslint:disable-next-line:no-unused-expression991    expect(result.success).to.be.true;992    // tslint:disable-next-line: no-unused-expression993    expect(whiteListedBefore).to.be.false;994    // tslint:disable-next-line: no-unused-expression995    expect(whiteListedAfter).to.be.true;996  });997}998999export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {1000  await usingApi(async (api) => {1001    // Run the transaction1002    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);1003    const events = await submitTransactionAsync(sender, tx);1004    const result = getGenericResult(events);10051006    // What to expect1007    // tslint:disable-next-line:no-unused-expression1008    expect(result.success).to.be.true;1009  });1010}10111012export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {1013  await usingApi(async (api) => {1014    // Run the transaction1015    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);1016    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1017    const result = getGenericResult(events);10181019    // What to expect1020    // tslint:disable-next-line:no-unused-expression1021    expect(result.success).to.be.false;1022  });1023}10241025export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1026  : Promise<ICollectionInterface | null> => {1027  return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1028};10291030export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1031  // set global object - collectionsCount1032  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();1033};10341035export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {1036  return await usingApi(async (api) => {1037    return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1038  });1039}