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

difftreelog

fix warn about skipped tests

Daniel Shiposha2022-08-09parent: #3d7ffe7.patch.diff
in: master

1 file changed

modifiedtests/src/util/helpers.tsdiffbeforeafterboth
before · tests/src/util/helpers.ts
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} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import type {GenericEventData} from '@polkadot/types';22import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';23import {evmToAddress} from '@polkadot/util-crypto';24import BN from 'bn.js';25import chai from 'chai';26import chaiAsPromised from 'chai-as-promised';27import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';28import {hexToStr, strToUTF16, utf16ToStr} from './util';29import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';30import {UpDataStructsTokenChild} from '../interfaces';31import { Context } from 'mocha';3233chai.use(chaiAsPromised);34const expect = chai.expect;3536export type CrossAccountId = {37  Substrate: string,38} | {39  Ethereum: string,40};414243export enum Pallets {44  Inflation = 'inflation',45  RmrkCore = 'rmrkcore',46  RmrkEquip = 'rmrkequip',47  ReFungible = 'refungible',48  Fungible = 'fungible',49  NFT = 'nonfungible',50}5152export async function isUnique(): Promise<boolean> {53  return usingApi(async api => {54    const chain = await api.rpc.system.chain();5556    return chain.eq('UNIQUE');57  });58}5960export async function isQuartz(): Promise<boolean> {61  return usingApi(async api => {62    const chain = await api.rpc.system.chain();63    64    return chain.eq('QUARTZ');65  });66}6768let modulesNames: any;69export function getModuleNames(api: ApiPromise): string[] {70  if (typeof modulesNames === 'undefined') 71    modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());72  return modulesNames;73}7475export function requirePallets(mocha: Context, api: ApiPromise, requiredPallets: string[]) {76  const pallets = getModuleNames(api);7778  const isAllPalletsPresent = requiredPallets.every(p => pallets.includes(p));7980  if (!isAllPalletsPresent) {81    mocha.skip();82  }83}8485export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {86  if (typeof input === 'string') {87    if (input.length >= 47) {88      return {Substrate: input};89    } else if (input.length === 42 && input.startsWith('0x')) {90      return {Ethereum: input.toLowerCase()};91    } else if (input.length === 40 && !input.startsWith('0x')) {92      return {Ethereum: '0x' + input.toLowerCase()};93    } else {94      throw new Error(`Unknown address format: "${input}"`);95    }96  }97  if ('address' in input) {98    return {Substrate: input.address};99  }100  if ('Ethereum' in input) {101    return {102      Ethereum: input.Ethereum.toLowerCase(),103    };104  } else if ('ethereum' in input) {105    return {106      Ethereum: (input as any).ethereum.toLowerCase(),107    };108  } else if ('Substrate' in input) {109    return input;110  } else if ('substrate' in input) {111    return {112      Substrate: (input as any).substrate,113    };114  }115116  // AccountId117  return {Substrate: input.toString()};118}119export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {120  input = normalizeAccountId(input);121  if ('Substrate' in input) {122    return input.Substrate;123  } else {124    return evmToAddress(input.Ethereum);125  }126}127128export const U128_MAX = (1n << 128n) - 1n;129130const MICROUNIQUE = 1_000_000_000_000n;131const MILLIUNIQUE = 1_000n * MICROUNIQUE;132const CENTIUNIQUE = 10n * MILLIUNIQUE;133export const UNIQUE = 100n * CENTIUNIQUE;134135interface GenericResult<T> {136  success: boolean;137  data: T | null;138}139140interface CreateCollectionResult {141  success: boolean;142  collectionId: number;143}144145interface CreateItemResult {146  success: boolean;147  collectionId: number;148  itemId: number;149  recipient?: CrossAccountId;150  amount?: number;151}152153interface DestroyItemResult {154  success: boolean;155  collectionId: number;156  itemId: number;157  owner: CrossAccountId;158  amount: number;159}160161interface TransferResult {162  collectionId: number;163  itemId: number;164  sender?: CrossAccountId;165  recipient?: CrossAccountId;166  value: bigint;167}168169interface IReFungibleOwner {170  fraction: BN;171  owner: number[];172}173174interface IGetMessage {175  checkMsgUnqMethod: string;176  checkMsgTrsMethod: string;177  checkMsgSysMethod: string;178}179180export interface IFungibleTokenDataType {181  value: number;182}183184export interface IChainLimits {185  collectionNumbersLimit: number;186  accountTokenOwnershipLimit: number;187  collectionsAdminsLimit: number;188  customDataLimit: number;189  nftSponsorTransferTimeout: number;190  fungibleSponsorTransferTimeout: number;191  refungibleSponsorTransferTimeout: number;192  //offchainSchemaLimit: number;193  //constOnChainSchemaLimit: number;194}195196export interface IReFungibleTokenDataType {197  owner: IReFungibleOwner[];198}199200export function uniqueEventMessage(events: EventRecord[]): IGetMessage {201  let checkMsgUnqMethod = '';202  let checkMsgTrsMethod = '';203  let checkMsgSysMethod = '';204  events.forEach(({event: {method, section}}) => {205    if (section === 'common') {206      checkMsgUnqMethod = method;207    } else if (section === 'treasury') {208      checkMsgTrsMethod = method;209    } else if (section === 'system') {210      checkMsgSysMethod = method;211    } else { return null; }212  });213  const result: IGetMessage = {214    checkMsgUnqMethod,215    checkMsgTrsMethod,216    checkMsgSysMethod,217  };218  return result;219}220221export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {222  const event = events.find(r => check(r.event));223  if (!event) return;224  return event.event as T;225}226227export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;228export function getGenericResult<T>(229  events: EventRecord[],230  expectSection: string,231  expectMethod: string,232  extractAction: (data: GenericEventData) => T233): GenericResult<T>;234235export function getGenericResult<T>(236  events: EventRecord[],237  expectSection?: string,238  expectMethod?: string,239  extractAction?: (data: GenericEventData) => T,240): GenericResult<T> {241  let success = false;242  let successData = null;243244  events.forEach(({event: {data, method, section}}) => {245    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);246    if (method === 'ExtrinsicSuccess') {247      success = true;248    } else if ((expectSection == section) && (expectMethod == method)) {249      successData = extractAction!(data as any);250    }251  });252253  const result: GenericResult<T> = {254    success,255    data: successData,256  };257  return result;258}259260export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {261  const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));262  const result: CreateCollectionResult = {263    success: genericResult.success,264    collectionId: genericResult.data ?? 0,265  };266  return result;267}268269export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {270  const results: CreateItemResult[] = [];271  272  const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {273    const collectionId = parseInt(data[0].toString(), 10);274    const itemId = parseInt(data[1].toString(), 10);275    const recipient = normalizeAccountId(data[2].toJSON() as any);276    const amount = parseInt(data[3].toString(), 10);277278    const itemRes: CreateItemResult = {279      success: true,280      collectionId,281      itemId,282      recipient,283      amount,284    };285286    results.push(itemRes);287    return results;288  });289290  if (!genericResult.success) return [];291  return results;292}293294export function getCreateItemResult(events: EventRecord[]): CreateItemResult {295  const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));296  297  if (genericResult.data == null) 298    return {299      success: genericResult.success,300      collectionId: 0,301      itemId: 0,302      amount: 0,303    };304  else 305    return {306      success: genericResult.success,307      collectionId: genericResult.data[0] as number,308      itemId: genericResult.data[1] as number,309      recipient: normalizeAccountId(genericResult.data![2] as any),310      amount: genericResult.data[3] as number,311    };312}313314export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {315  const results: DestroyItemResult[] = [];316  317  const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {318    const collectionId = parseInt(data[0].toString(), 10);319    const itemId = parseInt(data[1].toString(), 10);320    const owner = normalizeAccountId(data[2].toJSON() as any);321    const amount = parseInt(data[3].toString(), 10);322323    const itemRes: DestroyItemResult = {324      success: true,325      collectionId,326      itemId,327      owner,328      amount,329    };330331    results.push(itemRes);332    return results;333  });334335  if (!genericResult.success) return [];336  return results;337}338339export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {340  for (const {event} of events) {341    if (api.events.common.Transfer.is(event)) {342      const [collection, token, sender, recipient, value] = event.data;343      return {344        collectionId: collection.toNumber(),345        itemId: token.toNumber(),346        sender: normalizeAccountId(sender.toJSON() as any),347        recipient: normalizeAccountId(recipient.toJSON() as any),348        value: value.toBigInt(),349      };350    }351  }352  throw new Error('no transfer event');353}354355interface Nft {356  type: 'NFT';357}358359interface Fungible {360  type: 'Fungible';361  decimalPoints: number;362}363364interface ReFungible {365  type: 'ReFungible';366}367368export type CollectionMode = Nft | Fungible | ReFungible;369370export type Property = {371  key: any,372  value: any,373};374375type Permission = {376  mutable: boolean;377  collectionAdmin: boolean;378  tokenOwner: boolean;379}380381type PropertyPermission = {382  key: any;383  permission: Permission;384}385386export type CreateCollectionParams = {387  mode: CollectionMode,388  name: string,389  description: string,390  tokenPrefix: string,391  properties?: Array<Property>,392  propPerm?: Array<PropertyPermission>393};394395const defaultCreateCollectionParams: CreateCollectionParams = {396  description: 'description',397  mode: {type: 'NFT'},398  name: 'name',399  tokenPrefix: 'prefix',400};401402export async function403createCollection(404  api: ApiPromise,405  sender: IKeyringPair,406  params: Partial<CreateCollectionParams> = {},407): Promise<CreateCollectionResult> {408  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};409410  let modeprm = {};411  if (mode.type === 'NFT') {412    modeprm = {nft: null};413  } else if (mode.type === 'Fungible') {414    modeprm = {fungible: mode.decimalPoints};415  } else if (mode.type === 'ReFungible') {416    modeprm = {refungible: null};417  }418419  const tx = api.tx.unique.createCollectionEx({420    name: strToUTF16(name),421    description: strToUTF16(description),422    tokenPrefix: strToUTF16(tokenPrefix),423    mode: modeprm as any,424  });425  const events = await submitTransactionAsync(sender, tx);426  return getCreateCollectionResult(events);427}428429export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {430  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};431432  let collectionId = 0;433  await usingApi(async (api, privateKeyWrapper) => {434    // Get number of collections before the transaction435    const collectionCountBefore = await getCreatedCollectionCount(api);436437    // Run the CreateCollection transaction438    const alicePrivateKey = privateKeyWrapper('//Alice');439440    const result = await createCollection(api, alicePrivateKey, params);441442    // Get number of collections after the transaction443    const collectionCountAfter = await getCreatedCollectionCount(api);444445    // Get the collection446    const collection = await queryCollectionExpectSuccess(api, result.collectionId);447448    // What to expect449    // tslint:disable-next-line:no-unused-expression450    expect(result.success).to.be.true;451    expect(result.collectionId).to.be.equal(collectionCountAfter);452    // tslint:disable-next-line:no-unused-expression453    expect(collection).to.be.not.null;454    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');455    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));456    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);457    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);458    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);459460    collectionId = result.collectionId;461  });462463  return collectionId;464}465466export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {467  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};468469  let collectionId = 0;470  await usingApi(async (api, privateKeyWrapper) => {471    // Get number of collections before the transaction472    const collectionCountBefore = await getCreatedCollectionCount(api);473474    // Run the CreateCollection transaction475    const alicePrivateKey = privateKeyWrapper('//Alice');476477    let modeprm = {};478    if (mode.type === 'NFT') {479      modeprm = {nft: null};480    } else if (mode.type === 'Fungible') {481      modeprm = {fungible: mode.decimalPoints};482    } else if (mode.type === 'ReFungible') {483      modeprm = {refungible: null};484    }485486    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});487    const events = await submitTransactionAsync(alicePrivateKey, tx);488    const result = getCreateCollectionResult(events);489490    // Get number of collections after the transaction491    const collectionCountAfter = await getCreatedCollectionCount(api);492493    // Get the collection494    const collection = await queryCollectionExpectSuccess(api, result.collectionId);495496    // What to expect497    // tslint:disable-next-line:no-unused-expression498    expect(result.success).to.be.true;499    expect(result.collectionId).to.be.equal(collectionCountAfter);500    // tslint:disable-next-line:no-unused-expression501    expect(collection).to.be.not.null;502    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');503    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));504    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);505    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);506    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);507508509    collectionId = result.collectionId;510  });511512  return collectionId;513}514515export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {516  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};517518  await usingApi(async (api, privateKeyWrapper) => {519    // Get number of collections before the transaction520    const collectionCountBefore = await getCreatedCollectionCount(api);521522    // Run the CreateCollection transaction523    const alicePrivateKey = privateKeyWrapper('//Alice');524525    let modeprm = {};526    if (mode.type === 'NFT') {527      modeprm = {nft: null};528    } else if (mode.type === 'Fungible') {529      modeprm = {fungible: mode.decimalPoints};530    } else if (mode.type === 'ReFungible') {531      modeprm = {refungible: null};532    }533534    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});535    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;536537538    // Get number of collections after the transaction539    const collectionCountAfter = await getCreatedCollectionCount(api);540541    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');542  });543}544545export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {546  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};547548  let modeprm = {};549  if (mode.type === 'NFT') {550    modeprm = {nft: null};551  } else if (mode.type === 'Fungible') {552    modeprm = {fungible: mode.decimalPoints};553  } else if (mode.type === 'ReFungible') {554    modeprm = {refungible: null};555  }556557  await usingApi(async (api, privateKeyWrapper) => {558    // Get number of collections before the transaction559    const collectionCountBefore = await getCreatedCollectionCount(api);560561    // Run the CreateCollection transaction562    const alicePrivateKey = privateKeyWrapper('//Alice');563    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});564    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;565566    // Get number of collections after the transaction567    const collectionCountAfter = await getCreatedCollectionCount(api);568569    // What to expect570    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');571  });572}573574export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {575  let bal = 0n;576  let unused;577  do {578    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;579    unused = privateKeyWrapper(`//${randomSeed}`);580    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();581  } while (bal !== 0n);582  return unused;583}584585export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {586  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();587}588589export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {590  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));591}592593export async function findNotExistingCollection(api: ApiPromise): Promise<number> {594  const totalNumber = await getCreatedCollectionCount(api);595  const newCollection: number = totalNumber + 1;596  return newCollection;597}598599function getDestroyResult(events: EventRecord[]): boolean {600  let success = false;601  events.forEach(({event: {method}}) => {602    if (method == 'ExtrinsicSuccess') {603      success = true;604    }605  });606  return success;607}608609export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {610  await usingApi(async (api, privateKeyWrapper) => {611    // Run the DestroyCollection transaction612    const alicePrivateKey = privateKeyWrapper(senderSeed);613    const tx = api.tx.unique.destroyCollection(collectionId);614    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;615  });616}617618export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {619  await usingApi(async (api, privateKeyWrapper) => {620    // Run the DestroyCollection transaction621    const alicePrivateKey = privateKeyWrapper(senderSeed);622    const tx = api.tx.unique.destroyCollection(collectionId);623    const events = await submitTransactionAsync(alicePrivateKey, tx);624    const result = getDestroyResult(events);625    expect(result).to.be.true;626627    // What to expect628    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;629  });630}631632export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {633  await usingApi(async (api) => {634    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);635    const events = await submitTransactionAsync(sender, tx);636    const result = getGenericResult(events);637638    expect(result.success).to.be.true;639  });640}641642export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {643  await usingApi(async(api) => {644    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);645    const events = await submitTransactionAsync(sender, tx);646    const result = getGenericResult(events);647648    expect(result.success).to.be.true;649  });650};651652export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {653  await usingApi(async (api) => {654    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);655    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;656    const result = getGenericResult(events);657658    expect(result.success).to.be.false;659  });660}661662export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {663  await usingApi(async (api, privateKeyWrapper) => {664665    // Run the transaction666    const senderPrivateKey = privateKeyWrapper(sender);667    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);668    const events = await submitTransactionAsync(senderPrivateKey, tx);669    const result = getGenericResult(events);670671    // Get the collection672    const collection = await queryCollectionExpectSuccess(api, collectionId);673674    // What to expect675    expect(result.success).to.be.true;676    expect(collection.sponsorship.toJSON()).to.deep.equal({677      unconfirmed: sponsor,678    });679  });680}681682export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {683  await usingApi(async (api, privateKeyWrapper) => {684685    // Run the transaction686    const alicePrivateKey = privateKeyWrapper(sender);687    const tx = api.tx.unique.removeCollectionSponsor(collectionId);688    const events = await submitTransactionAsync(alicePrivateKey, tx);689    const result = getGenericResult(events);690691    // Get the collection692    const collection = await queryCollectionExpectSuccess(api, collectionId);693694    // What to expect695    expect(result.success).to.be.true;696    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});697  });698}699700export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {701  await usingApi(async (api, privateKeyWrapper) => {702703    // Run the transaction704    const alicePrivateKey = privateKeyWrapper(senderSeed);705    const tx = api.tx.unique.removeCollectionSponsor(collectionId);706    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;707  });708}709710export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {711  await usingApi(async (api, privateKeyWrapper) => {712713    // Run the transaction714    const alicePrivateKey = privateKeyWrapper(senderSeed);715    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);716    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;717  });718}719720export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {721  await usingApi(async (api, privateKeyWrapper) => {722723    // Run the transaction724    const sender = privateKeyWrapper(senderSeed);725    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);726  });727}728729export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {730  await usingApi(async (api, privateKeyWrapper) => {731732    // Run the transaction733    const tx = api.tx.unique.confirmSponsorship(collectionId);734    const events = await submitTransactionAsync(sender, tx);735    const result = getGenericResult(events);736737    // Get the collection738    const collection = await queryCollectionExpectSuccess(api, collectionId);739740    // What to expect741    expect(result.success).to.be.true;742    expect(collection.sponsorship.toJSON()).to.be.deep.equal({743      confirmed: sender.address,744    });745  });746}747748749export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {750  await usingApi(async (api, privateKeyWrapper) => {751752    // Run the transaction753    const sender = privateKeyWrapper(senderSeed);754    const tx = api.tx.unique.confirmSponsorship(collectionId);755    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;756  });757}758759export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {760  await usingApi(async (api) => {761    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);762    const events = await submitTransactionAsync(sender, tx);763    const result = getGenericResult(events);764765    expect(result.success).to.be.true;766  });767}768769export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {770  await usingApi(async (api) => {771    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);772    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;773    const result = getGenericResult(events);774775    expect(result.success).to.be.false;776  });777}778779export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {780781  await usingApi(async (api) => {782783    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);784    const events = await submitTransactionAsync(sender, tx);785    const result = getGenericResult(events);786787    expect(result.success).to.be.true;788  });789}790791export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {792793  await usingApi(async (api) => {794795    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);796    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;797    const result = getGenericResult(events);798799    expect(result.success).to.be.false;800  });801}802803export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {804  await usingApi(async (api) => {805    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);806    const events = await submitTransactionAsync(sender, tx);807    const result = getGenericResult(events);808809    expect(result.success).to.be.true;810  });811}812813export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {814  await usingApi(async (api) => {815    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);816    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;817    const result = getGenericResult(events);818819    expect(result.success).to.be.false;820  });821}822823export async function getNextSponsored(824  api: ApiPromise,825  collectionId: number,826  account: string | CrossAccountId,827  tokenId: number,828): Promise<number> {829  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));830}831832export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {833  await usingApi(async (api) => {834    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);835    const events = await submitTransactionAsync(sender, tx);836    const result = getGenericResult(events);837838    expect(result.success).to.be.true;839  });840}841842export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {843  let allowlisted = false;844  await usingApi(async (api) => {845    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;846  });847  return allowlisted;848}849850export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {851  await usingApi(async (api) => {852    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());853    const events = await submitTransactionAsync(sender, tx);854    const result = getGenericResult(events);855856    expect(result.success).to.be.true;857  });858}859860export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {861  await usingApi(async (api) => {862    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());863    const events = await submitTransactionAsync(sender, tx);864    const result = getGenericResult(events);865866    expect(result.success).to.be.true;867  });868}869870export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {871  await usingApi(async (api) => {872    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());873    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;874    const result = getGenericResult(events);875876    expect(result.success).to.be.false;877  });878}879880export interface CreateFungibleData {881  readonly Value: bigint;882}883884export interface CreateReFungibleData { }885export interface CreateNftData { }886887export type CreateItemData = {888  NFT: CreateNftData;889} | {890  Fungible: CreateFungibleData;891} | {892  ReFungible: CreateReFungibleData;893};894895export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {896  const tx = api.tx.unique.burnItem(collectionId, tokenId, value);897  const events = await submitTransactionAsync(sender, tx);898  return getGenericResult(events).success;899}900901export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {902  await usingApi(async (api) => {903    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);904    // if burning token by admin - use adminButnItemExpectSuccess905    expect(balanceBefore >= BigInt(value)).to.be.true;906907    expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;908909    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);910    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);911  });912}913914export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {915  await usingApi(async (api) => {916    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);917918    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;919    const result = getCreateCollectionResult(events);920    // tslint:disable-next-line:no-unused-expression921    expect(result.success).to.be.false;922  });923}924925export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {926  await usingApi(async (api) => {927    const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);928    const events = await submitTransactionAsync(sender, tx);929    return getGenericResult(events).success;930  });931}932933export async function934approve(935  api: ApiPromise,936  collectionId: number,937  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,938) {939  const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);940  const events = await submitTransactionAsync(owner, approveUniqueTx);941  return getGenericResult(events).success;942}943944export async function945approveExpectSuccess(946  collectionId: number,947  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,948) {949  await usingApi(async (api: ApiPromise) => {950    const result = await approve(api, collectionId, tokenId, owner, approved, amount);951    expect(result).to.be.true;952953    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));954  });955}956957export async function adminApproveFromExpectSuccess(958  collectionId: number,959  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,960) {961  await usingApi(async (api: ApiPromise) => {962    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);963    const events = await submitTransactionAsync(admin, approveUniqueTx);964    const result = getGenericResult(events);965    expect(result.success).to.be.true;966967    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));968  });969}970971export async function972transferFrom(973  api: ApiPromise,974  collectionId: number,975  tokenId: number,976  accountApproved: IKeyringPair,977  accountFrom: IKeyringPair | CrossAccountId,978  accountTo: IKeyringPair | CrossAccountId,979  value: number | bigint,980) {981  const from = normalizeAccountId(accountFrom);982  const to = normalizeAccountId(accountTo);983  const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);984  const events = await submitTransactionAsync(accountApproved, transferFromTx);985  return getGenericResult(events).success;986}987988export async function989transferFromExpectSuccess(990  collectionId: number,991  tokenId: number,992  accountApproved: IKeyringPair,993  accountFrom: IKeyringPair | CrossAccountId,994  accountTo: IKeyringPair | CrossAccountId,995  value: number | bigint = 1,996  type = 'NFT',997) {998  await usingApi(async (api: ApiPromise) => {999    const from = normalizeAccountId(accountFrom);1000    const to = normalizeAccountId(accountTo);1001    let balanceBefore = 0n;1002    if (type === 'Fungible' || type === 'ReFungible') {1003      balanceBefore = await getBalance(api, collectionId, to, tokenId);1004    }1005    expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;1006    if (type === 'NFT') {1007      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1008    }1009    if (type === 'Fungible') {1010      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1011      if (JSON.stringify(to) !== JSON.stringify(from)) {1012        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1013      } else {1014        expect(balanceAfter).to.be.equal(balanceBefore);1015      }1016    }1017    if (type === 'ReFungible') {1018      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1019    }1020  });1021}10221023export async function1024transferFromExpectFail(1025  collectionId: number,1026  tokenId: number,1027  accountApproved: IKeyringPair,1028  accountFrom: IKeyringPair,1029  accountTo: IKeyringPair,1030  value: number | bigint = 1,1031) {1032  await usingApi(async (api: ApiPromise) => {1033    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1034    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1035    const result = getCreateCollectionResult(events);1036    // tslint:disable-next-line:no-unused-expression1037    expect(result.success).to.be.false;1038  });1039}10401041/* eslint no-async-promise-executor: "off" */1042export async function getBlockNumber(api: ApiPromise): Promise<number> {1043  return new Promise<number>(async (resolve) => {1044    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1045      unsubscribe();1046      resolve(head.number.toNumber());1047    });1048  });1049}10501051export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1052  await usingApi(async (api) => {1053    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1054    const events = await submitTransactionAsync(sender, changeAdminTx);1055    const result = getCreateCollectionResult(events);1056    expect(result.success).to.be.true;1057  });1058}10591060export async function adminApproveFromExpectFail(1061  collectionId: number,1062  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1063) {1064  await usingApi(async (api: ApiPromise) => {1065    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1066    const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1067    const result = getGenericResult(events);1068    expect(result.success).to.be.false;1069  });1070}10711072export async function1073getFreeBalance(account: IKeyringPair): Promise<bigint> {1074  let balance = 0n;1075  await usingApi(async (api) => {1076    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1077  });10781079  return balance;1080}10811082export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1083  const tx = api.tx.balances.transfer(target, amount);1084  const events = await submitTransactionAsync(source, tx);1085  const result = getGenericResult(events);1086  expect(result.success).to.be.true;1087}10881089export async function1090scheduleExpectSuccess(1091  operationTx: any,1092  sender: IKeyringPair,1093  blockSchedule: number,1094  scheduledId: string,1095  period = 1,1096  repetitions = 1,1097) {1098  await usingApi(async (api: ApiPromise) => {1099    const blockNumber: number | undefined = await getBlockNumber(api);1100    const expectedBlockNumber = blockNumber + blockSchedule;11011102    expect(blockNumber).to.be.greaterThan(0);1103    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1104      scheduledId,1105      expectedBlockNumber, 1106      repetitions > 1 ? [period, repetitions] : null, 1107      0, 1108      {Value: operationTx as any},1109    );11101111    const events = await submitTransactionAsync(sender, scheduleTx);1112    expect(getGenericResult(events).success).to.be.true;1113  });1114}11151116export async function1117scheduleExpectFailure(1118  operationTx: any,1119  sender: IKeyringPair,1120  blockSchedule: number,1121  scheduledId: string,1122  period = 1,1123  repetitions = 1,1124) {1125  await usingApi(async (api: ApiPromise) => {1126    const blockNumber: number | undefined = await getBlockNumber(api);1127    const expectedBlockNumber = blockNumber + blockSchedule;11281129    expect(blockNumber).to.be.greaterThan(0);1130    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1131      scheduledId,1132      expectedBlockNumber, 1133      repetitions <= 1 ? null : [period, repetitions], 1134      0, 1135      {Value: operationTx as any},1136    );11371138    //const events = 1139    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1140    //expect(getGenericResult(events).success).to.be.false;1141  });1142}11431144export async function1145scheduleTransferAndWaitExpectSuccess(1146  collectionId: number,1147  tokenId: number,1148  sender: IKeyringPair,1149  recipient: IKeyringPair,1150  value: number | bigint = 1,1151  blockSchedule: number,1152  scheduledId: string,1153) {1154  await usingApi(async (api: ApiPromise) => {1155    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);11561157    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();11581159    // sleep for n + 1 blocks1160    await waitNewBlocks(blockSchedule + 1);11611162    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();11631164    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1165    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1166  });1167}11681169export async function1170scheduleTransferExpectSuccess(1171  collectionId: number,1172  tokenId: number,1173  sender: IKeyringPair,1174  recipient: IKeyringPair,1175  value: number | bigint = 1,1176  blockSchedule: number,1177  scheduledId: string,1178) {1179  await usingApi(async (api: ApiPromise) => {1180    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);11811182    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);11831184    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1185  });1186}11871188export async function1189scheduleTransferFundsPeriodicExpectSuccess(1190  amount: bigint,1191  sender: IKeyringPair,1192  recipient: IKeyringPair,1193  blockSchedule: number,1194  scheduledId: string,1195  period: number,1196  repetitions: number,1197) {1198  await usingApi(async (api: ApiPromise) => {1199    const transferTx = api.tx.balances.transfer(recipient.address, amount);12001201    const balanceBefore = await getFreeBalance(recipient);1202    1203    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);12041205    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1206  });1207}12081209export async function1210transfer(1211  api: ApiPromise,1212  collectionId: number,1213  tokenId: number,1214  sender: IKeyringPair,1215  recipient: IKeyringPair | CrossAccountId,1216  value: number | bigint,1217) : Promise<boolean> {1218  const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1219  const events = await executeTransaction(api, sender, transferTx);1220  return getGenericResult(events).success;1221}12221223export async function1224transferExpectSuccess(1225  collectionId: number,1226  tokenId: number,1227  sender: IKeyringPair,1228  recipient: IKeyringPair | CrossAccountId,1229  value: number | bigint = 1,1230  type = 'NFT',1231) {1232  await usingApi(async (api: ApiPromise) => {1233    const from = normalizeAccountId(sender);1234    const to = normalizeAccountId(recipient);12351236    let balanceBefore = 0n;1237    if (type === 'Fungible' || type === 'ReFungible') {1238      balanceBefore = await getBalance(api, collectionId, to, tokenId);1239    }12401241    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1242    const events = await executeTransaction(api, sender, transferTx);1243    const result = getTransferResult(api, events);12441245    expect(result.collectionId).to.be.equal(collectionId);1246    expect(result.itemId).to.be.equal(tokenId);1247    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1248    expect(result.recipient).to.be.deep.equal(to);1249    expect(result.value).to.be.equal(BigInt(value));12501251    if (type === 'NFT') {1252      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1253    }1254    if (type === 'Fungible' || type === 'ReFungible') {1255      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1256      if (JSON.stringify(to) !== JSON.stringify(from)) {1257        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1258      } else {1259        expect(balanceAfter).to.be.equal(balanceBefore);1260      }1261    }1262  });1263}12641265export async function1266transferExpectFailure(1267  collectionId: number,1268  tokenId: number,1269  sender: IKeyringPair,1270  recipient: IKeyringPair | CrossAccountId,1271  value: number | bigint = 1,1272) {1273  await usingApi(async (api: ApiPromise) => {1274    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1275    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1276    const result = getGenericResult(events);1277    // if (events && Array.isArray(events)) {1278    //   const result = getCreateCollectionResult(events);1279    // tslint:disable-next-line:no-unused-expression1280    expect(result.success).to.be.false;1281    //}1282  });1283}12841285export async function1286approveExpectFail(1287  collectionId: number,1288  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1289) {1290  await usingApi(async (api: ApiPromise) => {1291    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1292    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1293    const result = getCreateCollectionResult(events);1294    // tslint:disable-next-line:no-unused-expression1295    expect(result.success).to.be.false;1296  });1297}12981299export async function getBalance(1300  api: ApiPromise,1301  collectionId: number,1302  owner: string | CrossAccountId | IKeyringPair,1303  token: number,1304): Promise<bigint> {1305  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1306}1307export async function getTokenOwner(1308  api: ApiPromise,1309  collectionId: number,1310  token: number,1311): Promise<CrossAccountId> {1312  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1313  if (owner == null) throw new Error('owner == null');1314  return normalizeAccountId(owner);1315}1316export async function getTopmostTokenOwner(1317  api: ApiPromise,1318  collectionId: number,1319  token: number,1320): Promise<CrossAccountId> {1321  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1322  if (owner == null) throw new Error('owner == null');1323  return normalizeAccountId(owner);1324}1325export async function getTokenChildren(1326  api: ApiPromise,1327  collectionId: number,1328  tokenId: number,1329): Promise<UpDataStructsTokenChild[]> {1330  return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1331}1332export async function isTokenExists(1333  api: ApiPromise,1334  collectionId: number,1335  token: number,1336): Promise<boolean> {1337  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1338}1339export async function getLastTokenId(1340  api: ApiPromise,1341  collectionId: number,1342): Promise<number> {1343  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1344}1345export async function getAdminList(1346  api: ApiPromise,1347  collectionId: number,1348): Promise<string[]> {1349  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1350}1351export async function getTokenProperties(1352  api: ApiPromise,1353  collectionId: number,1354  tokenId: number,1355  propertyKeys: string[],1356): Promise<UpDataStructsProperty[]> {1357  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1358}13591360export async function createFungibleItemExpectSuccess(1361  sender: IKeyringPair,1362  collectionId: number,1363  data: CreateFungibleData,1364  owner: CrossAccountId | string = sender.address,1365) {1366  return await usingApi(async (api) => {1367    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});13681369    const events = await submitTransactionAsync(sender, tx);1370    const result = getCreateItemResult(events);13711372    expect(result.success).to.be.true;1373    return result.itemId;1374  });1375}13761377export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1378  await usingApi(async (api) => {1379    const to = normalizeAccountId(owner);1380    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);13811382    const events = await submitTransactionAsync(sender, tx);1383    expect(getGenericResult(events).success).to.be.true;1384  });1385}13861387export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1388  await usingApi(async (api) => {1389    const to = normalizeAccountId(owner);1390    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);13911392    const events = await submitTransactionAsync(sender, tx);1393    const result = getCreateItemsResult(events);13941395    for (const res of result) {1396      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1397    }1398  });1399}14001401export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1402  await usingApi(async (api) => {1403    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);14041405    const events = await submitTransactionAsync(sender, tx);1406    const result = getCreateItemsResult(events);14071408    for (const res of result) {1409      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1410    }1411  });1412}14131414export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1415  let newItemId = 0;1416  await usingApi(async (api) => {1417    const to = normalizeAccountId(owner);1418    const itemCountBefore = await getLastTokenId(api, collectionId);1419    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14201421    let tx;1422    if (createMode === 'Fungible') {1423      const createData = {fungible: {value: 10}};1424      tx = api.tx.unique.createItem(collectionId, to, createData as any);1425    } else if (createMode === 'ReFungible') {1426      const createData = {refungible: {pieces: 100}};1427      tx = api.tx.unique.createItem(collectionId, to, createData as any);1428    } else {1429      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1430      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1431    }14321433    const events = await submitTransactionAsync(sender, tx);1434    const result = getCreateItemResult(events);14351436    const itemCountAfter = await getLastTokenId(api, collectionId);1437    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14381439    if (createMode === 'NFT') {1440      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1441    }14421443    // What to expect1444    // tslint:disable-next-line:no-unused-expression1445    expect(result.success).to.be.true;1446    if (createMode === 'Fungible') {1447      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1448    } else {1449      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1450    }1451    expect(collectionId).to.be.equal(result.collectionId);1452    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1453    expect(to).to.be.deep.equal(result.recipient);1454    newItemId = result.itemId;1455  });1456  return newItemId;1457}14581459export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1460  await usingApi(async (api) => {14611462    let tx;1463    if (createMode === 'NFT') {1464      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1465      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1466    } else {1467      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1468    }146914701471    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1472    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1473    const result = getCreateItemResult(events);14741475    expect(result.success).to.be.false;1476  });1477}14781479export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1480  let newItemId = 0;1481  await usingApi(async (api) => {1482    const to = normalizeAccountId(owner);1483    const itemCountBefore = await getLastTokenId(api, collectionId);1484    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14851486    let tx;1487    if (createMode === 'Fungible') {1488      const createData = {fungible: {value: 10}};1489      tx = api.tx.unique.createItem(collectionId, to, createData as any);1490    } else if (createMode === 'ReFungible') {1491      const createData = {refungible: {pieces: 100}};1492      tx = api.tx.unique.createItem(collectionId, to, createData as any);1493    } else {1494      const createData = {nft: {}};1495      tx = api.tx.unique.createItem(collectionId, to, createData as any);1496    }14971498    const events = await executeTransaction(api, sender, tx);1499    const result = getCreateItemResult(events);15001501    const itemCountAfter = await getLastTokenId(api, collectionId);1502    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15031504    // What to expect1505    // tslint:disable-next-line:no-unused-expression1506    expect(result.success).to.be.true;1507    if (createMode === 'Fungible') {1508      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1509    } else {1510      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1511    }1512    expect(collectionId).to.be.equal(result.collectionId);1513    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1514    expect(to).to.be.deep.equal(result.recipient);1515    newItemId = result.itemId;1516  });1517  return newItemId;1518}15191520export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1521  const createData = {refungible: {pieces: amount}};1522  const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15231524  const events = await submitTransactionAsync(sender, tx);1525  return  getCreateItemResult(events);1526}15271528export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1529  await usingApi(async (api) => {1530    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15311532    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1533    const result = getCreateItemResult(events);15341535    expect(result.success).to.be.false;1536  });1537}15381539export async function setPublicAccessModeExpectSuccess(1540  sender: IKeyringPair, collectionId: number,1541  accessMode: 'Normal' | 'AllowList',1542) {1543  await usingApi(async (api) => {15441545    // Run the transaction1546    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1547    const events = await submitTransactionAsync(sender, tx);1548    const result = getGenericResult(events);15491550    // Get the collection1551    const collection = await queryCollectionExpectSuccess(api, collectionId);15521553    // What to expect1554    // tslint:disable-next-line:no-unused-expression1555    expect(result.success).to.be.true;1556    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1557  });1558}15591560export async function setPublicAccessModeExpectFail(1561  sender: IKeyringPair, collectionId: number,1562  accessMode: 'Normal' | 'AllowList',1563) {1564  await usingApi(async (api) => {15651566    // Run the transaction1567    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1568    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1569    const result = getGenericResult(events);15701571    // What to expect1572    // tslint:disable-next-line:no-unused-expression1573    expect(result.success).to.be.false;1574  });1575}15761577export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1578  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1579}15801581export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1582  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1583}15841585export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1586  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1587}15881589export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1590  await usingApi(async (api) => {15911592    // Run the transaction1593    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1594    const events = await submitTransactionAsync(sender, tx);1595    const result = getGenericResult(events);1596    expect(result.success).to.be.true;15971598    // Get the collection1599    const collection = await queryCollectionExpectSuccess(api, collectionId);16001601    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1602  });1603}16041605export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1606  await setMintPermissionExpectSuccess(sender, collectionId, true);1607}16081609export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1610  await usingApi(async (api) => {1611    // Run the transaction1612    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1613    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1614    const result = getCreateCollectionResult(events);1615    // tslint:disable-next-line:no-unused-expression1616    expect(result.success).to.be.false;1617  });1618}16191620export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1621  await usingApi(async (api) => {1622    // Run the transaction1623    const tx = api.tx.unique.setChainLimits(limits);1624    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1625    const result = getCreateCollectionResult(events);1626    // tslint:disable-next-line:no-unused-expression1627    expect(result.success).to.be.false;1628  });1629}16301631export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1632  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1633}16341635export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1636  await usingApi(async (api) => {1637    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16381639    // Run the transaction1640    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1641    const events = await submitTransactionAsync(sender, tx);1642    const result = getGenericResult(events);1643    expect(result.success).to.be.true;16441645    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1646  });1647}16481649export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1650  await usingApi(async (api) => {16511652    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;16531654    // Run the transaction1655    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1656    const events = await submitTransactionAsync(sender, tx);1657    const result = getGenericResult(events);1658    expect(result.success).to.be.true;16591660    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1661  });1662}16631664export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1665  await usingApi(async (api) => {16661667    // Run the transaction1668    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1669    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1670    const result = getGenericResult(events);16711672    // What to expect1673    // tslint:disable-next-line:no-unused-expression1674    expect(result.success).to.be.false;1675  });1676}16771678export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1679  await usingApi(async (api) => {1680    // Run the transaction1681    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1682    const events = await submitTransactionAsync(sender, tx);1683    const result = getGenericResult(events);16841685    // What to expect1686    // tslint:disable-next-line:no-unused-expression1687    expect(result.success).to.be.true;1688  });1689}16901691export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1692  await usingApi(async (api) => {1693    // Run the transaction1694    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1695    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1696    const result = getGenericResult(events);16971698    // What to expect1699    // tslint:disable-next-line:no-unused-expression1700    expect(result.success).to.be.false;1701  });1702}17031704export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1705  : Promise<UpDataStructsRpcCollection | null> => {1706  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1707};17081709export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1710  // set global object - collectionsCount1711  return (await api.rpc.unique.collectionStats()).created.toNumber();1712};17131714export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1715  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1716}17171718export async function waitNewBlocks(blocksCount = 1): Promise<void> {1719  await usingApi(async (api) => {1720    const promise = new Promise<void>(async (resolve) => {1721      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1722        if (blocksCount > 0) {1723          blocksCount--;1724        } else {1725          unsubscribe();1726          resolve();1727        }1728      });1729    });1730    return promise;1731  });1732}17331734export async function repartitionRFT(1735  api: ApiPromise,1736  collectionId: number,1737  sender: IKeyringPair,1738  tokenId: number,1739  amount: bigint,1740): Promise<boolean> {1741  const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1742  const events = await submitTransactionAsync(sender, tx);1743  const result = getGenericResult(events);17441745  return result.success;1746}17471748export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1749  let i: any = it;1750  if (opts.only) i = i.only;1751  else if (opts.skip) i = i.skip;1752  i(name, async () => {1753    await usingApi(async (api, privateKeyWrapper) => {1754      await cb({api, privateKeyWrapper});1755    });1756  });1757}17581759itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1760itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});
after · tests/src/util/helpers.ts
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} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import type {GenericEventData} from '@polkadot/types';22import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';23import {evmToAddress} from '@polkadot/util-crypto';24import BN from 'bn.js';25import chai from 'chai';26import chaiAsPromised from 'chai-as-promised';27import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';28import {hexToStr, strToUTF16, utf16ToStr} from './util';29import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';30import {UpDataStructsTokenChild} from '../interfaces';31import { Context } from 'mocha';3233chai.use(chaiAsPromised);34const expect = chai.expect;3536export type CrossAccountId = {37  Substrate: string,38} | {39  Ethereum: string,40};414243export enum Pallets {44  Inflation = 'inflation',45  RmrkCore = 'rmrkcore',46  RmrkEquip = 'rmrkequip',47  ReFungible = 'refungible',48  Fungible = 'fungible',49  NFT = 'nonfungible',50  Scheduler = 'scheduler',51}5253export async function isUnique(): Promise<boolean> {54  return usingApi(async api => {55    const chain = await api.rpc.system.chain();5657    return chain.eq('UNIQUE');58  });59}6061export async function isQuartz(): Promise<boolean> {62  return usingApi(async api => {63    const chain = await api.rpc.system.chain();64    65    return chain.eq('QUARTZ');66  });67}6869let modulesNames: any;70export function getModuleNames(api: ApiPromise): string[] {71  if (typeof modulesNames === 'undefined') 72    modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());73  return modulesNames;74}7576export async function missingRequiredPallets(requiredPallets: string[]): Promise<string[]> {77  return await usingApi(async api => {78    const pallets = getModuleNames(api);7980    return requiredPallets.filter(p => !pallets.includes(p));81  });82}8384export async function checkPalletsPresence(requiredPallets: string[]): Promise<boolean> {85  return (await missingRequiredPallets(requiredPallets)).length == 0;86}8788export async function requirePallets(mocha: Context, requiredPallets: string[]) {89  const missingPallets = await missingRequiredPallets(requiredPallets);9091  if (missingPallets.length > 0) {92    const skippingTestMsg = `\tSkipping test "${mocha.test?.title}".`;93    const missingPalletsMsg = `\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;94    const skipMsg = `${skippingTestMsg}\n${missingPalletsMsg}`;9596    console.log('\x1b[38:5:208m%s\x1b[0m', skipMsg);9798    mocha.skip();99  }100}101102export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {103  if (typeof input === 'string') {104    if (input.length >= 47) {105      return {Substrate: input};106    } else if (input.length === 42 && input.startsWith('0x')) {107      return {Ethereum: input.toLowerCase()};108    } else if (input.length === 40 && !input.startsWith('0x')) {109      return {Ethereum: '0x' + input.toLowerCase()};110    } else {111      throw new Error(`Unknown address format: "${input}"`);112    }113  }114  if ('address' in input) {115    return {Substrate: input.address};116  }117  if ('Ethereum' in input) {118    return {119      Ethereum: input.Ethereum.toLowerCase(),120    };121  } else if ('ethereum' in input) {122    return {123      Ethereum: (input as any).ethereum.toLowerCase(),124    };125  } else if ('Substrate' in input) {126    return input;127  } else if ('substrate' in input) {128    return {129      Substrate: (input as any).substrate,130    };131  }132133  // AccountId134  return {Substrate: input.toString()};135}136export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {137  input = normalizeAccountId(input);138  if ('Substrate' in input) {139    return input.Substrate;140  } else {141    return evmToAddress(input.Ethereum);142  }143}144145export const U128_MAX = (1n << 128n) - 1n;146147const MICROUNIQUE = 1_000_000_000_000n;148const MILLIUNIQUE = 1_000n * MICROUNIQUE;149const CENTIUNIQUE = 10n * MILLIUNIQUE;150export const UNIQUE = 100n * CENTIUNIQUE;151152interface GenericResult<T> {153  success: boolean;154  data: T | null;155}156157interface CreateCollectionResult {158  success: boolean;159  collectionId: number;160}161162interface CreateItemResult {163  success: boolean;164  collectionId: number;165  itemId: number;166  recipient?: CrossAccountId;167  amount?: number;168}169170interface DestroyItemResult {171  success: boolean;172  collectionId: number;173  itemId: number;174  owner: CrossAccountId;175  amount: number;176}177178interface TransferResult {179  collectionId: number;180  itemId: number;181  sender?: CrossAccountId;182  recipient?: CrossAccountId;183  value: bigint;184}185186interface IReFungibleOwner {187  fraction: BN;188  owner: number[];189}190191interface IGetMessage {192  checkMsgUnqMethod: string;193  checkMsgTrsMethod: string;194  checkMsgSysMethod: string;195}196197export interface IFungibleTokenDataType {198  value: number;199}200201export interface IChainLimits {202  collectionNumbersLimit: number;203  accountTokenOwnershipLimit: number;204  collectionsAdminsLimit: number;205  customDataLimit: number;206  nftSponsorTransferTimeout: number;207  fungibleSponsorTransferTimeout: number;208  refungibleSponsorTransferTimeout: number;209  //offchainSchemaLimit: number;210  //constOnChainSchemaLimit: number;211}212213export interface IReFungibleTokenDataType {214  owner: IReFungibleOwner[];215}216217export function uniqueEventMessage(events: EventRecord[]): IGetMessage {218  let checkMsgUnqMethod = '';219  let checkMsgTrsMethod = '';220  let checkMsgSysMethod = '';221  events.forEach(({event: {method, section}}) => {222    if (section === 'common') {223      checkMsgUnqMethod = method;224    } else if (section === 'treasury') {225      checkMsgTrsMethod = method;226    } else if (section === 'system') {227      checkMsgSysMethod = method;228    } else { return null; }229  });230  const result: IGetMessage = {231    checkMsgUnqMethod,232    checkMsgTrsMethod,233    checkMsgSysMethod,234  };235  return result;236}237238export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {239  const event = events.find(r => check(r.event));240  if (!event) return;241  return event.event as T;242}243244export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;245export function getGenericResult<T>(246  events: EventRecord[],247  expectSection: string,248  expectMethod: string,249  extractAction: (data: GenericEventData) => T250): GenericResult<T>;251252export function getGenericResult<T>(253  events: EventRecord[],254  expectSection?: string,255  expectMethod?: string,256  extractAction?: (data: GenericEventData) => T,257): GenericResult<T> {258  let success = false;259  let successData = null;260261  events.forEach(({event: {data, method, section}}) => {262    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);263    if (method === 'ExtrinsicSuccess') {264      success = true;265    } else if ((expectSection == section) && (expectMethod == method)) {266      successData = extractAction!(data as any);267    }268  });269270  const result: GenericResult<T> = {271    success,272    data: successData,273  };274  return result;275}276277export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {278  const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));279  const result: CreateCollectionResult = {280    success: genericResult.success,281    collectionId: genericResult.data ?? 0,282  };283  return result;284}285286export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {287  const results: CreateItemResult[] = [];288  289  const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {290    const collectionId = parseInt(data[0].toString(), 10);291    const itemId = parseInt(data[1].toString(), 10);292    const recipient = normalizeAccountId(data[2].toJSON() as any);293    const amount = parseInt(data[3].toString(), 10);294295    const itemRes: CreateItemResult = {296      success: true,297      collectionId,298      itemId,299      recipient,300      amount,301    };302303    results.push(itemRes);304    return results;305  });306307  if (!genericResult.success) return [];308  return results;309}310311export function getCreateItemResult(events: EventRecord[]): CreateItemResult {312  const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));313  314  if (genericResult.data == null) 315    return {316      success: genericResult.success,317      collectionId: 0,318      itemId: 0,319      amount: 0,320    };321  else 322    return {323      success: genericResult.success,324      collectionId: genericResult.data[0] as number,325      itemId: genericResult.data[1] as number,326      recipient: normalizeAccountId(genericResult.data![2] as any),327      amount: genericResult.data[3] as number,328    };329}330331export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {332  const results: DestroyItemResult[] = [];333  334  const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {335    const collectionId = parseInt(data[0].toString(), 10);336    const itemId = parseInt(data[1].toString(), 10);337    const owner = normalizeAccountId(data[2].toJSON() as any);338    const amount = parseInt(data[3].toString(), 10);339340    const itemRes: DestroyItemResult = {341      success: true,342      collectionId,343      itemId,344      owner,345      amount,346    };347348    results.push(itemRes);349    return results;350  });351352  if (!genericResult.success) return [];353  return results;354}355356export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {357  for (const {event} of events) {358    if (api.events.common.Transfer.is(event)) {359      const [collection, token, sender, recipient, value] = event.data;360      return {361        collectionId: collection.toNumber(),362        itemId: token.toNumber(),363        sender: normalizeAccountId(sender.toJSON() as any),364        recipient: normalizeAccountId(recipient.toJSON() as any),365        value: value.toBigInt(),366      };367    }368  }369  throw new Error('no transfer event');370}371372interface Nft {373  type: 'NFT';374}375376interface Fungible {377  type: 'Fungible';378  decimalPoints: number;379}380381interface ReFungible {382  type: 'ReFungible';383}384385export type CollectionMode = Nft | Fungible | ReFungible;386387export type Property = {388  key: any,389  value: any,390};391392type Permission = {393  mutable: boolean;394  collectionAdmin: boolean;395  tokenOwner: boolean;396}397398type PropertyPermission = {399  key: any;400  permission: Permission;401}402403export type CreateCollectionParams = {404  mode: CollectionMode,405  name: string,406  description: string,407  tokenPrefix: string,408  properties?: Array<Property>,409  propPerm?: Array<PropertyPermission>410};411412const defaultCreateCollectionParams: CreateCollectionParams = {413  description: 'description',414  mode: {type: 'NFT'},415  name: 'name',416  tokenPrefix: 'prefix',417};418419export async function420createCollection(421  api: ApiPromise,422  sender: IKeyringPair,423  params: Partial<CreateCollectionParams> = {},424): Promise<CreateCollectionResult> {425  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};426427  let modeprm = {};428  if (mode.type === 'NFT') {429    modeprm = {nft: null};430  } else if (mode.type === 'Fungible') {431    modeprm = {fungible: mode.decimalPoints};432  } else if (mode.type === 'ReFungible') {433    modeprm = {refungible: null};434  }435436  const tx = api.tx.unique.createCollectionEx({437    name: strToUTF16(name),438    description: strToUTF16(description),439    tokenPrefix: strToUTF16(tokenPrefix),440    mode: modeprm as any,441  });442  const events = await submitTransactionAsync(sender, tx);443  return getCreateCollectionResult(events);444}445446export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {447  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};448449  let collectionId = 0;450  await usingApi(async (api, privateKeyWrapper) => {451    // Get number of collections before the transaction452    const collectionCountBefore = await getCreatedCollectionCount(api);453454    // Run the CreateCollection transaction455    const alicePrivateKey = privateKeyWrapper('//Alice');456457    const result = await createCollection(api, alicePrivateKey, params);458459    // Get number of collections after the transaction460    const collectionCountAfter = await getCreatedCollectionCount(api);461462    // Get the collection463    const collection = await queryCollectionExpectSuccess(api, result.collectionId);464465    // What to expect466    // tslint:disable-next-line:no-unused-expression467    expect(result.success).to.be.true;468    expect(result.collectionId).to.be.equal(collectionCountAfter);469    // tslint:disable-next-line:no-unused-expression470    expect(collection).to.be.not.null;471    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');472    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));473    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);474    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);475    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);476477    collectionId = result.collectionId;478  });479480  return collectionId;481}482483export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {484  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};485486  let collectionId = 0;487  await usingApi(async (api, privateKeyWrapper) => {488    // Get number of collections before the transaction489    const collectionCountBefore = await getCreatedCollectionCount(api);490491    // Run the CreateCollection transaction492    const alicePrivateKey = privateKeyWrapper('//Alice');493494    let modeprm = {};495    if (mode.type === 'NFT') {496      modeprm = {nft: null};497    } else if (mode.type === 'Fungible') {498      modeprm = {fungible: mode.decimalPoints};499    } else if (mode.type === 'ReFungible') {500      modeprm = {refungible: null};501    }502503    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});504    const events = await submitTransactionAsync(alicePrivateKey, tx);505    const result = getCreateCollectionResult(events);506507    // Get number of collections after the transaction508    const collectionCountAfter = await getCreatedCollectionCount(api);509510    // Get the collection511    const collection = await queryCollectionExpectSuccess(api, result.collectionId);512513    // What to expect514    // tslint:disable-next-line:no-unused-expression515    expect(result.success).to.be.true;516    expect(result.collectionId).to.be.equal(collectionCountAfter);517    // tslint:disable-next-line:no-unused-expression518    expect(collection).to.be.not.null;519    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');520    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));521    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);522    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);523    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);524525526    collectionId = result.collectionId;527  });528529  return collectionId;530}531532export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {533  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};534535  await usingApi(async (api, privateKeyWrapper) => {536    // Get number of collections before the transaction537    const collectionCountBefore = await getCreatedCollectionCount(api);538539    // Run the CreateCollection transaction540    const alicePrivateKey = privateKeyWrapper('//Alice');541542    let modeprm = {};543    if (mode.type === 'NFT') {544      modeprm = {nft: null};545    } else if (mode.type === 'Fungible') {546      modeprm = {fungible: mode.decimalPoints};547    } else if (mode.type === 'ReFungible') {548      modeprm = {refungible: null};549    }550551    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});552    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;553554555    // Get number of collections after the transaction556    const collectionCountAfter = await getCreatedCollectionCount(api);557558    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');559  });560}561562export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {563  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};564565  let modeprm = {};566  if (mode.type === 'NFT') {567    modeprm = {nft: null};568  } else if (mode.type === 'Fungible') {569    modeprm = {fungible: mode.decimalPoints};570  } else if (mode.type === 'ReFungible') {571    modeprm = {refungible: null};572  }573574  await usingApi(async (api, privateKeyWrapper) => {575    // Get number of collections before the transaction576    const collectionCountBefore = await getCreatedCollectionCount(api);577578    // Run the CreateCollection transaction579    const alicePrivateKey = privateKeyWrapper('//Alice');580    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});581    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;582583    // Get number of collections after the transaction584    const collectionCountAfter = await getCreatedCollectionCount(api);585586    // What to expect587    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');588  });589}590591export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {592  let bal = 0n;593  let unused;594  do {595    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;596    unused = privateKeyWrapper(`//${randomSeed}`);597    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();598  } while (bal !== 0n);599  return unused;600}601602export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {603  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();604}605606export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {607  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));608}609610export async function findNotExistingCollection(api: ApiPromise): Promise<number> {611  const totalNumber = await getCreatedCollectionCount(api);612  const newCollection: number = totalNumber + 1;613  return newCollection;614}615616function getDestroyResult(events: EventRecord[]): boolean {617  let success = false;618  events.forEach(({event: {method}}) => {619    if (method == 'ExtrinsicSuccess') {620      success = true;621    }622  });623  return success;624}625626export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {627  await usingApi(async (api, privateKeyWrapper) => {628    // Run the DestroyCollection transaction629    const alicePrivateKey = privateKeyWrapper(senderSeed);630    const tx = api.tx.unique.destroyCollection(collectionId);631    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;632  });633}634635export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {636  await usingApi(async (api, privateKeyWrapper) => {637    // Run the DestroyCollection transaction638    const alicePrivateKey = privateKeyWrapper(senderSeed);639    const tx = api.tx.unique.destroyCollection(collectionId);640    const events = await submitTransactionAsync(alicePrivateKey, tx);641    const result = getDestroyResult(events);642    expect(result).to.be.true;643644    // What to expect645    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;646  });647}648649export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {650  await usingApi(async (api) => {651    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);652    const events = await submitTransactionAsync(sender, tx);653    const result = getGenericResult(events);654655    expect(result.success).to.be.true;656  });657}658659export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {660  await usingApi(async(api) => {661    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);662    const events = await submitTransactionAsync(sender, tx);663    const result = getGenericResult(events);664665    expect(result.success).to.be.true;666  });667};668669export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {670  await usingApi(async (api) => {671    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);672    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;673    const result = getGenericResult(events);674675    expect(result.success).to.be.false;676  });677}678679export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {680  await usingApi(async (api, privateKeyWrapper) => {681682    // Run the transaction683    const senderPrivateKey = privateKeyWrapper(sender);684    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);685    const events = await submitTransactionAsync(senderPrivateKey, tx);686    const result = getGenericResult(events);687688    // Get the collection689    const collection = await queryCollectionExpectSuccess(api, collectionId);690691    // What to expect692    expect(result.success).to.be.true;693    expect(collection.sponsorship.toJSON()).to.deep.equal({694      unconfirmed: sponsor,695    });696  });697}698699export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {700  await usingApi(async (api, privateKeyWrapper) => {701702    // Run the transaction703    const alicePrivateKey = privateKeyWrapper(sender);704    const tx = api.tx.unique.removeCollectionSponsor(collectionId);705    const events = await submitTransactionAsync(alicePrivateKey, tx);706    const result = getGenericResult(events);707708    // Get the collection709    const collection = await queryCollectionExpectSuccess(api, collectionId);710711    // What to expect712    expect(result.success).to.be.true;713    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});714  });715}716717export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {718  await usingApi(async (api, privateKeyWrapper) => {719720    // Run the transaction721    const alicePrivateKey = privateKeyWrapper(senderSeed);722    const tx = api.tx.unique.removeCollectionSponsor(collectionId);723    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;724  });725}726727export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {728  await usingApi(async (api, privateKeyWrapper) => {729730    // Run the transaction731    const alicePrivateKey = privateKeyWrapper(senderSeed);732    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);733    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;734  });735}736737export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {738  await usingApi(async (api, privateKeyWrapper) => {739740    // Run the transaction741    const sender = privateKeyWrapper(senderSeed);742    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);743  });744}745746export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {747  await usingApi(async (api, privateKeyWrapper) => {748749    // Run the transaction750    const tx = api.tx.unique.confirmSponsorship(collectionId);751    const events = await submitTransactionAsync(sender, tx);752    const result = getGenericResult(events);753754    // Get the collection755    const collection = await queryCollectionExpectSuccess(api, collectionId);756757    // What to expect758    expect(result.success).to.be.true;759    expect(collection.sponsorship.toJSON()).to.be.deep.equal({760      confirmed: sender.address,761    });762  });763}764765766export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {767  await usingApi(async (api, privateKeyWrapper) => {768769    // Run the transaction770    const sender = privateKeyWrapper(senderSeed);771    const tx = api.tx.unique.confirmSponsorship(collectionId);772    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;773  });774}775776export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {777  await usingApi(async (api) => {778    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);779    const events = await submitTransactionAsync(sender, tx);780    const result = getGenericResult(events);781782    expect(result.success).to.be.true;783  });784}785786export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {787  await usingApi(async (api) => {788    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);789    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;790    const result = getGenericResult(events);791792    expect(result.success).to.be.false;793  });794}795796export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {797798  await usingApi(async (api) => {799800    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);801    const events = await submitTransactionAsync(sender, tx);802    const result = getGenericResult(events);803804    expect(result.success).to.be.true;805  });806}807808export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {809810  await usingApi(async (api) => {811812    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);813    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;814    const result = getGenericResult(events);815816    expect(result.success).to.be.false;817  });818}819820export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {821  await usingApi(async (api) => {822    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);823    const events = await submitTransactionAsync(sender, tx);824    const result = getGenericResult(events);825826    expect(result.success).to.be.true;827  });828}829830export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {831  await usingApi(async (api) => {832    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);833    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;834    const result = getGenericResult(events);835836    expect(result.success).to.be.false;837  });838}839840export async function getNextSponsored(841  api: ApiPromise,842  collectionId: number,843  account: string | CrossAccountId,844  tokenId: number,845): Promise<number> {846  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));847}848849export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {850  await usingApi(async (api) => {851    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);852    const events = await submitTransactionAsync(sender, tx);853    const result = getGenericResult(events);854855    expect(result.success).to.be.true;856  });857}858859export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {860  let allowlisted = false;861  await usingApi(async (api) => {862    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;863  });864  return allowlisted;865}866867export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {868  await usingApi(async (api) => {869    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());870    const events = await submitTransactionAsync(sender, tx);871    const result = getGenericResult(events);872873    expect(result.success).to.be.true;874  });875}876877export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {878  await usingApi(async (api) => {879    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());880    const events = await submitTransactionAsync(sender, tx);881    const result = getGenericResult(events);882883    expect(result.success).to.be.true;884  });885}886887export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {888  await usingApi(async (api) => {889    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());890    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;891    const result = getGenericResult(events);892893    expect(result.success).to.be.false;894  });895}896897export interface CreateFungibleData {898  readonly Value: bigint;899}900901export interface CreateReFungibleData { }902export interface CreateNftData { }903904export type CreateItemData = {905  NFT: CreateNftData;906} | {907  Fungible: CreateFungibleData;908} | {909  ReFungible: CreateReFungibleData;910};911912export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {913  const tx = api.tx.unique.burnItem(collectionId, tokenId, value);914  const events = await submitTransactionAsync(sender, tx);915  return getGenericResult(events).success;916}917918export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {919  await usingApi(async (api) => {920    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);921    // if burning token by admin - use adminButnItemExpectSuccess922    expect(balanceBefore >= BigInt(value)).to.be.true;923924    expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;925926    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);927    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);928  });929}930931export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {932  await usingApi(async (api) => {933    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);934935    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;936    const result = getCreateCollectionResult(events);937    // tslint:disable-next-line:no-unused-expression938    expect(result.success).to.be.false;939  });940}941942export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {943  await usingApi(async (api) => {944    const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);945    const events = await submitTransactionAsync(sender, tx);946    return getGenericResult(events).success;947  });948}949950export async function951approve(952  api: ApiPromise,953  collectionId: number,954  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,955) {956  const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);957  const events = await submitTransactionAsync(owner, approveUniqueTx);958  return getGenericResult(events).success;959}960961export async function962approveExpectSuccess(963  collectionId: number,964  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,965) {966  await usingApi(async (api: ApiPromise) => {967    const result = await approve(api, collectionId, tokenId, owner, approved, amount);968    expect(result).to.be.true;969970    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));971  });972}973974export async function adminApproveFromExpectSuccess(975  collectionId: number,976  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,977) {978  await usingApi(async (api: ApiPromise) => {979    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);980    const events = await submitTransactionAsync(admin, approveUniqueTx);981    const result = getGenericResult(events);982    expect(result.success).to.be.true;983984    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));985  });986}987988export async function989transferFrom(990  api: ApiPromise,991  collectionId: number,992  tokenId: number,993  accountApproved: IKeyringPair,994  accountFrom: IKeyringPair | CrossAccountId,995  accountTo: IKeyringPair | CrossAccountId,996  value: number | bigint,997) {998  const from = normalizeAccountId(accountFrom);999  const to = normalizeAccountId(accountTo);1000  const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);1001  const events = await submitTransactionAsync(accountApproved, transferFromTx);1002  return getGenericResult(events).success;1003}10041005export async function1006transferFromExpectSuccess(1007  collectionId: number,1008  tokenId: number,1009  accountApproved: IKeyringPair,1010  accountFrom: IKeyringPair | CrossAccountId,1011  accountTo: IKeyringPair | CrossAccountId,1012  value: number | bigint = 1,1013  type = 'NFT',1014) {1015  await usingApi(async (api: ApiPromise) => {1016    const from = normalizeAccountId(accountFrom);1017    const to = normalizeAccountId(accountTo);1018    let balanceBefore = 0n;1019    if (type === 'Fungible' || type === 'ReFungible') {1020      balanceBefore = await getBalance(api, collectionId, to, tokenId);1021    }1022    expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;1023    if (type === 'NFT') {1024      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1025    }1026    if (type === 'Fungible') {1027      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1028      if (JSON.stringify(to) !== JSON.stringify(from)) {1029        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1030      } else {1031        expect(balanceAfter).to.be.equal(balanceBefore);1032      }1033    }1034    if (type === 'ReFungible') {1035      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1036    }1037  });1038}10391040export async function1041transferFromExpectFail(1042  collectionId: number,1043  tokenId: number,1044  accountApproved: IKeyringPair,1045  accountFrom: IKeyringPair,1046  accountTo: IKeyringPair,1047  value: number | bigint = 1,1048) {1049  await usingApi(async (api: ApiPromise) => {1050    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1051    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1052    const result = getCreateCollectionResult(events);1053    // tslint:disable-next-line:no-unused-expression1054    expect(result.success).to.be.false;1055  });1056}10571058/* eslint no-async-promise-executor: "off" */1059export async function getBlockNumber(api: ApiPromise): Promise<number> {1060  return new Promise<number>(async (resolve) => {1061    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1062      unsubscribe();1063      resolve(head.number.toNumber());1064    });1065  });1066}10671068export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1069  await usingApi(async (api) => {1070    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1071    const events = await submitTransactionAsync(sender, changeAdminTx);1072    const result = getCreateCollectionResult(events);1073    expect(result.success).to.be.true;1074  });1075}10761077export async function adminApproveFromExpectFail(1078  collectionId: number,1079  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1080) {1081  await usingApi(async (api: ApiPromise) => {1082    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1083    const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1084    const result = getGenericResult(events);1085    expect(result.success).to.be.false;1086  });1087}10881089export async function1090getFreeBalance(account: IKeyringPair): Promise<bigint> {1091  let balance = 0n;1092  await usingApi(async (api) => {1093    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1094  });10951096  return balance;1097}10981099export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1100  const tx = api.tx.balances.transfer(target, amount);1101  const events = await submitTransactionAsync(source, tx);1102  const result = getGenericResult(events);1103  expect(result.success).to.be.true;1104}11051106export async function1107scheduleExpectSuccess(1108  operationTx: any,1109  sender: IKeyringPair,1110  blockSchedule: number,1111  scheduledId: string,1112  period = 1,1113  repetitions = 1,1114) {1115  await usingApi(async (api: ApiPromise) => {1116    const blockNumber: number | undefined = await getBlockNumber(api);1117    const expectedBlockNumber = blockNumber + blockSchedule;11181119    expect(blockNumber).to.be.greaterThan(0);1120    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1121      scheduledId,1122      expectedBlockNumber, 1123      repetitions > 1 ? [period, repetitions] : null, 1124      0, 1125      {Value: operationTx as any},1126    );11271128    const events = await submitTransactionAsync(sender, scheduleTx);1129    expect(getGenericResult(events).success).to.be.true;1130  });1131}11321133export async function1134scheduleExpectFailure(1135  operationTx: any,1136  sender: IKeyringPair,1137  blockSchedule: number,1138  scheduledId: string,1139  period = 1,1140  repetitions = 1,1141) {1142  await usingApi(async (api: ApiPromise) => {1143    const blockNumber: number | undefined = await getBlockNumber(api);1144    const expectedBlockNumber = blockNumber + blockSchedule;11451146    expect(blockNumber).to.be.greaterThan(0);1147    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1148      scheduledId,1149      expectedBlockNumber, 1150      repetitions <= 1 ? null : [period, repetitions], 1151      0, 1152      {Value: operationTx as any},1153    );11541155    //const events = 1156    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1157    //expect(getGenericResult(events).success).to.be.false;1158  });1159}11601161export async function1162scheduleTransferAndWaitExpectSuccess(1163  collectionId: number,1164  tokenId: number,1165  sender: IKeyringPair,1166  recipient: IKeyringPair,1167  value: number | bigint = 1,1168  blockSchedule: number,1169  scheduledId: string,1170) {1171  await usingApi(async (api: ApiPromise) => {1172    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);11731174    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();11751176    // sleep for n + 1 blocks1177    await waitNewBlocks(blockSchedule + 1);11781179    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();11801181    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1182    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1183  });1184}11851186export async function1187scheduleTransferExpectSuccess(1188  collectionId: number,1189  tokenId: number,1190  sender: IKeyringPair,1191  recipient: IKeyringPair,1192  value: number | bigint = 1,1193  blockSchedule: number,1194  scheduledId: string,1195) {1196  await usingApi(async (api: ApiPromise) => {1197    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);11981199    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);12001201    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1202  });1203}12041205export async function1206scheduleTransferFundsPeriodicExpectSuccess(1207  amount: bigint,1208  sender: IKeyringPair,1209  recipient: IKeyringPair,1210  blockSchedule: number,1211  scheduledId: string,1212  period: number,1213  repetitions: number,1214) {1215  await usingApi(async (api: ApiPromise) => {1216    const transferTx = api.tx.balances.transfer(recipient.address, amount);12171218    const balanceBefore = await getFreeBalance(recipient);1219    1220    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);12211222    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1223  });1224}12251226export async function1227transfer(1228  api: ApiPromise,1229  collectionId: number,1230  tokenId: number,1231  sender: IKeyringPair,1232  recipient: IKeyringPair | CrossAccountId,1233  value: number | bigint,1234) : Promise<boolean> {1235  const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1236  const events = await executeTransaction(api, sender, transferTx);1237  return getGenericResult(events).success;1238}12391240export async function1241transferExpectSuccess(1242  collectionId: number,1243  tokenId: number,1244  sender: IKeyringPair,1245  recipient: IKeyringPair | CrossAccountId,1246  value: number | bigint = 1,1247  type = 'NFT',1248) {1249  await usingApi(async (api: ApiPromise) => {1250    const from = normalizeAccountId(sender);1251    const to = normalizeAccountId(recipient);12521253    let balanceBefore = 0n;1254    if (type === 'Fungible' || type === 'ReFungible') {1255      balanceBefore = await getBalance(api, collectionId, to, tokenId);1256    }12571258    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1259    const events = await executeTransaction(api, sender, transferTx);1260    const result = getTransferResult(api, events);12611262    expect(result.collectionId).to.be.equal(collectionId);1263    expect(result.itemId).to.be.equal(tokenId);1264    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1265    expect(result.recipient).to.be.deep.equal(to);1266    expect(result.value).to.be.equal(BigInt(value));12671268    if (type === 'NFT') {1269      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1270    }1271    if (type === 'Fungible' || type === 'ReFungible') {1272      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1273      if (JSON.stringify(to) !== JSON.stringify(from)) {1274        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1275      } else {1276        expect(balanceAfter).to.be.equal(balanceBefore);1277      }1278    }1279  });1280}12811282export async function1283transferExpectFailure(1284  collectionId: number,1285  tokenId: number,1286  sender: IKeyringPair,1287  recipient: IKeyringPair | CrossAccountId,1288  value: number | bigint = 1,1289) {1290  await usingApi(async (api: ApiPromise) => {1291    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1292    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1293    const result = getGenericResult(events);1294    // if (events && Array.isArray(events)) {1295    //   const result = getCreateCollectionResult(events);1296    // tslint:disable-next-line:no-unused-expression1297    expect(result.success).to.be.false;1298    //}1299  });1300}13011302export async function1303approveExpectFail(1304  collectionId: number,1305  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1306) {1307  await usingApi(async (api: ApiPromise) => {1308    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1309    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1310    const result = getCreateCollectionResult(events);1311    // tslint:disable-next-line:no-unused-expression1312    expect(result.success).to.be.false;1313  });1314}13151316export async function getBalance(1317  api: ApiPromise,1318  collectionId: number,1319  owner: string | CrossAccountId | IKeyringPair,1320  token: number,1321): Promise<bigint> {1322  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1323}1324export async function getTokenOwner(1325  api: ApiPromise,1326  collectionId: number,1327  token: number,1328): Promise<CrossAccountId> {1329  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1330  if (owner == null) throw new Error('owner == null');1331  return normalizeAccountId(owner);1332}1333export async function getTopmostTokenOwner(1334  api: ApiPromise,1335  collectionId: number,1336  token: number,1337): Promise<CrossAccountId> {1338  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1339  if (owner == null) throw new Error('owner == null');1340  return normalizeAccountId(owner);1341}1342export async function getTokenChildren(1343  api: ApiPromise,1344  collectionId: number,1345  tokenId: number,1346): Promise<UpDataStructsTokenChild[]> {1347  return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1348}1349export async function isTokenExists(1350  api: ApiPromise,1351  collectionId: number,1352  token: number,1353): Promise<boolean> {1354  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1355}1356export async function getLastTokenId(1357  api: ApiPromise,1358  collectionId: number,1359): Promise<number> {1360  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1361}1362export async function getAdminList(1363  api: ApiPromise,1364  collectionId: number,1365): Promise<string[]> {1366  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1367}1368export async function getTokenProperties(1369  api: ApiPromise,1370  collectionId: number,1371  tokenId: number,1372  propertyKeys: string[],1373): Promise<UpDataStructsProperty[]> {1374  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1375}13761377export async function createFungibleItemExpectSuccess(1378  sender: IKeyringPair,1379  collectionId: number,1380  data: CreateFungibleData,1381  owner: CrossAccountId | string = sender.address,1382) {1383  return await usingApi(async (api) => {1384    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});13851386    const events = await submitTransactionAsync(sender, tx);1387    const result = getCreateItemResult(events);13881389    expect(result.success).to.be.true;1390    return result.itemId;1391  });1392}13931394export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1395  await usingApi(async (api) => {1396    const to = normalizeAccountId(owner);1397    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);13981399    const events = await submitTransactionAsync(sender, tx);1400    expect(getGenericResult(events).success).to.be.true;1401  });1402}14031404export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1405  await usingApi(async (api) => {1406    const to = normalizeAccountId(owner);1407    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14081409    const events = await submitTransactionAsync(sender, tx);1410    const result = getCreateItemsResult(events);14111412    for (const res of result) {1413      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1414    }1415  });1416}14171418export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1419  await usingApi(async (api) => {1420    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);14211422    const events = await submitTransactionAsync(sender, tx);1423    const result = getCreateItemsResult(events);14241425    for (const res of result) {1426      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1427    }1428  });1429}14301431export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1432  let newItemId = 0;1433  await usingApi(async (api) => {1434    const to = normalizeAccountId(owner);1435    const itemCountBefore = await getLastTokenId(api, collectionId);1436    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14371438    let tx;1439    if (createMode === 'Fungible') {1440      const createData = {fungible: {value: 10}};1441      tx = api.tx.unique.createItem(collectionId, to, createData as any);1442    } else if (createMode === 'ReFungible') {1443      const createData = {refungible: {pieces: 100}};1444      tx = api.tx.unique.createItem(collectionId, to, createData as any);1445    } else {1446      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1447      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1448    }14491450    const events = await submitTransactionAsync(sender, tx);1451    const result = getCreateItemResult(events);14521453    const itemCountAfter = await getLastTokenId(api, collectionId);1454    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14551456    if (createMode === 'NFT') {1457      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1458    }14591460    // What to expect1461    // tslint:disable-next-line:no-unused-expression1462    expect(result.success).to.be.true;1463    if (createMode === 'Fungible') {1464      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1465    } else {1466      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1467    }1468    expect(collectionId).to.be.equal(result.collectionId);1469    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1470    expect(to).to.be.deep.equal(result.recipient);1471    newItemId = result.itemId;1472  });1473  return newItemId;1474}14751476export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1477  await usingApi(async (api) => {14781479    let tx;1480    if (createMode === 'NFT') {1481      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1482      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1483    } else {1484      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1485    }148614871488    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1489    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1490    const result = getCreateItemResult(events);14911492    expect(result.success).to.be.false;1493  });1494}14951496export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1497  let newItemId = 0;1498  await usingApi(async (api) => {1499    const to = normalizeAccountId(owner);1500    const itemCountBefore = await getLastTokenId(api, collectionId);1501    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);15021503    let tx;1504    if (createMode === 'Fungible') {1505      const createData = {fungible: {value: 10}};1506      tx = api.tx.unique.createItem(collectionId, to, createData as any);1507    } else if (createMode === 'ReFungible') {1508      const createData = {refungible: {pieces: 100}};1509      tx = api.tx.unique.createItem(collectionId, to, createData as any);1510    } else {1511      const createData = {nft: {}};1512      tx = api.tx.unique.createItem(collectionId, to, createData as any);1513    }15141515    const events = await executeTransaction(api, sender, tx);1516    const result = getCreateItemResult(events);15171518    const itemCountAfter = await getLastTokenId(api, collectionId);1519    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15201521    // What to expect1522    // tslint:disable-next-line:no-unused-expression1523    expect(result.success).to.be.true;1524    if (createMode === 'Fungible') {1525      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1526    } else {1527      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1528    }1529    expect(collectionId).to.be.equal(result.collectionId);1530    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1531    expect(to).to.be.deep.equal(result.recipient);1532    newItemId = result.itemId;1533  });1534  return newItemId;1535}15361537export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1538  const createData = {refungible: {pieces: amount}};1539  const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15401541  const events = await submitTransactionAsync(sender, tx);1542  return  getCreateItemResult(events);1543}15441545export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1546  await usingApi(async (api) => {1547    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15481549    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1550    const result = getCreateItemResult(events);15511552    expect(result.success).to.be.false;1553  });1554}15551556export async function setPublicAccessModeExpectSuccess(1557  sender: IKeyringPair, collectionId: number,1558  accessMode: 'Normal' | 'AllowList',1559) {1560  await usingApi(async (api) => {15611562    // Run the transaction1563    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1564    const events = await submitTransactionAsync(sender, tx);1565    const result = getGenericResult(events);15661567    // Get the collection1568    const collection = await queryCollectionExpectSuccess(api, collectionId);15691570    // What to expect1571    // tslint:disable-next-line:no-unused-expression1572    expect(result.success).to.be.true;1573    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1574  });1575}15761577export async function setPublicAccessModeExpectFail(1578  sender: IKeyringPair, collectionId: number,1579  accessMode: 'Normal' | 'AllowList',1580) {1581  await usingApi(async (api) => {15821583    // Run the transaction1584    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1585    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1586    const result = getGenericResult(events);15871588    // What to expect1589    // tslint:disable-next-line:no-unused-expression1590    expect(result.success).to.be.false;1591  });1592}15931594export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1595  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1596}15971598export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1599  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1600}16011602export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1603  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1604}16051606export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1607  await usingApi(async (api) => {16081609    // Run the transaction1610    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1611    const events = await submitTransactionAsync(sender, tx);1612    const result = getGenericResult(events);1613    expect(result.success).to.be.true;16141615    // Get the collection1616    const collection = await queryCollectionExpectSuccess(api, collectionId);16171618    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1619  });1620}16211622export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1623  await setMintPermissionExpectSuccess(sender, collectionId, true);1624}16251626export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1627  await usingApi(async (api) => {1628    // Run the transaction1629    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1630    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1631    const result = getCreateCollectionResult(events);1632    // tslint:disable-next-line:no-unused-expression1633    expect(result.success).to.be.false;1634  });1635}16361637export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1638  await usingApi(async (api) => {1639    // Run the transaction1640    const tx = api.tx.unique.setChainLimits(limits);1641    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1642    const result = getCreateCollectionResult(events);1643    // tslint:disable-next-line:no-unused-expression1644    expect(result.success).to.be.false;1645  });1646}16471648export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1649  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1650}16511652export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1653  await usingApi(async (api) => {1654    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16551656    // Run the transaction1657    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1658    const events = await submitTransactionAsync(sender, tx);1659    const result = getGenericResult(events);1660    expect(result.success).to.be.true;16611662    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1663  });1664}16651666export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1667  await usingApi(async (api) => {16681669    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;16701671    // Run the transaction1672    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1673    const events = await submitTransactionAsync(sender, tx);1674    const result = getGenericResult(events);1675    expect(result.success).to.be.true;16761677    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1678  });1679}16801681export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1682  await usingApi(async (api) => {16831684    // Run the transaction1685    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1686    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1687    const result = getGenericResult(events);16881689    // What to expect1690    // tslint:disable-next-line:no-unused-expression1691    expect(result.success).to.be.false;1692  });1693}16941695export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1696  await usingApi(async (api) => {1697    // Run the transaction1698    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1699    const events = await submitTransactionAsync(sender, tx);1700    const result = getGenericResult(events);17011702    // What to expect1703    // tslint:disable-next-line:no-unused-expression1704    expect(result.success).to.be.true;1705  });1706}17071708export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1709  await usingApi(async (api) => {1710    // Run the transaction1711    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1712    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1713    const result = getGenericResult(events);17141715    // What to expect1716    // tslint:disable-next-line:no-unused-expression1717    expect(result.success).to.be.false;1718  });1719}17201721export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1722  : Promise<UpDataStructsRpcCollection | null> => {1723  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1724};17251726export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1727  // set global object - collectionsCount1728  return (await api.rpc.unique.collectionStats()).created.toNumber();1729};17301731export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1732  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1733}17341735export async function waitNewBlocks(blocksCount = 1): Promise<void> {1736  await usingApi(async (api) => {1737    const promise = new Promise<void>(async (resolve) => {1738      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1739        if (blocksCount > 0) {1740          blocksCount--;1741        } else {1742          unsubscribe();1743          resolve();1744        }1745      });1746    });1747    return promise;1748  });1749}17501751export async function repartitionRFT(1752  api: ApiPromise,1753  collectionId: number,1754  sender: IKeyringPair,1755  tokenId: number,1756  amount: bigint,1757): Promise<boolean> {1758  const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1759  const events = await submitTransactionAsync(sender, tx);1760  const result = getGenericResult(events);17611762  return result.success;1763}17641765export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1766  let i: any = it;1767  if (opts.only) i = i.only;1768  else if (opts.skip) i = i.skip;1769  i(name, async () => {1770    await usingApi(async (api, privateKeyWrapper) => {1771      await cb({api, privateKeyWrapper});1772    });1773  });1774}17751776itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1777itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});