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

difftreelog

source

tests/src/util/helpers.ts50.9 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';22import {evmToAddress} from '@polkadot/util-crypto';23import BN from 'bn.js';24import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {alicesPublicKey} from '../accounts';27import privateKey from '../substrate/privateKey';28import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection, UpDataStructsCreateItemData} from '@polkadot/types/lookup';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36  Substrate: string,37} | {38  Ethereum: string,39};4041export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {42  if (typeof input === 'string') {43    if (input.length === 48 || input.length === 47) {44      return {Substrate: input};45    } else if (input.length === 42 && input.startsWith('0x')) {46      return {Ethereum: input.toLowerCase()};47    } else if (input.length === 40 && !input.startsWith('0x')) {48      return {Ethereum: '0x' + input.toLowerCase()};49    } else {50      throw new Error(`Unknown address format: "${input}"`);51    }52  }53  if ('address' in input) {54    return {Substrate: input.address};55  }56  if ('Ethereum' in input) {57    return {58      Ethereum: input.Ethereum.toLowerCase(),59    };60  } else if ('ethereum' in input) {61    return {62      Ethereum: (input as any).ethereum.toLowerCase(),63    };64  } else if ('Substrate' in input) {65    return input;66  } else if ('substrate' in input) {67    return {68      Substrate: (input as any).substrate,69    };70  }7172  // AccountId73  return {Substrate: input.toString()};74}75export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {76  input = normalizeAccountId(input);77  if ('Substrate' in input) {78    return input.Substrate;79  } else {80    return evmToAddress(input.Ethereum);81  }82}8384export const U128_MAX = (1n << 128n) - 1n;8586const MICROUNIQUE = 1_000_000_000_000n;87const MILLIUNIQUE = 1_000n * MICROUNIQUE;88const CENTIUNIQUE = 10n * MILLIUNIQUE;89export const UNIQUE = 100n * CENTIUNIQUE;9091type GenericResult = {92  success: boolean,93};9495interface CreateCollectionResult {96  success: boolean;97  collectionId: number;98}99100interface CreateItemResult {101  success: boolean;102  collectionId: number;103  itemId: number;104  recipient?: CrossAccountId;105}106107interface TransferResult {108  collectionId: number;109  itemId: number;110  sender?: CrossAccountId;111  recipient?: CrossAccountId;112  value: bigint;113}114115interface IReFungibleOwner {116  fraction: BN;117  owner: number[];118}119120interface IGetMessage {121  checkMsgUnqMethod: string;122  checkMsgTrsMethod: string;123  checkMsgSysMethod: string;124}125126export interface IFungibleTokenDataType {127  value: number;128}129130export interface IChainLimits {131  collectionNumbersLimit: number;132  accountTokenOwnershipLimit: number;133  collectionsAdminsLimit: number;134  customDataLimit: number;135  nftSponsorTransferTimeout: number;136  fungibleSponsorTransferTimeout: number;137  refungibleSponsorTransferTimeout: number;138  offchainSchemaLimit: number;139  constOnChainSchemaLimit: number;140}141142export interface IReFungibleTokenDataType {143  owner: IReFungibleOwner[];144  constData: number[];145}146147export function uniqueEventMessage(events: EventRecord[]): IGetMessage {148  let checkMsgUnqMethod = '';149  let checkMsgTrsMethod = '';150  let checkMsgSysMethod = '';151  events.forEach(({event: {method, section}}) => {152    if (section === 'common') {153      checkMsgUnqMethod = method;154    } else if (section === 'treasury') {155      checkMsgTrsMethod = method;156    } else if (section === 'system') {157      checkMsgSysMethod = method;158    } else { return null; }159  });160  const result: IGetMessage = {161    checkMsgUnqMethod,162    checkMsgTrsMethod,163    checkMsgSysMethod,164  };165  return result;166}167168export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {169  const event = events.find(r => check(r.event));170  if (!event) return;171  return event.event as T;172}173174export function getGenericResult(events: EventRecord[]): GenericResult {175  const result: GenericResult = {176    success: false,177  };178  events.forEach(({event: {method}}) => {179    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);180    if (method === 'ExtrinsicSuccess') {181      result.success = true;182    }183  });184  return result;185}186187188189export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {190  let success = false;191  let collectionId = 0;192  events.forEach(({event: {data, method, section}}) => {193    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);194    if (method == 'ExtrinsicSuccess') {195      success = true;196    } else if ((section == 'common') && (method == 'CollectionCreated')) {197      collectionId = parseInt(data[0].toString(), 10);198    }199  });200  const result: CreateCollectionResult = {201    success,202    collectionId,203  };204  return result;205}206207export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {208  let success = false;209  let collectionId = 0;210  let itemId = 0;211  let recipient;212213  const results : CreateItemResult[]  = [];214215  events.forEach(({event: {data, method, section}}) => {216    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);217    if (method == 'ExtrinsicSuccess') {218      success = true;219    } else if ((section == 'common') && (method == 'ItemCreated')) {220      collectionId = parseInt(data[0].toString(), 10);221      itemId = parseInt(data[1].toString(), 10);222      recipient = normalizeAccountId(data[2].toJSON() as any);223224      const itemRes: CreateItemResult = {225        success,226        collectionId,227        itemId,228        recipient,229      };230231      results.push(itemRes);232    }233  });234235  return results;236}237238export function getCreateItemResult(events: EventRecord[]): CreateItemResult {239  let success = false;240  let collectionId = 0;241  let itemId = 0;242  let recipient;243  events.forEach(({event: {data, method, section}}) => {244    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);245    if (method == 'ExtrinsicSuccess') {246      success = true;247    } else if ((section == 'common') && (method == 'ItemCreated')) {248      collectionId = parseInt(data[0].toString(), 10);249      itemId = parseInt(data[1].toString(), 10);250      recipient = normalizeAccountId(data[2].toJSON() as any);251    }252  });253  const result: CreateItemResult = {254    success,255    collectionId,256    itemId,257    recipient,258  };259  return result;260}261262export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {263  for (const {event} of events) {264    if (api.events.common.Transfer.is(event)) {265      const [collection, token, sender, recipient, value] = event.data;266      return {267        collectionId: collection.toNumber(),268        itemId: token.toNumber(),269        sender: normalizeAccountId(sender.toJSON() as any),270        recipient: normalizeAccountId(recipient.toJSON() as any),271        value: value.toBigInt(),272      };273    }274  }275  throw new Error('no transfer event');276}277278interface Nft {279  type: 'NFT';280}281282interface Fungible {283  type: 'Fungible';284  decimalPoints: number;285}286287interface ReFungible {288  type: 'ReFungible';289}290291type CollectionMode = Nft | Fungible | ReFungible;292293export type Property = {294  key: any,295  value: any,296};297298type Permission = {299  mutable: boolean;300  collectionAdmin: boolean;301  tokenOwner: boolean;302}303304type PropertyPermission = {305  key: any;306  permission: Permission;307}308309export type CreateCollectionParams = {310  mode: CollectionMode,311  name: string,312  description: string,313  tokenPrefix: string,314  schemaVersion: string,315  properties?: Array<Property>,316  propPerm?: Array<PropertyPermission>317};318319const defaultCreateCollectionParams: CreateCollectionParams = {320  description: 'description',321  mode: {type: 'NFT'},322  name: 'name',323  tokenPrefix: 'prefix',324  schemaVersion: 'ImageURL',325};326327export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {328  const {name, description, mode, tokenPrefix, schemaVersion} = {...defaultCreateCollectionParams, ...params};329330  let collectionId = 0;331  await usingApi(async (api) => {332    // Get number of collections before the transaction333    const collectionCountBefore = await getCreatedCollectionCount(api);334335    // Run the CreateCollection transaction336    const alicePrivateKey = privateKey('//Alice');337338    let modeprm = {};339    if (mode.type === 'NFT') {340      modeprm = {nft: null};341    } else if (mode.type === 'Fungible') {342      modeprm = {fungible: mode.decimalPoints};343    } else if (mode.type === 'ReFungible') {344      modeprm = {refungible: null};345    }346347    const tx = api.tx.unique.createCollectionEx({348      name: strToUTF16(name),349      description: strToUTF16(description),350      tokenPrefix: strToUTF16(tokenPrefix),351      mode: modeprm as any,352      schemaVersion: schemaVersion,353    });354    const events = await submitTransactionAsync(alicePrivateKey, tx);355    const result = getCreateCollectionResult(events);356357    // Get number of collections after the transaction358    const collectionCountAfter = await getCreatedCollectionCount(api);359360    // Get the collection361    const collection = await queryCollectionExpectSuccess(api, result.collectionId);362363    // What to expect364    // tslint:disable-next-line:no-unused-expression365    expect(result.success).to.be.true;366    expect(result.collectionId).to.be.equal(collectionCountAfter);367    // tslint:disable-next-line:no-unused-expression368    expect(collection).to.be.not.null;369    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');370    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));371    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);372    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);373    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);374375    collectionId = result.collectionId;376  });377378  return collectionId;379}380381export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {382  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};383384  let collectionId = 0;385  await usingApi(async (api) => {386    // Get number of collections before the transaction387    const collectionCountBefore = await getCreatedCollectionCount(api);388389    // Run the CreateCollection transaction390    const alicePrivateKey = privateKey('//Alice');391392    let modeprm = {};393    if (mode.type === 'NFT') {394      modeprm = {nft: null};395    } else if (mode.type === 'Fungible') {396      modeprm = {fungible: mode.decimalPoints};397    } else if (mode.type === 'ReFungible') {398      modeprm = {refungible: null};399    }400401    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});402    const events = await submitTransactionAsync(alicePrivateKey, tx);403    const result = getCreateCollectionResult(events);404405    // Get number of collections after the transaction406    const collectionCountAfter = await getCreatedCollectionCount(api);407408    // Get the collection409    const collection = await queryCollectionExpectSuccess(api, result.collectionId);410411    // What to expect412    // tslint:disable-next-line:no-unused-expression413    expect(result.success).to.be.true;414    expect(result.collectionId).to.be.equal(collectionCountAfter);415    // tslint:disable-next-line:no-unused-expression416    expect(collection).to.be.not.null;417    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');418    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));419    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);420    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);421    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);422423424    collectionId = result.collectionId;425  });426427  return collectionId;428}429430export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {431  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};432433  await usingApi(async (api) => {434    // Get number of collections before the transaction435    const collectionCountBefore = await getCreatedCollectionCount(api);436437    // Run the CreateCollection transaction438    const alicePrivateKey = privateKey('//Alice');439440    let modeprm = {};441    if (mode.type === 'NFT') {442      modeprm = {nft: null};443    } else if (mode.type === 'Fungible') {444      modeprm = {fungible: mode.decimalPoints};445    } else if (mode.type === 'ReFungible') {446      modeprm = {refungible: null};447    }448449    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});450    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;451452453    // Get number of collections after the transaction454    const collectionCountAfter = await getCreatedCollectionCount(api);455456    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');457  });458}459460export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {461  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};462463  let modeprm = {};464  if (mode.type === 'NFT') {465    modeprm = {nft: null};466  } else if (mode.type === 'Fungible') {467    modeprm = {fungible: mode.decimalPoints};468  } else if (mode.type === 'ReFungible') {469    modeprm = {refungible: null};470  }471472  await usingApi(async (api) => {473    // Get number of collections before the transaction474    const collectionCountBefore = await getCreatedCollectionCount(api);475476    // Run the CreateCollection transaction477    const alicePrivateKey = privateKey('//Alice');478    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});479    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;480481    // Get number of collections after the transaction482    const collectionCountAfter = await getCreatedCollectionCount(api);483484    // What to expect485    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');486  });487}488489export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {490  let bal = 0n;491  let unused;492  do {493    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;494    const keyring = new Keyring({type: 'sr25519'});495    unused = keyring.addFromUri(`//${randomSeed}`);496    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();497  } while (bal !== 0n);498  return unused;499}500501export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {502  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();503}504505export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {506  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));507}508509export async function findNotExistingCollection(api: ApiPromise): Promise<number> {510  const totalNumber = await getCreatedCollectionCount(api);511  const newCollection: number = totalNumber + 1;512  return newCollection;513}514515function getDestroyResult(events: EventRecord[]): boolean {516  let success = false;517  events.forEach(({event: {method}}) => {518    if (method == 'ExtrinsicSuccess') {519      success = true;520    }521  });522  return success;523}524525export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {526  await usingApi(async (api) => {527    // Run the DestroyCollection transaction528    const alicePrivateKey = privateKey(senderSeed);529    const tx = api.tx.unique.destroyCollection(collectionId);530    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;531  });532}533534export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {535  await usingApi(async (api) => {536    // Run the DestroyCollection transaction537    const alicePrivateKey = privateKey(senderSeed);538    const tx = api.tx.unique.destroyCollection(collectionId);539    const events = await submitTransactionAsync(alicePrivateKey, tx);540    const result = getDestroyResult(events);541    expect(result).to.be.true;542543    // What to expect544    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;545  });546}547548export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {549  await usingApi(async (api) => {550    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);551    const events = await submitTransactionAsync(sender, tx);552    const result = getGenericResult(events);553554    expect(result.success).to.be.true;555  });556}557558export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {559  await usingApi(async (api) => {560    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);561    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;562    const result = getGenericResult(events);563564    expect(result.success).to.be.false;565  });566}567568export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {569  await usingApi(async (api) => {570571    // Run the transaction572    const senderPrivateKey = privateKey(sender);573    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);574    const events = await submitTransactionAsync(senderPrivateKey, tx);575    const result = getGenericResult(events);576577    // Get the collection578    const collection = await queryCollectionExpectSuccess(api, collectionId);579580    // What to expect581    expect(result.success).to.be.true;582    expect(collection.sponsorship.toJSON()).to.deep.equal({583      unconfirmed: sponsor,584    });585  });586}587588export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {589  await usingApi(async (api) => {590591    // Run the transaction592    const alicePrivateKey = privateKey(sender);593    const tx = api.tx.unique.removeCollectionSponsor(collectionId);594    const events = await submitTransactionAsync(alicePrivateKey, tx);595    const result = getGenericResult(events);596597    // Get the collection598    const collection = await queryCollectionExpectSuccess(api, collectionId);599600    // What to expect601    expect(result.success).to.be.true;602    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});603  });604}605606export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {607  await usingApi(async (api) => {608609    // Run the transaction610    const alicePrivateKey = privateKey(senderSeed);611    const tx = api.tx.unique.removeCollectionSponsor(collectionId);612    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;613  });614}615616export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {617  await usingApi(async (api) => {618619    // Run the transaction620    const alicePrivateKey = privateKey(senderSeed);621    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);622    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;623  });624}625626export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {627  await usingApi(async (api) => {628629    // Run the transaction630    const sender = privateKey(senderSeed);631    const tx = api.tx.unique.confirmSponsorship(collectionId);632    const events = await submitTransactionAsync(sender, tx);633    const result = getGenericResult(events);634635    // Get the collection636    const collection = await queryCollectionExpectSuccess(api, collectionId);637638    // What to expect639    expect(result.success).to.be.true;640    expect(collection.sponsorship.toJSON()).to.be.deep.equal({641      confirmed: sender.address,642    });643  });644}645646647export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {648  await usingApi(async (api) => {649650    // Run the transaction651    const sender = privateKey(senderSeed);652    const tx = api.tx.unique.confirmSponsorship(collectionId);653    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;654  });655}656657export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {658  await usingApi(async (api) => {659    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);660    const events = await submitTransactionAsync(sender, tx);661    const result = getGenericResult(events);662663    expect(result.success).to.be.true;664  });665}666667export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {668  await usingApi(async (api) => {669    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);670    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;671    const result = getGenericResult(events);672673    expect(result.success).to.be.false;674  });675}676677export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {678679  await usingApi(async (api) => {680681    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);682    const events = await submitTransactionAsync(sender, tx);683    const result = getGenericResult(events);684685    expect(result.success).to.be.true;686  });687}688689export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {690691  await usingApi(async (api) => {692693    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);694    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;695    const result = getGenericResult(events);696697    expect(result.success).to.be.false;698  });699}700701export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {702  await usingApi(async (api) => {703    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);704    const events = await submitTransactionAsync(sender, tx);705    const result = getGenericResult(events);706707    expect(result.success).to.be.true;708  });709}710711export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {712  await usingApi(async (api) => {713    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);714    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;715    const result = getGenericResult(events);716717    expect(result.success).to.be.false;718  });719}720721export async function getNextSponsored(722  api: ApiPromise,723  collectionId: number,724  account: string | CrossAccountId,725  tokenId: number,726): Promise<number> {727  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));728}729730export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {731  await usingApi(async (api) => {732    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);733    const events = await submitTransactionAsync(sender, tx);734    const result = getGenericResult(events);735736    expect(result.success).to.be.true;737  });738}739740export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {741  let allowlisted = false;742  await usingApi(async (api) => {743    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;744  });745  return allowlisted;746}747748export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {749  await usingApi(async (api) => {750    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());751    const events = await submitTransactionAsync(sender, tx);752    const result = getGenericResult(events);753754    expect(result.success).to.be.true;755  });756}757758export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {759  await usingApi(async (api) => {760    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());761    const events = await submitTransactionAsync(sender, tx);762    const result = getGenericResult(events);763764    expect(result.success).to.be.true;765  });766}767768export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {769  await usingApi(async (api) => {770    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());771    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;772    const result = getGenericResult(events);773774    expect(result.success).to.be.false;775  });776}777778export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {779  await usingApi(async (api) => {780    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));781    const events = await submitTransactionAsync(sender, tx);782    const result = getGenericResult(events);783784    expect(result.success).to.be.true;785  });786}787788export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {789  await usingApi(async (api) => {790    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));791    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;792  });793}794795export interface CreateFungibleData {796  readonly Value: bigint;797}798799export interface CreateReFungibleData { }800export interface CreateNftData { }801802export type CreateItemData = {803  NFT: CreateNftData;804} | {805  Fungible: CreateFungibleData;806} | {807  ReFungible: CreateReFungibleData;808};809810export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {811  await usingApi(async (api) => {812    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);813    // if burning token by admin - use adminButnItemExpectSuccess814    expect(balanceBefore >= BigInt(value)).to.be.true;815816    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);817    const events = await submitTransactionAsync(sender, tx);818    const result = getGenericResult(events);819    expect(result.success).to.be.true;820821    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);822    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);823  });824}825826export async function827approveExpectSuccess(828  collectionId: number,829  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,830) {831  await usingApi(async (api: ApiPromise) => {832    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);833    const events = await submitTransactionAsync(owner, approveUniqueTx);834    const result = getGenericResult(events);835    expect(result.success).to.be.true;836837    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));838  });839}840841export async function adminApproveFromExpectSuccess(842  collectionId: number,843  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,844) {845  await usingApi(async (api: ApiPromise) => {846    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);847    const events = await submitTransactionAsync(admin, approveUniqueTx);848    const result = getGenericResult(events);849    expect(result.success).to.be.true;850851    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));852  });853}854855export async function856transferFromExpectSuccess(857  collectionId: number,858  tokenId: number,859  accountApproved: IKeyringPair,860  accountFrom: IKeyringPair | CrossAccountId,861  accountTo: IKeyringPair | CrossAccountId,862  value: number | bigint = 1,863  type = 'NFT',864) {865  await usingApi(async (api: ApiPromise) => {866    const from = normalizeAccountId(accountFrom);867    const to = normalizeAccountId(accountTo);868    let balanceBefore = 0n;869    if (type === 'Fungible' || type === 'ReFungible') {870      balanceBefore = await getBalance(api, collectionId, to, tokenId);871    }872    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);873    const events = await submitTransactionAsync(accountApproved, transferFromTx);874    const result = getCreateItemResult(events);875    // tslint:disable-next-line:no-unused-expression876    expect(result.success).to.be.true;877    if (type === 'NFT') {878      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);879    }880    if (type === 'Fungible') {881      const balanceAfter = await getBalance(api, collectionId, to, tokenId);882      if (JSON.stringify(to) !== JSON.stringify(from)) {883        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));884      } else {885        expect(balanceAfter).to.be.equal(balanceBefore);886      }887    }888    if (type === 'ReFungible') {889      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));890    }891  });892}893894export async function895transferFromExpectFail(896  collectionId: number,897  tokenId: number,898  accountApproved: IKeyringPair,899  accountFrom: IKeyringPair,900  accountTo: IKeyringPair,901  value: number | bigint = 1,902) {903  await usingApi(async (api: ApiPromise) => {904    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);905    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;906    const result = getCreateCollectionResult(events);907    // tslint:disable-next-line:no-unused-expression908    expect(result.success).to.be.false;909  });910}911912/* eslint no-async-promise-executor: "off" */913async function getBlockNumber(api: ApiPromise): Promise<number> {914  return new Promise<number>(async (resolve) => {915    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {916      unsubscribe();917      resolve(head.number.toNumber());918    });919  });920}921922export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {923  await usingApi(async (api) => {924    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));925    const events = await submitTransactionAsync(sender, changeAdminTx);926    const result = getCreateCollectionResult(events);927    expect(result.success).to.be.true;928  });929}930931export async function932getFreeBalance(account: IKeyringPair): Promise<bigint> {933  let balance = 0n;934  await usingApi(async (api) => {935    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());936  });937938  return balance;939}940941export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {942  const tx = api.tx.balances.transfer(target, amount);943  const events = await submitTransactionAsync(source, tx);944  const result = getGenericResult(events);945  expect(result.success).to.be.true;946}947948export async function949scheduleTransferExpectSuccess(950  collectionId: number,951  tokenId: number,952  sender: IKeyringPair,953  recipient: IKeyringPair,954  value: number | bigint = 1,955  blockSchedule: number,956) {957  await usingApi(async (api: ApiPromise) => {958    const blockNumber: number | undefined = await getBlockNumber(api);959    const expectedBlockNumber = blockNumber + blockSchedule;960961    expect(blockNumber).to.be.greaterThan(0);962    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);963    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);964965    await submitTransactionAsync(sender, scheduleTx);966967    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();968969    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));970971    // sleep for 4 blocks972    await waitNewBlocks(blockSchedule + 1);973974    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();975976    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));977    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);978  });979}980981982export async function983transferExpectSuccess(984  collectionId: number,985  tokenId: number,986  sender: IKeyringPair,987  recipient: IKeyringPair | CrossAccountId,988  value: number | bigint = 1,989  type = 'NFT',990) {991  await usingApi(async (api: ApiPromise) => {992    const from = normalizeAccountId(sender);993    const to = normalizeAccountId(recipient);994995    let balanceBefore = 0n;996    if (type === 'Fungible') {997      balanceBefore = await getBalance(api, collectionId, to, tokenId);998    }999    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1000    const events = await executeTransaction(api, sender, transferTx);10011002    const result = getTransferResult(api, events);1003    expect(result.collectionId).to.be.equal(collectionId);1004    expect(result.itemId).to.be.equal(tokenId);1005    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1006    expect(result.recipient).to.be.deep.equal(to);1007    expect(result.value).to.be.equal(BigInt(value));10081009    if (type === 'NFT') {1010      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1011    }1012    if (type === 'Fungible') {1013      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1014      if (JSON.stringify(to) !== JSON.stringify(from)) {1015        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1016      } else {1017        expect(balanceAfter).to.be.equal(balanceBefore);1018      }1019    }1020    if (type === 'ReFungible') {1021      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1022    }1023  });1024}10251026export async function1027transferExpectFailure(1028  collectionId: number,1029  tokenId: number,1030  sender: IKeyringPair,1031  recipient: IKeyringPair | CrossAccountId,1032  value: number | bigint = 1,1033) {1034  await usingApi(async (api: ApiPromise) => {1035    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1036    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1037    const result = getGenericResult(events);1038    // if (events && Array.isArray(events)) {1039    //   const result = getCreateCollectionResult(events);1040    // tslint:disable-next-line:no-unused-expression1041    expect(result.success).to.be.false;1042    //}1043  });1044}10451046export async function1047approveExpectFail(1048  collectionId: number,1049  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1050) {1051  await usingApi(async (api: ApiPromise) => {1052    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1053    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1054    const result = getCreateCollectionResult(events);1055    // tslint:disable-next-line:no-unused-expression1056    expect(result.success).to.be.false;1057  });1058}10591060export async function getBalance(1061  api: ApiPromise,1062  collectionId: number,1063  owner: string | CrossAccountId,1064  token: number,1065): Promise<bigint> {1066  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1067}1068export async function getTokenOwner(1069  api: ApiPromise,1070  collectionId: number,1071  token: number,1072): Promise<CrossAccountId> {1073  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1074  if (owner == null) throw new Error('owner == null');1075  return normalizeAccountId(owner);1076}1077export async function getTopmostTokenOwner(1078  api: ApiPromise,1079  collectionId: number,1080  token: number,1081): Promise<CrossAccountId> {1082  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1083  if (owner == null) throw new Error('owner == null');1084  return normalizeAccountId(owner);1085}1086export async function isTokenExists(1087  api: ApiPromise,1088  collectionId: number,1089  token: number,1090): Promise<boolean> {1091  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1092}1093export async function getLastTokenId(1094  api: ApiPromise,1095  collectionId: number,1096): Promise<number> {1097  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1098}1099export async function getAdminList(1100  api: ApiPromise,1101  collectionId: number,1102): Promise<string[]> {1103  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1104}1105export async function getConstMetadata(1106  api: ApiPromise,1107  collectionId: number,1108  tokenId: number,1109): Promise<number[]> {1110  return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1111}11121113export async function createFungibleItemExpectSuccess(1114  sender: IKeyringPair,1115  collectionId: number,1116  data: CreateFungibleData,1117  owner: CrossAccountId | string = sender.address,1118) {1119  return await usingApi(async (api) => {1120    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});11211122    const events = await submitTransactionAsync(sender, tx);1123    const result = getCreateItemResult(events);11241125    expect(result.success).to.be.true;1126    return result.itemId;1127  });1128}11291130export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1131  await usingApi(async (api) => {1132    const to = normalizeAccountId(owner);1133    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);11341135    const events = await submitTransactionAsync(sender, tx);1136    const result = getCreateItemsResult(events);11371138    for (let res of result) {1139      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1140    }1141  });1142}11431144export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1145  let newItemId = 0;1146  await usingApi(async (api) => {1147    const to = normalizeAccountId(owner);1148    const itemCountBefore = await getLastTokenId(api, collectionId);1149    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11501151    let tx;1152    if (createMode === 'Fungible') {1153      const createData = {fungible: {value: 10}};1154      tx = api.tx.unique.createItem(collectionId, to, createData as any);1155    } else if (createMode === 'ReFungible') {1156      const createData = {refungible: {const_data: [], pieces: 100}};1157      tx = api.tx.unique.createItem(collectionId, to, createData as any);1158    } else {1159      const data = api.createType('UpDataStructsCreateItemData', { NFT: { constData: 'test', properties: props}});1160      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1161    }11621163    const events = await submitTransactionAsync(sender, tx);1164    const result = getCreateItemResult(events);11651166    const itemCountAfter = await getLastTokenId(api, collectionId);1167    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);11681169    if (createMode === 'NFT') {1170      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1171    }11721173    // What to expect1174    // tslint:disable-next-line:no-unused-expression1175    expect(result.success).to.be.true;1176    if (createMode === 'Fungible') {1177      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1178    } else {1179      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1180    }1181    expect(collectionId).to.be.equal(result.collectionId);1182    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1183    expect(to).to.be.deep.equal(result.recipient);1184    newItemId = result.itemId;1185  });1186  return newItemId;1187}11881189export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1190  let newItemId = 0;1191  await usingApi(async (api) => {1192    const to = normalizeAccountId(owner);1193    const itemCountBefore = await getLastTokenId(api, collectionId);1194    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11951196    let tx;1197    if (createMode === 'Fungible') {1198      const createData = {fungible: {value: 10}};1199      tx = api.tx.unique.createItem(collectionId, to, createData as any);1200    } else if (createMode === 'ReFungible') {1201      const createData = {refungible: {const_data: [], pieces: 100}};1202      tx = api.tx.unique.createItem(collectionId, to, createData as any);1203    } else {1204      const createData = {nft: {const_data: []}};1205      tx = api.tx.unique.createItem(collectionId, to, createData as any);1206    }12071208    const events = await submitTransactionAsync(sender, tx);1209    const result = getCreateItemResult(events);12101211    const itemCountAfter = await getLastTokenId(api, collectionId);1212    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);12131214    // What to expect1215    // tslint:disable-next-line:no-unused-expression1216    expect(result.success).to.be.true;1217    if (createMode === 'Fungible') {1218      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1219    } else {1220      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1221    }1222    expect(collectionId).to.be.equal(result.collectionId);1223    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1224    expect(to).to.be.deep.equal(result.recipient);1225    newItemId = result.itemId;1226  });1227  return newItemId;1228}12291230export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1231  await usingApi(async (api) => {1232    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);12331234    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1235    const result = getCreateItemResult(events);12361237    expect(result.success).to.be.false;1238  });1239}12401241export async function setPublicAccessModeExpectSuccess(1242  sender: IKeyringPair, collectionId: number,1243  accessMode: 'Normal' | 'AllowList',1244) {1245  await usingApi(async (api) => {12461247    // Run the transaction1248    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1249    const events = await submitTransactionAsync(sender, tx);1250    const result = getGenericResult(events);12511252    // Get the collection1253    const collection = await queryCollectionExpectSuccess(api, collectionId);12541255    // What to expect1256    // tslint:disable-next-line:no-unused-expression1257    expect(result.success).to.be.true;1258    expect(collection.access.toHuman()).to.be.equal(accessMode);1259  });1260}12611262export async function setPublicAccessModeExpectFail(1263  sender: IKeyringPair, collectionId: number,1264  accessMode: 'Normal' | 'AllowList',1265) {1266  await usingApi(async (api) => {12671268    // Run the transaction1269    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1270    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1271    const result = getGenericResult(events);12721273    // What to expect1274    // tslint:disable-next-line:no-unused-expression1275    expect(result.success).to.be.false;1276  });1277}12781279export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1280  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1281}12821283export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1284  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1285}12861287export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1288  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1289}12901291export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1292  await usingApi(async (api) => {12931294    // Run the transaction1295    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1296    const events = await submitTransactionAsync(sender, tx);1297    const result = getGenericResult(events);1298    expect(result.success).to.be.true;12991300    // Get the collection1301    const collection = await queryCollectionExpectSuccess(api, collectionId);13021303    expect(collection.mintMode.toHuman()).to.be.equal(enabled);1304  });1305}13061307export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1308  await setMintPermissionExpectSuccess(sender, collectionId, true);1309}13101311export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1312  await usingApi(async (api) => {1313    // Run the transaction1314    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1315    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1316    const result = getCreateCollectionResult(events);1317    // tslint:disable-next-line:no-unused-expression1318    expect(result.success).to.be.false;1319  });1320}13211322export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1323  await usingApi(async (api) => {1324    // Run the transaction1325    const tx = api.tx.unique.setChainLimits(limits);1326    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1327    const result = getCreateCollectionResult(events);1328    // tslint:disable-next-line:no-unused-expression1329    expect(result.success).to.be.false;1330  });1331}13321333export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1334  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1335}13361337export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1338  await usingApi(async (api) => {1339    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;13401341    // Run the transaction1342    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1343    const events = await submitTransactionAsync(sender, tx);1344    const result = getGenericResult(events);1345    expect(result.success).to.be.true;13461347    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1348  });1349}13501351export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1352  await usingApi(async (api) => {13531354    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;13551356    // Run the transaction1357    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1358    const events = await submitTransactionAsync(sender, tx);1359    const result = getGenericResult(events);1360    expect(result.success).to.be.true;13611362    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1363  });1364}13651366export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1367  await usingApi(async (api) => {13681369    // Run the transaction1370    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1371    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1372    const result = getGenericResult(events);13731374    // What to expect1375    // tslint:disable-next-line:no-unused-expression1376    expect(result.success).to.be.false;1377  });1378}13791380export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1381  await usingApi(async (api) => {1382    // Run the transaction1383    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1384    const events = await submitTransactionAsync(sender, tx);1385    const result = getGenericResult(events);13861387    // What to expect1388    // tslint:disable-next-line:no-unused-expression1389    expect(result.success).to.be.true;1390  });1391}13921393export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1394  await usingApi(async (api) => {1395    // Run the transaction1396    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1397    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1398    const result = getGenericResult(events);13991400    // What to expect1401    // tslint:disable-next-line:no-unused-expression1402    expect(result.success).to.be.false;1403  });1404}14051406export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1407  : Promise<UpDataStructsRpcCollection | null> => {1408  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1409};14101411export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1412  // set global object - collectionsCount1413  return (await api.rpc.unique.collectionStats()).created.toNumber();1414};14151416export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1417  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1418}14191420export async function waitNewBlocks(blocksCount = 1): Promise<void> {1421  await usingApi(async (api) => {1422    const promise = new Promise<void>(async (resolve) => {1423      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1424        if (blocksCount > 0) {1425          blocksCount--;1426        } else {1427          unsubscribe();1428          resolve();1429        }1430      });1431    });1432    return promise;1433  });1434}