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

difftreelog

source

tests/src/util/helpers.ts44.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 '../interfaces/augment-api-rpc';7import '../interfaces/augment-api-query';8import {ApiPromise, Keyring} from '@polkadot/api';9import type {AccountId, EventRecord} from '@polkadot/types/interfaces';10import {IKeyringPair} from '@polkadot/types/types';11import {evmToAddress} from '@polkadot/util-crypto';12import BN from 'bn.js';13import chai from 'chai';14import chaiAsPromised from 'chai-as-promised';15import {alicesPublicKey} from '../accounts';16import privateKey from '../substrate/privateKey';17import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';18import {hexToStr, strToUTF16, utf16ToStr} from './util';19import {UpDataStructsCollection} from '@polkadot/types/lookup';2021chai.use(chaiAsPromised);22const expect = chai.expect;2324export type CrossAccountId = {25  Substrate: string,26} | {27  Ethereum: string,28};2930export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {31  if (typeof input === 'string') {32    if (input.length === 48 || input.length === 47) {33      return {Substrate: input};34    } else if (input.length === 42 && input.startsWith('0x')) {35      return {Ethereum: input.toLowerCase()};36    } else if (input.length === 40 && !input.startsWith('0x')) {37      return {Ethereum: '0x' + input.toLowerCase()};38    } else {39      throw new Error(`Unknown address format: "${input}"`);40    }41  }42  if ('address' in input) {43    return {Substrate: input.address};44  }45  if ('Ethereum' in input) {46    return {47      Ethereum: input.Ethereum.toLowerCase(),48    };49  } else if ('ethereum' in input) {50    return {51      Ethereum: (input as any).ethereum.toLowerCase(),52    };53  } else if ('Substrate' in input) {54    return input;55  } else if ('substrate' in input) {56    return {57      Substrate: (input as any).substrate,58    };59  }6061  // AccountId62  return {Substrate: input.toString()};63}64export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {65  input = normalizeAccountId(input);66  if ('Substrate' in input) {67    return input.Substrate;68  } else {69    return evmToAddress(input.Ethereum);70  }71}7273export const U128_MAX = (1n << 128n) - 1n;7475const MICROUNIQUE = 1_000_000_000_000n;76const MILLIUNIQUE = 1_000n * MICROUNIQUE;77const CENTIUNIQUE = 10n * MILLIUNIQUE;78export const UNIQUE = 100n * CENTIUNIQUE;7980type GenericResult = {81  success: boolean,82};8384interface CreateCollectionResult {85  success: boolean;86  collectionId: number;87}8889interface CreateItemResult {90  success: boolean;91  collectionId: number;92  itemId: number;93  recipient?: CrossAccountId;94}9596interface TransferResult {97  success: boolean;98  collectionId: number;99  itemId: number;100  sender?: CrossAccountId;101  recipient?: CrossAccountId;102  value: bigint;103}104105interface IReFungibleOwner {106  fraction: BN;107  owner: number[];108}109110interface IGetMessage {111  checkMsgUnqMethod: string;112  checkMsgTrsMethod: string;113  checkMsgSysMethod: string;114}115116export interface IFungibleTokenDataType {117  value: number;118}119120export interface IChainLimits {121  collectionNumbersLimit: number;122  accountTokenOwnershipLimit: number;123  collectionsAdminsLimit: number;124  customDataLimit: number;125  nftSponsorTransferTimeout: number;126  fungibleSponsorTransferTimeout: number;127  refungibleSponsorTransferTimeout: number;128  offchainSchemaLimit: number;129  variableOnChainSchemaLimit: number;130  constOnChainSchemaLimit: number;131}132133export interface IReFungibleTokenDataType {134  owner: IReFungibleOwner[];135  constData: number[];136  variableData: number[];137}138139export function uniqueEventMessage(events: EventRecord[]): IGetMessage {140  let checkMsgUnqMethod = '';141  let checkMsgTrsMethod = '';142  let checkMsgSysMethod = '';143  events.forEach(({event: {method, section}}) => {144    if (section === 'common') {145      checkMsgUnqMethod = method;146    } else if (section === 'treasury') {147      checkMsgTrsMethod = method;148    } else if (section === 'system') {149      checkMsgSysMethod = method;150    } else { return null; }151  });152  const result: IGetMessage = {153    checkMsgUnqMethod,154    checkMsgTrsMethod,155    checkMsgSysMethod,156  };157  return result;158}159160export function getGenericResult(events: EventRecord[]): GenericResult {161  const result: GenericResult = {162    success: false,163  };164  events.forEach(({event: {method}}) => {165    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);166    if (method === 'ExtrinsicSuccess') {167      result.success = true;168    }169  });170  return result;171}172173174175export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {176  let success = false;177  let collectionId = 0;178  events.forEach(({event: {data, method, section}}) => {179    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);180    if (method == 'ExtrinsicSuccess') {181      success = true;182    } else if ((section == 'common') && (method == 'CollectionCreated')) {183      collectionId = parseInt(data[0].toString(), 10);184    }185  });186  const result: CreateCollectionResult = {187    success,188    collectionId,189  };190  return result;191}192193export function getCreateItemResult(events: EventRecord[]): CreateItemResult {194  let success = false;195  let collectionId = 0;196  let itemId = 0;197  let recipient;198  events.forEach(({event: {data, method, section}}) => {199    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);200    if (method == 'ExtrinsicSuccess') {201      success = true;202    } else if ((section == 'common') && (method == 'ItemCreated')) {203      collectionId = parseInt(data[0].toString(), 10);204      itemId = parseInt(data[1].toString(), 10);205      recipient = normalizeAccountId(data[2].toJSON() as any);206    }207  });208  const result: CreateItemResult = {209    success,210    collectionId,211    itemId,212    recipient,213  };214  return result;215}216217export function getTransferResult(events: EventRecord[]): TransferResult {218  const result: TransferResult = {219    success: false,220    collectionId: 0,221    itemId: 0,222    value: 0n,223  };224225  events.forEach(({event: {data, method, section}}) => {226    if (method === 'ExtrinsicSuccess') {227      result.success = true;228    } else if (section === 'common' && method === 'Transfer') {229      result.collectionId = +data[0].toString();230      result.itemId = +data[1].toString();231      result.sender = normalizeAccountId(data[2].toJSON() as any);232      result.recipient = normalizeAccountId(data[3].toJSON() as any);233      result.value = BigInt(data[4].toString());234    }235  });236237  return result;238}239240interface Nft {241  type: 'NFT';242}243244interface Fungible {245  type: 'Fungible';246  decimalPoints: number;247}248249interface ReFungible {250  type: 'ReFungible';251}252253type CollectionMode = Nft | Fungible | ReFungible;254255export type CreateCollectionParams = {256  mode: CollectionMode,257  name: string,258  description: string,259  tokenPrefix: string,260};261262const defaultCreateCollectionParams: CreateCollectionParams = {263  description: 'description',264  mode: {type: 'NFT'},265  name: 'name',266  tokenPrefix: 'prefix',267};268269export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {270  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};271272  let collectionId = 0;273  await usingApi(async (api) => {274    // Get number of collections before the transaction275    const collectionCountBefore = await getCreatedCollectionCount(api);276277    // Run the CreateCollection transaction278    const alicePrivateKey = privateKey('//Alice');279280    let modeprm = {};281    if (mode.type === 'NFT') {282      modeprm = {nft: null};283    } else if (mode.type === 'Fungible') {284      modeprm = {fungible: mode.decimalPoints};285    } else if (mode.type === 'ReFungible') {286      modeprm = {refungible: null};287    }288289    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});290    const events = await submitTransactionAsync(alicePrivateKey, tx);291    const result = getCreateCollectionResult(events);292293    // Get number of collections after the transaction294    const collectionCountAfter = await getCreatedCollectionCount(api);295296    // Get the collection297    const collection = await queryCollectionExpectSuccess(api, result.collectionId);298299    // What to expect300    // tslint:disable-next-line:no-unused-expression301    expect(result.success).to.be.true;302    expect(result.collectionId).to.be.equal(collectionCountAfter);303    // tslint:disable-next-line:no-unused-expression304    expect(collection).to.be.not.null;305    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');306    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));307    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);308    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);309    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);310311    collectionId = result.collectionId;312  });313314  return collectionId;315}316317export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {318  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};319320  let modeprm = {};321  if (mode.type === 'NFT') {322    modeprm = {nft: null};323  } else if (mode.type === 'Fungible') {324    modeprm = {fungible: mode.decimalPoints};325  } else if (mode.type === 'ReFungible') {326    modeprm = {refungible: null};327  }328329  await usingApi(async (api) => {330    // Get number of collections before the transaction331    const collectionCountBefore = await getCreatedCollectionCount(api);332333    // Run the CreateCollection transaction334    const alicePrivateKey = privateKey('//Alice');335    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});336    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;337    const result = getCreateCollectionResult(events);338339    // Get number of collections after the transaction340    const collectionCountAfter = await getCreatedCollectionCount(api);341342    // What to expect343    // tslint:disable-next-line:no-unused-expression344    expect(result.success).to.be.false;345    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');346  });347}348349export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {350  let bal = 0n;351  let unused;352  do {353    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;354    const keyring = new Keyring({type: 'sr25519'});355    unused = keyring.addFromUri(`//${randomSeed}`);356    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();357  } while (bal !== 0n);358  return unused;359}360361export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {362  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();363}364365export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {366  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));367}368369export async function findNotExistingCollection(api: ApiPromise): Promise<number> {370  const totalNumber = await getCreatedCollectionCount(api);371  const newCollection: number = totalNumber + 1;372  return newCollection;373}374375function getDestroyResult(events: EventRecord[]): boolean {376  let success = false;377  events.forEach(({event: {method}}) => {378    if (method == 'ExtrinsicSuccess') {379      success = true;380    }381  });382  return success;383}384385export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {386  await usingApi(async (api) => {387    // Run the DestroyCollection transaction388    const alicePrivateKey = privateKey(senderSeed);389    const tx = api.tx.unique.destroyCollection(collectionId);390    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;391  });392}393394export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {395  await usingApi(async (api) => {396    // Run the DestroyCollection transaction397    const alicePrivateKey = privateKey(senderSeed);398    const tx = api.tx.unique.destroyCollection(collectionId);399    const events = await submitTransactionAsync(alicePrivateKey, tx);400    const result = getDestroyResult(events);401    expect(result).to.be.true;402403    // What to expect404    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;405  });406}407408export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {409  await usingApi(async (api) => {410    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);411    const events = await submitTransactionAsync(sender, tx);412    const result = getGenericResult(events);413414    expect(result.success).to.be.true;415  });416}417418export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {419  await usingApi(async (api) => {420    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);421    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;422    const result = getGenericResult(events);423424    expect(result.success).to.be.false;425  });426}427428export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {429  await usingApi(async (api) => {430431    // Run the transaction432    const senderPrivateKey = privateKey(sender);433    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);434    const events = await submitTransactionAsync(senderPrivateKey, tx);435    const result = getGenericResult(events);436437    // Get the collection438    const collection = await queryCollectionExpectSuccess(api, collectionId);439440    // What to expect441    expect(result.success).to.be.true;442    expect(collection.sponsorship.toJSON()).to.deep.equal({443      unconfirmed: sponsor,444    });445  });446}447448export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {449  await usingApi(async (api) => {450451    // Run the transaction452    const alicePrivateKey = privateKey(sender);453    const tx = api.tx.unique.removeCollectionSponsor(collectionId);454    const events = await submitTransactionAsync(alicePrivateKey, tx);455    const result = getGenericResult(events);456457    // Get the collection458    const collection = await queryCollectionExpectSuccess(api, collectionId);459460    // What to expect461    expect(result.success).to.be.true;462    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});463  });464}465466export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {467  await usingApi(async (api) => {468469    // Run the transaction470    const alicePrivateKey = privateKey(senderSeed);471    const tx = api.tx.unique.removeCollectionSponsor(collectionId);472    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;473  });474}475476export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {477  await usingApi(async (api) => {478479    // Run the transaction480    const alicePrivateKey = privateKey(senderSeed);481    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);482    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;483  });484}485486export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {487  await usingApi(async (api) => {488489    // Run the transaction490    const sender = privateKey(senderSeed);491    const tx = api.tx.unique.confirmSponsorship(collectionId);492    const events = await submitTransactionAsync(sender, tx);493    const result = getGenericResult(events);494495    // Get the collection496    const collection = await queryCollectionExpectSuccess(api, collectionId);497498    // What to expect499    expect(result.success).to.be.true;500    expect(collection.sponsorship.toJSON()).to.be.deep.equal({501      confirmed: sender.address,502    });503  });504}505506507export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {508  await usingApi(async (api) => {509510    // Run the transaction511    const sender = privateKey(senderSeed);512    const tx = api.tx.unique.confirmSponsorship(collectionId);513    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;514  });515}516517export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {518519  await usingApi(async (api) => {520    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);521    const events = await submitTransactionAsync(sender, tx);522    const result = getGenericResult(events);523524    expect(result.success).to.be.true;525  });526}527528export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {529530  await usingApi(async (api) => {531    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);532    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;533    const result = getGenericResult(events);534535    expect(result.success).to.be.false;536  });537}538539export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {540  await usingApi(async (api) => {541    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);542    const events = await submitTransactionAsync(sender, tx);543    const result = getGenericResult(events);544545    expect(result.success).to.be.true;546  });547}548549export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {550  await usingApi(async (api) => {551    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);552    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;553    const result = getGenericResult(events);554555    expect(result.success).to.be.false;556  });557}558559export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {560561  await usingApi(async (api) => {562563    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);564    const events = await submitTransactionAsync(sender, tx);565    const result = getGenericResult(events);566567    expect(result.success).to.be.true;568  });569}570571export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {572573  await usingApi(async (api) => {574575    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);576    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;577    const result = getGenericResult(events);578579    expect(result.success).to.be.false;580  });581}582583export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {584  await usingApi(async (api) => {585    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);586    const events = await submitTransactionAsync(sender, tx);587    const result = getGenericResult(events);588589    expect(result.success).to.be.true;590  });591}592593export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {594  await usingApi(async (api) => {595    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);596    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;597    const result = getGenericResult(events);598599    expect(result.success).to.be.false;600  });601}602603export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {604  await usingApi(async (api) => {605    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);606    const events = await submitTransactionAsync(sender, tx);607    const result = getGenericResult(events);608609    expect(result.success).to.be.true;610  });611}612613export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {614  let allowlisted = false;615  await usingApi(async (api) => {616    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;617  });618  return allowlisted;619}620621export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {622  await usingApi(async (api) => {623    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());624    const events = await submitTransactionAsync(sender, tx);625    const result = getGenericResult(events);626627    expect(result.success).to.be.true;628  });629}630631export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {632  await usingApi(async (api) => {633    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());634    const events = await submitTransactionAsync(sender, tx);635    const result = getGenericResult(events);636637    expect(result.success).to.be.true;638  });639}640641export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {642  await usingApi(async (api) => {643    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());644    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;645    const result = getGenericResult(events);646647    expect(result.success).to.be.false;648  });649}650651export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {652  await usingApi(async (api) => {653    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));654    const events = await submitTransactionAsync(sender, tx);655    const result = getGenericResult(events);656657    expect(result.success).to.be.true;658  });659}660661export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {662  await usingApi(async (api) => {663    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));664    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;665  });666}667668export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {669  await usingApi(async (api) => {670    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));671    const events = await submitTransactionAsync(sender, tx);672    const result = getGenericResult(events);673674    expect(result.success).to.be.true;675  });676}677678export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {679  await usingApi(async (api) => {680    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));681    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;682  });683}684685export interface CreateFungibleData {686  readonly Value: bigint;687}688689export interface CreateReFungibleData { }690export interface CreateNftData { }691692export type CreateItemData = {693  NFT: CreateNftData;694} | {695  Fungible: CreateFungibleData;696} | {697  ReFungible: CreateReFungibleData;698};699700export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {701  await usingApi(async (api) => {702    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);703    // if burning token by admin - use adminButnItemExpectSuccess704    expect(balanceBefore >= BigInt(value)).to.be.true;705706    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);707    const events = await submitTransactionAsync(sender, tx);708    const result = getGenericResult(events);709    expect(result.success).to.be.true;710711    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);712    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);713  });714}715716export async function717approveExpectSuccess(718  collectionId: number,719  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,720) {721  await usingApi(async (api: ApiPromise) => {722    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);723    const events = await submitTransactionAsync(owner, approveUniqueTx);724    const result = getGenericResult(events);725    expect(result.success).to.be.true;726727    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));728  });729}730731export async function adminApproveFromExpectSuccess(732  collectionId: number,733  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,734) {735  await usingApi(async (api: ApiPromise) => {736    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);737    const events = await submitTransactionAsync(admin, approveUniqueTx);738    const result = getGenericResult(events);739    expect(result.success).to.be.true;740741    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));742  });743}744745export async function746transferFromExpectSuccess(747  collectionId: number,748  tokenId: number,749  accountApproved: IKeyringPair,750  accountFrom: IKeyringPair | CrossAccountId,751  accountTo: IKeyringPair | CrossAccountId,752  value: number | bigint = 1,753  type = 'NFT',754) {755  await usingApi(async (api: ApiPromise) => {756    const from = normalizeAccountId(accountFrom);757    const to = normalizeAccountId(accountTo);758    let balanceBefore = 0n;759    if (type === 'Fungible') {760      balanceBefore = await getBalance(api, collectionId, to, tokenId);761    }762    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);763    const events = await submitTransactionAsync(accountApproved, transferFromTx);764    const result = getCreateItemResult(events);765    // tslint:disable-next-line:no-unused-expression766    expect(result.success).to.be.true;767    if (type === 'NFT') {768      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);769    }770    if (type === 'Fungible') {771      const balanceAfter = await getBalance(api, collectionId, to, tokenId);772      if (JSON.stringify(to) !== JSON.stringify(from)) {773        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));774      } else {775        expect(balanceAfter).to.be.equal(balanceBefore);776      }777    }778    if (type === 'ReFungible') {779      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));780    }781  });782}783784export async function785transferFromExpectFail(786  collectionId: number,787  tokenId: number,788  accountApproved: IKeyringPair,789  accountFrom: IKeyringPair,790  accountTo: IKeyringPair,791  value: number | bigint = 1,792) {793  await usingApi(async (api: ApiPromise) => {794    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);795    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;796    const result = getCreateCollectionResult(events);797    // tslint:disable-next-line:no-unused-expression798    expect(result.success).to.be.false;799  });800}801802/* eslint no-async-promise-executor: "off" */803async function getBlockNumber(api: ApiPromise): Promise<number> {804  return new Promise<number>(async (resolve) => {805    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {806      unsubscribe();807      resolve(head.number.toNumber());808    });809  });810}811812export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {813  await usingApi(async (api) => {814    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));815    const events = await submitTransactionAsync(sender, changeAdminTx);816    const result = getCreateCollectionResult(events);817    expect(result.success).to.be.true;818  });819}820821export async function822getFreeBalance(account: IKeyringPair): Promise<bigint> {823  let balance = 0n;824  await usingApi(async (api) => {825    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());826  });827828  return balance;829}830831export async function832scheduleTransferExpectSuccess(833  collectionId: number,834  tokenId: number,835  sender: IKeyringPair,836  recipient: IKeyringPair,837  value: number | bigint = 1,838  blockSchedule: number,839) {840  await usingApi(async (api: ApiPromise) => {841    const blockNumber: number | undefined = await getBlockNumber(api);842    const expectedBlockNumber = blockNumber + blockSchedule;843844    expect(blockNumber).to.be.greaterThan(0);845    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);846    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);847848    await submitTransactionAsync(sender, scheduleTx);849850    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();851852    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));853854    // sleep for 4 blocks855    await waitNewBlocks(blockSchedule + 1);856857    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();858859    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));860    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);861  });862}863864865export async function866transferExpectSuccess(867  collectionId: number,868  tokenId: number,869  sender: IKeyringPair,870  recipient: IKeyringPair | CrossAccountId,871  value: number | bigint = 1,872  type = 'NFT',873) {874  await usingApi(async (api: ApiPromise) => {875    const from = normalizeAccountId(sender);876    const to = normalizeAccountId(recipient);877878    let balanceBefore = 0n;879    if (type === 'Fungible') {880      balanceBefore = await getBalance(api, collectionId, to, tokenId);881    }882    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);883    const events = await submitTransactionAsync(sender, transferTx);884    const result = getTransferResult(events);885    // tslint:disable-next-line:no-unused-expression886    expect(result.success).to.be.true;887    expect(result.collectionId).to.be.equal(collectionId);888    expect(result.itemId).to.be.equal(tokenId);889    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));890    expect(result.recipient).to.be.deep.equal(to);891    expect(result.value).to.be.equal(BigInt(value));892    if (type === 'NFT') {893      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);894    }895    if (type === 'Fungible') {896      const balanceAfter = await getBalance(api, collectionId, to, tokenId);897      if (JSON.stringify(to) !== JSON.stringify(from)) {898        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));899      } else {900        expect(balanceAfter).to.be.equal(balanceBefore);901      }902    }903    if (type === 'ReFungible') {904      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;905    }906  });907}908909export async function910transferExpectFailure(911  collectionId: number,912  tokenId: number,913  sender: IKeyringPair,914  recipient: IKeyringPair,915  value: number | bigint = 1,916) {917  await usingApi(async (api: ApiPromise) => {918    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);919    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;920    const result = getGenericResult(events);921    // if (events && Array.isArray(events)) {922    //   const result = getCreateCollectionResult(events);923    // tslint:disable-next-line:no-unused-expression924    expect(result.success).to.be.false;925    //}926  });927}928929export async function930approveExpectFail(931  collectionId: number,932  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,933) {934  await usingApi(async (api: ApiPromise) => {935    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);936    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;937    const result = getCreateCollectionResult(events);938    // tslint:disable-next-line:no-unused-expression939    expect(result.success).to.be.false;940  });941}942943export async function getBalance(944  api: ApiPromise,945  collectionId: number,946  owner: string | CrossAccountId,947  token: number,948): Promise<bigint> {949  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();950}951export async function getTokenOwner(952  api: ApiPromise,953  collectionId: number,954  token: number,955): Promise<CrossAccountId> {956  return normalizeAccountId((await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any);957}958export async function isTokenExists(959  api: ApiPromise,960  collectionId: number,961  token: number,962): Promise<boolean> {963  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();964}965export async function getLastTokenId(966  api: ApiPromise,967  collectionId: number,968): Promise<number> {969  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();970}971export async function getAdminList(972  api: ApiPromise,973  collectionId: number,974): Promise<string[]> {975  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;976}977export async function getVariableMetadata(978  api: ApiPromise,979  collectionId: number,980  tokenId: number,981): Promise<number[]> {982  return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];983}984export async function getConstMetadata(985  api: ApiPromise,986  collectionId: number,987  tokenId: number,988): Promise<number[]> {989  return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];990}991992export async function createFungibleItemExpectSuccess(993  sender: IKeyringPair,994  collectionId: number,995  data: CreateFungibleData,996  owner: CrossAccountId | string = sender.address,997) {998  return await usingApi(async (api) => {999    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});10001001    const events = await submitTransactionAsync(sender, tx);1002    const result = getCreateItemResult(events);10031004    expect(result.success).to.be.true;1005    return result.itemId;1006  });1007}10081009export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1010  let newItemId = 0;1011  await usingApi(async (api) => {1012    const to = normalizeAccountId(owner);1013    const itemCountBefore = await getLastTokenId(api, collectionId);1014    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10151016    let tx;1017    if (createMode === 'Fungible') {1018      const createData = {fungible: {value: 10}};1019      tx = api.tx.unique.createItem(collectionId, to, createData as any);1020    } else if (createMode === 'ReFungible') {1021      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1022      tx = api.tx.unique.createItem(collectionId, to, createData as any);1023    } else {1024      const createData = {nft: {const_data: [], variable_data: []}};1025      tx = api.tx.unique.createItem(collectionId, to, createData as any);1026    }10271028    const events = await submitTransactionAsync(sender, tx);1029    const result = getCreateItemResult(events);10301031    const itemCountAfter = await getLastTokenId(api, collectionId);1032    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10331034    // What to expect1035    // tslint:disable-next-line:no-unused-expression1036    expect(result.success).to.be.true;1037    if (createMode === 'Fungible') {1038      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1039    } else {1040      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1041    }1042    expect(collectionId).to.be.equal(result.collectionId);1043    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1044    expect(to).to.be.deep.equal(result.recipient);1045    newItemId = result.itemId;1046  });1047  return newItemId;1048}10491050export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {1051  await usingApi(async (api) => {1052    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);10531054    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1055    const result = getCreateItemResult(events);10561057    expect(result.success).to.be.false;1058  });1059}10601061export async function setPublicAccessModeExpectSuccess(1062  sender: IKeyringPair, collectionId: number,1063  accessMode: 'Normal' | 'AllowList',1064) {1065  await usingApi(async (api) => {10661067    // Run the transaction1068    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1069    const events = await submitTransactionAsync(sender, tx);1070    const result = getGenericResult(events);10711072    // Get the collection1073    const collection = await queryCollectionExpectSuccess(api, collectionId);10741075    // What to expect1076    // tslint:disable-next-line:no-unused-expression1077    expect(result.success).to.be.true;1078    expect(collection.access.toHuman()).to.be.equal(accessMode);1079  });1080}10811082export async function setPublicAccessModeExpectFail(1083  sender: IKeyringPair, collectionId: number,1084  accessMode: 'Normal' | 'AllowList',1085) {1086  await usingApi(async (api) => {10871088    // Run the transaction1089    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1090    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1091    const result = getGenericResult(events);10921093    // What to expect1094    // tslint:disable-next-line:no-unused-expression1095    expect(result.success).to.be.false;1096  });1097}10981099export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1100  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1101}11021103export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1104  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1105}11061107export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1108  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1109}11101111export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1112  await usingApi(async (api) => {11131114    // Run the transaction1115    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1116    const events = await submitTransactionAsync(sender, tx);1117    const result = getGenericResult(events);1118    expect(result.success).to.be.true;11191120    // Get the collection1121    const collection = await queryCollectionExpectSuccess(api, collectionId);11221123    expect(collection.mintMode.toHuman()).to.be.equal(enabled);1124  });1125}11261127export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1128  await setMintPermissionExpectSuccess(sender, collectionId, true);1129}11301131export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1132  await usingApi(async (api) => {1133    // Run the transaction1134    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1135    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1136    const result = getCreateCollectionResult(events);1137    // tslint:disable-next-line:no-unused-expression1138    expect(result.success).to.be.false;1139  });1140}11411142export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1143  await usingApi(async (api) => {1144    // Run the transaction1145    const tx = api.tx.unique.setChainLimits(limits);1146    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1147    const result = getCreateCollectionResult(events);1148    // tslint:disable-next-line:no-unused-expression1149    expect(result.success).to.be.false;1150  });1151}11521153export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1154  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1155}11561157export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1158  await usingApi(async (api) => {1159    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;11601161    // Run the transaction1162    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1163    const events = await submitTransactionAsync(sender, tx);1164    const result = getGenericResult(events);1165    expect(result.success).to.be.true;11661167    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1168  });1169}11701171export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1172  await usingApi(async (api) => {11731174    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;11751176    // Run the transaction1177    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1178    const events = await submitTransactionAsync(sender, tx);1179    const result = getGenericResult(events);1180    expect(result.success).to.be.true;11811182    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1183  });1184}11851186export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1187  await usingApi(async (api) => {11881189    // Run the transaction1190    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1191    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1192    const result = getGenericResult(events);11931194    // What to expect1195    // tslint:disable-next-line:no-unused-expression1196    expect(result.success).to.be.false;1197  });1198}11991200export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1201  await usingApi(async (api) => {1202    // Run the transaction1203    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1204    const events = await submitTransactionAsync(sender, tx);1205    const result = getGenericResult(events);12061207    // What to expect1208    // tslint:disable-next-line:no-unused-expression1209    expect(result.success).to.be.true;1210  });1211}12121213export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1214  await usingApi(async (api) => {1215    // Run the transaction1216    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1217    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1218    const result = getGenericResult(events);12191220    // What to expect1221    // tslint:disable-next-line:no-unused-expression1222    expect(result.success).to.be.false;1223  });1224}12251226export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1227  : Promise<UpDataStructsCollection | null> => {1228  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1229};12301231export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1232  // set global object - collectionsCount1233  return (await api.rpc.unique.collectionStats()).created.toNumber();1234};12351236export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsCollection> {1237  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1238}12391240export async function waitNewBlocks(blocksCount = 1): Promise<void> {1241  await usingApi(async (api) => {1242    const promise = new Promise<void>(async (resolve) => {1243      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1244        if (blocksCount > 0) {1245          blocksCount--;1246        } else {1247          unsubscribe();1248          resolve();1249        }1250      });1251    });1252    return promise;1253  });1254}