git.delta.rocks / unique-network / refs/commits / 503028ebb65c

difftreelog

test(xcm) qtz/unq rejects relay tokens

Daniel Shiposha2022-09-06parent: #6c9f876.patch.diff
in: master

3 files 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, Keyring} 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.error('\x1b[38:5:208m%s\x1b[0m', skipMsg);9798    mocha.skip();99  }100}101102export function bigIntToSub(api: ApiPromise, number: bigint) {103  return api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();104}105106export function bigIntToDecimals(number: bigint, decimals = 18): string {107  let numberStr = number.toString();108  console.log('[0] str = ', numberStr);109110  // Get rid of `n` at the end111  numberStr = numberStr.substring(0, numberStr.length - 1);112  console.log('[1] str = ', numberStr);113114  const dotPos = numberStr.length - decimals;115  if (dotPos <= 0) {116    return '0.' + numberStr;117  } else {118    const intPart = numberStr.substring(0, dotPos);119    const fractPart = numberStr.substring(dotPos);120    return intPart + '.' + fractPart;121  }122}123124export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {125  if (typeof input === 'string') {126    if (input.length >= 47) {127      return {Substrate: input};128    } else if (input.length === 42 && input.startsWith('0x')) {129      return {Ethereum: input.toLowerCase()};130    } else if (input.length === 40 && !input.startsWith('0x')) {131      return {Ethereum: '0x' + input.toLowerCase()};132    } else {133      throw new Error(`Unknown address format: "${input}"`);134    }135  }136  if ('address' in input) {137    return {Substrate: input.address};138  }139  if ('Ethereum' in input) {140    return {141      Ethereum: input.Ethereum.toLowerCase(),142    };143  } else if ('ethereum' in input) {144    return {145      Ethereum: (input as any).ethereum.toLowerCase(),146    };147  } else if ('Substrate' in input) {148    return input;149  } else if ('substrate' in input) {150    return {151      Substrate: (input as any).substrate,152    };153  }154155  // AccountId156  return {Substrate: input.toString()};157}158export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {159  input = normalizeAccountId(input);160  if ('Substrate' in input) {161    return input.Substrate;162  } else {163    return evmToAddress(input.Ethereum);164  }165}166167export const U128_MAX = (1n << 128n) - 1n;168169const MICROUNIQUE = 1_000_000_000_000n;170const MILLIUNIQUE = 1_000n * MICROUNIQUE;171const CENTIUNIQUE = 10n * MILLIUNIQUE;172export const UNIQUE = 100n * CENTIUNIQUE;173174interface GenericResult<T> {175  success: boolean;176  data: T | null;177}178179interface CreateCollectionResult {180  success: boolean;181  collectionId: number;182}183184interface CreateItemResult {185  success: boolean;186  collectionId: number;187  itemId: number;188  recipient?: CrossAccountId;189  amount?: number;190}191192interface DestroyItemResult {193  success: boolean;194  collectionId: number;195  itemId: number;196  owner: CrossAccountId;197  amount: number;198}199200interface TransferResult {201  collectionId: number;202  itemId: number;203  sender?: CrossAccountId;204  recipient?: CrossAccountId;205  value: bigint;206}207208interface IReFungibleOwner {209  fraction: BN;210  owner: number[];211}212213interface IGetMessage {214  checkMsgUnqMethod: string;215  checkMsgTrsMethod: string;216  checkMsgSysMethod: string;217}218219export interface IFungibleTokenDataType {220  value: number;221}222223export interface IChainLimits {224  collectionNumbersLimit: number;225  accountTokenOwnershipLimit: number;226  collectionsAdminsLimit: number;227  customDataLimit: number;228  nftSponsorTransferTimeout: number;229  fungibleSponsorTransferTimeout: number;230  refungibleSponsorTransferTimeout: number;231  //offchainSchemaLimit: number;232  //constOnChainSchemaLimit: number;233}234235export interface IReFungibleTokenDataType {236  owner: IReFungibleOwner[];237}238239export function uniqueEventMessage(events: EventRecord[]): IGetMessage {240  let checkMsgUnqMethod = '';241  let checkMsgTrsMethod = '';242  let checkMsgSysMethod = '';243  events.forEach(({event: {method, section}}) => {244    if (section === 'common') {245      checkMsgUnqMethod = method;246    } else if (section === 'treasury') {247      checkMsgTrsMethod = method;248    } else if (section === 'system') {249      checkMsgSysMethod = method;250    } else { return null; }251  });252  const result: IGetMessage = {253    checkMsgUnqMethod,254    checkMsgTrsMethod,255    checkMsgSysMethod,256  };257  return result;258}259260export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {261  const event = events.find(r => check(r.event));262  if (!event) return;263  return event.event as T;264}265266export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;267export function getGenericResult<T>(268  events: EventRecord[],269  expectSection: string,270  expectMethod: string,271  extractAction: (data: GenericEventData) => T272): GenericResult<T>;273274export function getGenericResult<T>(275  events: EventRecord[],276  expectSection?: string,277  expectMethod?: string,278  extractAction?: (data: GenericEventData) => T,279): GenericResult<T> {280  let success = false;281  let successData = null;282283  events.forEach(({event: {data, method, section}}) => {284    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);285    if (method === 'ExtrinsicSuccess') {286      success = true;287    } else if ((expectSection == section) && (expectMethod == method)) {288      successData = extractAction!(data as any);289    }290  });291292  const result: GenericResult<T> = {293    success,294    data: successData,295  };296  return result;297}298299export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {300  const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));301  const result: CreateCollectionResult = {302    success: genericResult.success,303    collectionId: genericResult.data ?? 0,304  };305  return result;306}307308export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {309  const results: CreateItemResult[] = [];310  311  const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {312    const collectionId = parseInt(data[0].toString(), 10);313    const itemId = parseInt(data[1].toString(), 10);314    const recipient = normalizeAccountId(data[2].toJSON() as any);315    const amount = parseInt(data[3].toString(), 10);316317    const itemRes: CreateItemResult = {318      success: true,319      collectionId,320      itemId,321      recipient,322      amount,323    };324325    results.push(itemRes);326    return results;327  });328329  if (!genericResult.success) return [];330  return results;331}332333export function getCreateItemResult(events: EventRecord[]): CreateItemResult {334  const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));335  336  if (genericResult.data == null) 337    return {338      success: genericResult.success,339      collectionId: 0,340      itemId: 0,341      amount: 0,342    };343  else 344    return {345      success: genericResult.success,346      collectionId: genericResult.data[0] as number,347      itemId: genericResult.data[1] as number,348      recipient: normalizeAccountId(genericResult.data![2] as any),349      amount: genericResult.data[3] as number,350    };351}352353export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {354  const results: DestroyItemResult[] = [];355  356  const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {357    const collectionId = parseInt(data[0].toString(), 10);358    const itemId = parseInt(data[1].toString(), 10);359    const owner = normalizeAccountId(data[2].toJSON() as any);360    const amount = parseInt(data[3].toString(), 10);361362    const itemRes: DestroyItemResult = {363      success: true,364      collectionId,365      itemId,366      owner,367      amount,368    };369370    results.push(itemRes);371    return results;372  });373374  if (!genericResult.success) return [];375  return results;376}377378export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {379  for (const {event} of events) {380    if (api.events.common.Transfer.is(event)) {381      const [collection, token, sender, recipient, value] = event.data;382      return {383        collectionId: collection.toNumber(),384        itemId: token.toNumber(),385        sender: normalizeAccountId(sender.toJSON() as any),386        recipient: normalizeAccountId(recipient.toJSON() as any),387        value: value.toBigInt(),388      };389    }390  }391  throw new Error('no transfer event');392}393394interface Nft {395  type: 'NFT';396}397398interface Fungible {399  type: 'Fungible';400  decimalPoints: number;401}402403interface ReFungible {404  type: 'ReFungible';405}406407export type CollectionMode = Nft | Fungible | ReFungible;408409export type Property = {410  key: any,411  value: any,412};413414type Permission = {415  mutable: boolean;416  collectionAdmin: boolean;417  tokenOwner: boolean;418}419420type PropertyPermission = {421  key: any;422  permission: Permission;423}424425export type CreateCollectionParams = {426  mode: CollectionMode,427  name: string,428  description: string,429  tokenPrefix: string,430  properties?: Array<Property>,431  propPerm?: Array<PropertyPermission>432};433434const defaultCreateCollectionParams: CreateCollectionParams = {435  description: 'description',436  mode: {type: 'NFT'},437  name: 'name',438  tokenPrefix: 'prefix',439};440441export async function442createCollection(443  api: ApiPromise,444  sender: IKeyringPair,445  params: Partial<CreateCollectionParams> = {},446): Promise<CreateCollectionResult> {447  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};448449  let modeprm = {};450  if (mode.type === 'NFT') {451    modeprm = {nft: null};452  } else if (mode.type === 'Fungible') {453    modeprm = {fungible: mode.decimalPoints};454  } else if (mode.type === 'ReFungible') {455    modeprm = {refungible: null};456  }457458  const tx = api.tx.unique.createCollectionEx({459    name: strToUTF16(name),460    description: strToUTF16(description),461    tokenPrefix: strToUTF16(tokenPrefix),462    mode: modeprm as any,463  });464  const events = await executeTransaction(api, sender, tx);465  return getCreateCollectionResult(events);466}467468export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {469  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};470471  let collectionId = 0;472  await usingApi(async (api, privateKeyWrapper) => {473    // Get number of collections before the transaction474    const collectionCountBefore = await getCreatedCollectionCount(api);475476    // Run the CreateCollection transaction477    const alicePrivateKey = privateKeyWrapper('//Alice');478479    const result = await createCollection(api, alicePrivateKey, params);480481    // Get number of collections after the transaction482    const collectionCountAfter = await getCreatedCollectionCount(api);483484    // Get the collection485    const collection = await queryCollectionExpectSuccess(api, result.collectionId);486487    // What to expect488    // tslint:disable-next-line:no-unused-expression489    expect(result.success).to.be.true;490    expect(result.collectionId).to.be.equal(collectionCountAfter);491    // tslint:disable-next-line:no-unused-expression492    expect(collection).to.be.not.null;493    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');494    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));495    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);496    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);497    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);498499    collectionId = result.collectionId;500  });501502  return collectionId;503}504505export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {506  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};507508  let collectionId = 0;509  await usingApi(async (api, privateKeyWrapper) => {510    // Get number of collections before the transaction511    const collectionCountBefore = await getCreatedCollectionCount(api);512513    // Run the CreateCollection transaction514    const alicePrivateKey = privateKeyWrapper('//Alice');515516    let modeprm = {};517    if (mode.type === 'NFT') {518      modeprm = {nft: null};519    } else if (mode.type === 'Fungible') {520      modeprm = {fungible: mode.decimalPoints};521    } else if (mode.type === 'ReFungible') {522      modeprm = {refungible: null};523    }524525    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});526    const events = await submitTransactionAsync(alicePrivateKey, tx);527    const result = getCreateCollectionResult(events);528529    // Get number of collections after the transaction530    const collectionCountAfter = await getCreatedCollectionCount(api);531532    // Get the collection533    const collection = await queryCollectionExpectSuccess(api, result.collectionId);534535    // What to expect536    // tslint:disable-next-line:no-unused-expression537    expect(result.success).to.be.true;538    expect(result.collectionId).to.be.equal(collectionCountAfter);539    // tslint:disable-next-line:no-unused-expression540    expect(collection).to.be.not.null;541    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');542    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));543    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);544    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);545    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);546547548    collectionId = result.collectionId;549  });550551  return collectionId;552}553554export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {555  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};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');563564    let modeprm = {};565    if (mode.type === 'NFT') {566      modeprm = {nft: null};567    } else if (mode.type === 'Fungible') {568      modeprm = {fungible: mode.decimalPoints};569    } else if (mode.type === 'ReFungible') {570      modeprm = {refungible: null};571    }572573    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});574    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;575576577    // Get number of collections after the transaction578    const collectionCountAfter = await getCreatedCollectionCount(api);579580    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');581  });582}583584export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {585  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};586587  let modeprm = {};588  if (mode.type === 'NFT') {589    modeprm = {nft: null};590  } else if (mode.type === 'Fungible') {591    modeprm = {fungible: mode.decimalPoints};592  } else if (mode.type === 'ReFungible') {593    modeprm = {refungible: null};594  }595596  await usingApi(async (api, privateKeyWrapper) => {597    // Get number of collections before the transaction598    const collectionCountBefore = await getCreatedCollectionCount(api);599600    // Run the CreateCollection transaction601    const alicePrivateKey = privateKeyWrapper('//Alice');602    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});603    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;604605    // Get number of collections after the transaction606    const collectionCountAfter = await getCreatedCollectionCount(api);607608    // What to expect609    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');610  });611}612613export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {614  let bal = 0n;615  let unused;616  do {617    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;618    unused = privateKeyWrapper(`//${randomSeed}`);619    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();620  } while (bal !== 0n);621  return unused;622}623624export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {625  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();626}627628export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {629  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));630}631632export async function findNotExistingCollection(api: ApiPromise): Promise<number> {633  const totalNumber = await getCreatedCollectionCount(api);634  const newCollection: number = totalNumber + 1;635  return newCollection;636}637638function getDestroyResult(events: EventRecord[]): boolean {639  let success = false;640  events.forEach(({event: {method}}) => {641    if (method == 'ExtrinsicSuccess') {642      success = true;643    }644  });645  return success;646}647648export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {649  await usingApi(async (api, privateKeyWrapper) => {650    // Run the DestroyCollection transaction651    const alicePrivateKey = privateKeyWrapper(senderSeed);652    const tx = api.tx.unique.destroyCollection(collectionId);653    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;654  });655}656657export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {658  await usingApi(async (api, privateKeyWrapper) => {659    // Run the DestroyCollection transaction660    const alicePrivateKey = privateKeyWrapper(senderSeed);661    const tx = api.tx.unique.destroyCollection(collectionId);662    const events = await submitTransactionAsync(alicePrivateKey, tx);663    const result = getDestroyResult(events);664    expect(result).to.be.true;665666    // What to expect667    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;668  });669}670671export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {672  await usingApi(async (api) => {673    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);674    const events = await submitTransactionAsync(sender, tx);675    const result = getGenericResult(events);676677    expect(result.success).to.be.true;678  });679}680681export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {682  await usingApi(async(api) => {683    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);684    const events = await submitTransactionAsync(sender, tx);685    const result = getGenericResult(events);686687    expect(result.success).to.be.true;688  });689};690691export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {692  await usingApi(async (api) => {693    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);694    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;695    const result = getGenericResult(events);696697    expect(result.success).to.be.false;698  });699}700701export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {702  await usingApi(async (api, privateKeyWrapper) => {703704    // Run the transaction705    const senderPrivateKey = privateKeyWrapper(sender);706    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);707    const events = await submitTransactionAsync(senderPrivateKey, tx);708    const result = getGenericResult(events);709710    // Get the collection711    const collection = await queryCollectionExpectSuccess(api, collectionId);712713    // What to expect714    expect(result.success).to.be.true;715    expect(collection.sponsorship.toJSON()).to.deep.equal({716      unconfirmed: sponsor,717    });718  });719}720721export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {722  await usingApi(async (api, privateKeyWrapper) => {723724    // Run the transaction725    const alicePrivateKey = privateKeyWrapper(sender);726    const tx = api.tx.unique.removeCollectionSponsor(collectionId);727    const events = await submitTransactionAsync(alicePrivateKey, tx);728    const result = getGenericResult(events);729730    // Get the collection731    const collection = await queryCollectionExpectSuccess(api, collectionId);732733    // What to expect734    expect(result.success).to.be.true;735    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});736  });737}738739export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {740  await usingApi(async (api, privateKeyWrapper) => {741742    // Run the transaction743    const alicePrivateKey = privateKeyWrapper(senderSeed);744    const tx = api.tx.unique.removeCollectionSponsor(collectionId);745    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;746  });747}748749export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {750  await usingApi(async (api, privateKeyWrapper) => {751752    // Run the transaction753    const alicePrivateKey = privateKeyWrapper(senderSeed);754    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);755    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;756  });757}758759export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {760  await usingApi(async (api, privateKeyWrapper) => {761762    // Run the transaction763    const sender = privateKeyWrapper(senderSeed);764    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);765  });766}767768export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {769  await usingApi(async (api, privateKeyWrapper) => {770771    // Run the transaction772    const tx = api.tx.unique.confirmSponsorship(collectionId);773    const events = await submitTransactionAsync(sender, tx);774    const result = getGenericResult(events);775776    // Get the collection777    const collection = await queryCollectionExpectSuccess(api, collectionId);778779    // What to expect780    expect(result.success).to.be.true;781    expect(collection.sponsorship.toJSON()).to.be.deep.equal({782      confirmed: sender.address,783    });784  });785}786787788export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {789  await usingApi(async (api, privateKeyWrapper) => {790791    // Run the transaction792    const sender = privateKeyWrapper(senderSeed);793    const tx = api.tx.unique.confirmSponsorship(collectionId);794    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;795  });796}797798export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {799  await usingApi(async (api) => {800    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);801    const events = await submitTransactionAsync(sender, tx);802    const result = getGenericResult(events);803804    expect(result.success).to.be.true;805  });806}807808export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {809  await usingApi(async (api) => {810    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);811    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;812    const result = getGenericResult(events);813814    expect(result.success).to.be.false;815  });816}817818export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {819820  await usingApi(async (api) => {821822    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);823    const events = await submitTransactionAsync(sender, tx);824    const result = getGenericResult(events);825826    expect(result.success).to.be.true;827  });828}829830export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {831832  await usingApi(async (api) => {833834    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);835    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;836    const result = getGenericResult(events);837838    expect(result.success).to.be.false;839  });840}841842export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {843  await usingApi(async (api) => {844    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);845    const events = await submitTransactionAsync(sender, tx);846    const result = getGenericResult(events);847848    expect(result.success).to.be.true;849  });850}851852export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {853  await usingApi(async (api) => {854    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);855    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;856    const result = getGenericResult(events);857858    expect(result.success).to.be.false;859  });860}861862export async function getNextSponsored(863  api: ApiPromise,864  collectionId: number,865  account: string | CrossAccountId,866  tokenId: number,867): Promise<number> {868  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));869}870871export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {872  await usingApi(async (api) => {873    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);874    const events = await submitTransactionAsync(sender, tx);875    const result = getGenericResult(events);876877    expect(result.success).to.be.true;878  });879}880881export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {882  let allowlisted = false;883  await usingApi(async (api) => {884    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;885  });886  return allowlisted;887}888889export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {890  await usingApi(async (api) => {891    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());892    const events = await submitTransactionAsync(sender, tx);893    const result = getGenericResult(events);894895    expect(result.success).to.be.true;896  });897}898899export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {900  await usingApi(async (api) => {901    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());902    const events = await submitTransactionAsync(sender, tx);903    const result = getGenericResult(events);904905    expect(result.success).to.be.true;906  });907}908909export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {910  await usingApi(async (api) => {911    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());912    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;913    const result = getGenericResult(events);914915    expect(result.success).to.be.false;916  });917}918919export interface CreateFungibleData {920  readonly Value: bigint;921}922923export interface CreateReFungibleData { }924export interface CreateNftData { }925926export type CreateItemData = {927  NFT: CreateNftData;928} | {929  Fungible: CreateFungibleData;930} | {931  ReFungible: CreateReFungibleData;932};933934export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {935  const tx = api.tx.unique.burnItem(collectionId, tokenId, value);936  const events = await submitTransactionAsync(sender, tx);937  return getGenericResult(events).success;938}939940export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {941  await usingApi(async (api) => {942    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);943    // if burning token by admin - use adminButnItemExpectSuccess944    expect(balanceBefore >= BigInt(value)).to.be.true;945946    expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;947948    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);949    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);950  });951}952953export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {954  await usingApi(async (api) => {955    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);956957    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;958    const result = getCreateCollectionResult(events);959    // tslint:disable-next-line:no-unused-expression960    expect(result.success).to.be.false;961  });962}963964export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {965  await usingApi(async (api) => {966    const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);967    const events = await submitTransactionAsync(sender, tx);968    return getGenericResult(events).success;969  });970}971972export async function973approve(974  api: ApiPromise,975  collectionId: number,976  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,977) {978  const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);979  const events = await submitTransactionAsync(owner, approveUniqueTx);980  return getGenericResult(events).success;981}982983export async function984approveExpectSuccess(985  collectionId: number,986  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,987) {988  await usingApi(async (api: ApiPromise) => {989    const result = await approve(api, collectionId, tokenId, owner, approved, amount);990    expect(result).to.be.true;991992    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));993  });994}995996export async function adminApproveFromExpectSuccess(997  collectionId: number,998  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,999) {1000  await usingApi(async (api: ApiPromise) => {1001    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1002    const events = await submitTransactionAsync(admin, approveUniqueTx);1003    const result = getGenericResult(events);1004    expect(result.success).to.be.true;10051006    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));1007  });1008}10091010export async function1011transferFrom(1012  api: ApiPromise,1013  collectionId: number,1014  tokenId: number,1015  accountApproved: IKeyringPair,1016  accountFrom: IKeyringPair | CrossAccountId,1017  accountTo: IKeyringPair | CrossAccountId,1018  value: number | bigint,1019) {1020  const from = normalizeAccountId(accountFrom);1021  const to = normalizeAccountId(accountTo);1022  const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);1023  const events = await submitTransactionAsync(accountApproved, transferFromTx);1024  return getGenericResult(events).success;1025}10261027export async function1028transferFromExpectSuccess(1029  collectionId: number,1030  tokenId: number,1031  accountApproved: IKeyringPair,1032  accountFrom: IKeyringPair | CrossAccountId,1033  accountTo: IKeyringPair | CrossAccountId,1034  value: number | bigint = 1,1035  type = 'NFT',1036) {1037  await usingApi(async (api: ApiPromise) => {1038    const from = normalizeAccountId(accountFrom);1039    const to = normalizeAccountId(accountTo);1040    let balanceBefore = 0n;1041    if (type === 'Fungible' || type === 'ReFungible') {1042      balanceBefore = await getBalance(api, collectionId, to, tokenId);1043    }1044    expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;1045    if (type === 'NFT') {1046      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1047    }1048    if (type === 'Fungible') {1049      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1050      if (JSON.stringify(to) !== JSON.stringify(from)) {1051        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1052      } else {1053        expect(balanceAfter).to.be.equal(balanceBefore);1054      }1055    }1056    if (type === 'ReFungible') {1057      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1058    }1059  });1060}10611062export async function1063transferFromExpectFail(1064  collectionId: number,1065  tokenId: number,1066  accountApproved: IKeyringPair,1067  accountFrom: IKeyringPair,1068  accountTo: IKeyringPair,1069  value: number | bigint = 1,1070) {1071  await usingApi(async (api: ApiPromise) => {1072    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1073    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1074    const result = getCreateCollectionResult(events);1075    // tslint:disable-next-line:no-unused-expression1076    expect(result.success).to.be.false;1077  });1078}10791080/* eslint no-async-promise-executor: "off" */1081export async function getBlockNumber(api: ApiPromise): Promise<number> {1082  return new Promise<number>(async (resolve) => {1083    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1084      unsubscribe();1085      resolve(head.number.toNumber());1086    });1087  });1088}10891090export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1091  await usingApi(async (api) => {1092    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1093    const events = await submitTransactionAsync(sender, changeAdminTx);1094    const result = getCreateCollectionResult(events);1095    expect(result.success).to.be.true;1096  });1097}10981099export async function adminApproveFromExpectFail(1100  collectionId: number,1101  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1102) {1103  await usingApi(async (api: ApiPromise) => {1104    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1105    const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1106    const result = getGenericResult(events);1107    expect(result.success).to.be.false;1108  });1109}11101111export async function1112getFreeBalance(account: IKeyringPair): Promise<bigint> {1113  let balance = 0n;1114  await usingApi(async (api) => {1115    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1116  });11171118  return balance;1119}11201121export async function paraSiblingSovereignAccount(paraid: number): Promise<string> {1122  return usingApi(async api => {1123    const siblingPrefix = '0x7369626c';1124    const encodedParaId = api.createType('u32', paraid).toHex(true).substring(2);1125    const suffix = '000000000000000000000000000000000000000000000000';11261127    return siblingPrefix + encodedParaId + suffix;1128  });1129}11301131export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1132  const tx = api.tx.balances.transfer(target, amount);1133  const events = await submitTransactionAsync(source, tx);1134  const result = getGenericResult(events);1135  expect(result.success).to.be.true;1136}11371138export async function1139scheduleExpectSuccess(1140  operationTx: any,1141  sender: IKeyringPair,1142  blockSchedule: number,1143  scheduledId: string,1144  period = 1,1145  repetitions = 1,1146) {1147  await usingApi(async (api: ApiPromise) => {1148    const blockNumber: number | undefined = await getBlockNumber(api);1149    const expectedBlockNumber = blockNumber + blockSchedule;11501151    expect(blockNumber).to.be.greaterThan(0);1152    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1153      scheduledId,1154      expectedBlockNumber, 1155      repetitions > 1 ? [period, repetitions] : null, 1156      0, 1157      {Value: operationTx as any},1158    );11591160    const events = await submitTransactionAsync(sender, scheduleTx);1161    expect(getGenericResult(events).success).to.be.true;1162  });1163}11641165export async function1166scheduleExpectFailure(1167  operationTx: any,1168  sender: IKeyringPair,1169  blockSchedule: number,1170  scheduledId: string,1171  period = 1,1172  repetitions = 1,1173) {1174  await usingApi(async (api: ApiPromise) => {1175    const blockNumber: number | undefined = await getBlockNumber(api);1176    const expectedBlockNumber = blockNumber + blockSchedule;11771178    expect(blockNumber).to.be.greaterThan(0);1179    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1180      scheduledId,1181      expectedBlockNumber, 1182      repetitions <= 1 ? null : [period, repetitions], 1183      0, 1184      {Value: operationTx as any},1185    );11861187    //const events = 1188    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1189    //expect(getGenericResult(events).success).to.be.false;1190  });1191}11921193export async function1194scheduleTransferAndWaitExpectSuccess(1195  collectionId: number,1196  tokenId: number,1197  sender: IKeyringPair,1198  recipient: IKeyringPair,1199  value: number | bigint = 1,1200  blockSchedule: number,1201  scheduledId: string,1202) {1203  await usingApi(async (api: ApiPromise) => {1204    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);12051206    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();12071208    // sleep for n + 1 blocks1209    await waitNewBlocks(blockSchedule + 1);12101211    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();12121213    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1214    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1215  });1216}12171218export async function1219scheduleTransferExpectSuccess(1220  collectionId: number,1221  tokenId: number,1222  sender: IKeyringPair,1223  recipient: IKeyringPair,1224  value: number | bigint = 1,1225  blockSchedule: number,1226  scheduledId: string,1227) {1228  await usingApi(async (api: ApiPromise) => {1229    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);12301231    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);12321233    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1234  });1235}12361237export async function1238scheduleTransferFundsPeriodicExpectSuccess(1239  amount: bigint,1240  sender: IKeyringPair,1241  recipient: IKeyringPair,1242  blockSchedule: number,1243  scheduledId: string,1244  period: number,1245  repetitions: number,1246) {1247  await usingApi(async (api: ApiPromise) => {1248    const transferTx = api.tx.balances.transfer(recipient.address, amount);12491250    const balanceBefore = await getFreeBalance(recipient);1251    1252    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);12531254    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1255  });1256}12571258export async function1259transfer(1260  api: ApiPromise,1261  collectionId: number,1262  tokenId: number,1263  sender: IKeyringPair,1264  recipient: IKeyringPair | CrossAccountId,1265  value: number | bigint,1266) : Promise<boolean> {1267  const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1268  const events = await executeTransaction(api, sender, transferTx);1269  return getGenericResult(events).success;1270}12711272export async function1273transferExpectSuccess(1274  collectionId: number,1275  tokenId: number,1276  sender: IKeyringPair,1277  recipient: IKeyringPair | CrossAccountId,1278  value: number | bigint = 1,1279  type = 'NFT',1280) {1281  await usingApi(async (api: ApiPromise) => {1282    const from = normalizeAccountId(sender);1283    const to = normalizeAccountId(recipient);12841285    let balanceBefore = 0n;1286    if (type === 'Fungible' || type === 'ReFungible') {1287      balanceBefore = await getBalance(api, collectionId, to, tokenId);1288    }12891290    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1291    const events = await executeTransaction(api, sender, transferTx);1292    const result = getTransferResult(api, events);12931294    expect(result.collectionId).to.be.equal(collectionId);1295    expect(result.itemId).to.be.equal(tokenId);1296    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1297    expect(result.recipient).to.be.deep.equal(to);1298    expect(result.value).to.be.equal(BigInt(value));12991300    if (type === 'NFT') {1301      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1302    }1303    if (type === 'Fungible' || type === 'ReFungible') {1304      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1305      if (JSON.stringify(to) !== JSON.stringify(from)) {1306        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1307      } else {1308        expect(balanceAfter).to.be.equal(balanceBefore);1309      }1310    }1311  });1312}13131314export async function1315transferExpectFailure(1316  collectionId: number,1317  tokenId: number,1318  sender: IKeyringPair,1319  recipient: IKeyringPair | CrossAccountId,1320  value: number | bigint = 1,1321) {1322  await usingApi(async (api: ApiPromise) => {1323    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1324    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1325    const result = getGenericResult(events);1326    // if (events && Array.isArray(events)) {1327    //   const result = getCreateCollectionResult(events);1328    // tslint:disable-next-line:no-unused-expression1329    expect(result.success).to.be.false;1330    //}1331  });1332}13331334export async function1335approveExpectFail(1336  collectionId: number,1337  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1338) {1339  await usingApi(async (api: ApiPromise) => {1340    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1341    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1342    const result = getCreateCollectionResult(events);1343    // tslint:disable-next-line:no-unused-expression1344    expect(result.success).to.be.false;1345  });1346}13471348export async function getBalance(1349  api: ApiPromise,1350  collectionId: number,1351  owner: string | CrossAccountId | IKeyringPair,1352  token: number,1353): Promise<bigint> {1354  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1355}1356export async function getTokenOwner(1357  api: ApiPromise,1358  collectionId: number,1359  token: number,1360): Promise<CrossAccountId> {1361  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1362  if (owner == null) throw new Error('owner == null');1363  return normalizeAccountId(owner);1364}1365export async function getTopmostTokenOwner(1366  api: ApiPromise,1367  collectionId: number,1368  token: number,1369): Promise<CrossAccountId> {1370  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1371  if (owner == null) throw new Error('owner == null');1372  return normalizeAccountId(owner);1373}1374export async function getTokenChildren(1375  api: ApiPromise,1376  collectionId: number,1377  tokenId: number,1378): Promise<UpDataStructsTokenChild[]> {1379  return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1380}1381export async function isTokenExists(1382  api: ApiPromise,1383  collectionId: number,1384  token: number,1385): Promise<boolean> {1386  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1387}1388export async function getLastTokenId(1389  api: ApiPromise,1390  collectionId: number,1391): Promise<number> {1392  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1393}1394export async function getAdminList(1395  api: ApiPromise,1396  collectionId: number,1397): Promise<string[]> {1398  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1399}1400export async function getTokenProperties(1401  api: ApiPromise,1402  collectionId: number,1403  tokenId: number,1404  propertyKeys: string[],1405): Promise<UpDataStructsProperty[]> {1406  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1407}14081409export async function createFungibleItemExpectSuccess(1410  sender: IKeyringPair,1411  collectionId: number,1412  data: CreateFungibleData,1413  owner: CrossAccountId | string = sender.address,1414) {1415  return await usingApi(async (api) => {1416    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});14171418    const events = await submitTransactionAsync(sender, tx);1419    const result = getCreateItemResult(events);14201421    expect(result.success).to.be.true;1422    return result.itemId;1423  });1424}14251426export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1427  await usingApi(async (api) => {1428    const to = normalizeAccountId(owner);1429    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14301431    const events = await submitTransactionAsync(sender, tx);1432    expect(getGenericResult(events).success).to.be.true;1433  });1434}14351436export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1437  await usingApi(async (api) => {1438    const to = normalizeAccountId(owner);1439    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14401441    const events = await submitTransactionAsync(sender, tx);1442    const result = getCreateItemsResult(events);14431444    for (const res of result) {1445      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1446    }1447  });1448}14491450export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1451  await usingApi(async (api) => {1452    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);14531454    const events = await submitTransactionAsync(sender, tx);1455    const result = getCreateItemsResult(events);14561457    for (const res of result) {1458      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1459    }1460  });1461}14621463export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1464  let newItemId = 0;1465  await usingApi(async (api) => {1466    const to = normalizeAccountId(owner);1467    const itemCountBefore = await getLastTokenId(api, collectionId);1468    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14691470    let tx;1471    if (createMode === 'Fungible') {1472      const createData = {fungible: {value: 10}};1473      tx = api.tx.unique.createItem(collectionId, to, createData as any);1474    } else if (createMode === 'ReFungible') {1475      const createData = {refungible: {pieces: 100}};1476      tx = api.tx.unique.createItem(collectionId, to, createData as any);1477    } else {1478      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1479      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1480    }14811482    const events = await submitTransactionAsync(sender, tx);1483    const result = getCreateItemResult(events);14841485    const itemCountAfter = await getLastTokenId(api, collectionId);1486    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14871488    if (createMode === 'NFT') {1489      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1490    }14911492    // What to expect1493    // tslint:disable-next-line:no-unused-expression1494    expect(result.success).to.be.true;1495    if (createMode === 'Fungible') {1496      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1497    } else {1498      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1499    }1500    expect(collectionId).to.be.equal(result.collectionId);1501    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1502    expect(to).to.be.deep.equal(result.recipient);1503    newItemId = result.itemId;1504  });1505  return newItemId;1506}15071508export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1509  await usingApi(async (api) => {15101511    let tx;1512    if (createMode === 'NFT') {1513      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1514      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1515    } else {1516      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1517    }151815191520    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1521    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1522    const result = getCreateItemResult(events);15231524    expect(result.success).to.be.false;1525  });1526}15271528export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1529  let newItemId = 0;1530  await usingApi(async (api) => {1531    const to = normalizeAccountId(owner);1532    const itemCountBefore = await getLastTokenId(api, collectionId);1533    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);15341535    let tx;1536    if (createMode === 'Fungible') {1537      const createData = {fungible: {value: 10}};1538      tx = api.tx.unique.createItem(collectionId, to, createData as any);1539    } else if (createMode === 'ReFungible') {1540      const createData = {refungible: {pieces: 100}};1541      tx = api.tx.unique.createItem(collectionId, to, createData as any);1542    } else {1543      const createData = {nft: {}};1544      tx = api.tx.unique.createItem(collectionId, to, createData as any);1545    }15461547    const events = await executeTransaction(api, sender, tx);1548    const result = getCreateItemResult(events);15491550    const itemCountAfter = await getLastTokenId(api, collectionId);1551    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15521553    // What to expect1554    // tslint:disable-next-line:no-unused-expression1555    expect(result.success).to.be.true;1556    if (createMode === 'Fungible') {1557      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1558    } else {1559      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1560    }1561    expect(collectionId).to.be.equal(result.collectionId);1562    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1563    expect(to).to.be.deep.equal(result.recipient);1564    newItemId = result.itemId;1565  });1566  return newItemId;1567}15681569export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1570  const createData = {refungible: {pieces: amount}};1571  const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15721573  const events = await submitTransactionAsync(sender, tx);1574  return  getCreateItemResult(events);1575}15761577export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1578  await usingApi(async (api) => {1579    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15801581    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1582    const result = getCreateItemResult(events);15831584    expect(result.success).to.be.false;1585  });1586}15871588export async function setPublicAccessModeExpectSuccess(1589  sender: IKeyringPair, collectionId: number,1590  accessMode: 'Normal' | 'AllowList',1591) {1592  await usingApi(async (api) => {15931594    // Run the transaction1595    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1596    const events = await submitTransactionAsync(sender, tx);1597    const result = getGenericResult(events);15981599    // Get the collection1600    const collection = await queryCollectionExpectSuccess(api, collectionId);16011602    // What to expect1603    // tslint:disable-next-line:no-unused-expression1604    expect(result.success).to.be.true;1605    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1606  });1607}16081609export async function setPublicAccessModeExpectFail(1610  sender: IKeyringPair, collectionId: number,1611  accessMode: 'Normal' | 'AllowList',1612) {1613  await usingApi(async (api) => {16141615    // Run the transaction1616    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1617    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1618    const result = getGenericResult(events);16191620    // What to expect1621    // tslint:disable-next-line:no-unused-expression1622    expect(result.success).to.be.false;1623  });1624}16251626export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1627  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1628}16291630export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1631  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1632}16331634export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1635  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1636}16371638export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1639  await usingApi(async (api) => {16401641    // Run the transaction1642    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1643    const events = await submitTransactionAsync(sender, tx);1644    const result = getGenericResult(events);1645    expect(result.success).to.be.true;16461647    // Get the collection1648    const collection = await queryCollectionExpectSuccess(api, collectionId);16491650    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1651  });1652}16531654export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1655  await setMintPermissionExpectSuccess(sender, collectionId, true);1656}16571658export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1659  await usingApi(async (api) => {1660    // Run the transaction1661    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1662    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1663    const result = getCreateCollectionResult(events);1664    // tslint:disable-next-line:no-unused-expression1665    expect(result.success).to.be.false;1666  });1667}16681669export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1670  await usingApi(async (api) => {1671    // Run the transaction1672    const tx = api.tx.unique.setChainLimits(limits);1673    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1674    const result = getCreateCollectionResult(events);1675    // tslint:disable-next-line:no-unused-expression1676    expect(result.success).to.be.false;1677  });1678}16791680export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1681  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1682}16831684export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1685  await usingApi(async (api) => {1686    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16871688    // Run the transaction1689    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1690    const events = await submitTransactionAsync(sender, tx);1691    const result = getGenericResult(events);1692    expect(result.success).to.be.true;16931694    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1695  });1696}16971698export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1699  await usingApi(async (api) => {17001701    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;17021703    // Run the transaction1704    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1705    const events = await submitTransactionAsync(sender, tx);1706    const result = getGenericResult(events);1707    expect(result.success).to.be.true;17081709    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1710  });1711}17121713export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1714  await usingApi(async (api) => {17151716    // Run the transaction1717    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1718    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1719    const result = getGenericResult(events);17201721    // What to expect1722    // tslint:disable-next-line:no-unused-expression1723    expect(result.success).to.be.false;1724  });1725}17261727export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1728  await usingApi(async (api) => {1729    // Run the transaction1730    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1731    const events = await submitTransactionAsync(sender, tx);1732    const result = getGenericResult(events);17331734    // What to expect1735    // tslint:disable-next-line:no-unused-expression1736    expect(result.success).to.be.true;1737  });1738}17391740export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1741  await usingApi(async (api) => {1742    // Run the transaction1743    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1744    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1745    const result = getGenericResult(events);17461747    // What to expect1748    // tslint:disable-next-line:no-unused-expression1749    expect(result.success).to.be.false;1750  });1751}17521753export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1754  : Promise<UpDataStructsRpcCollection | null> => {1755  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1756};17571758export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1759  // set global object - collectionsCount1760  return (await api.rpc.unique.collectionStats()).created.toNumber();1761};17621763export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1764  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1765}17661767export const describe_xcm = (1768  process.env.RUN_XCM_TESTS1769    ? describe1770    : describe.skip1771);17721773export async function waitNewBlocks(blocksCount = 1): Promise<void> {1774  await usingApi(async (api) => {1775    const promise = new Promise<void>(async (resolve) => {1776      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1777        if (blocksCount > 0) {1778          blocksCount--;1779        } else {1780          unsubscribe();1781          resolve();1782        }1783      });1784    });1785    return promise;1786  });1787}17881789export async function waitEvent(1790  api: ApiPromise,1791  maxBlocksToWait: number,1792  eventSection: string,1793  eventMethod: string,1794): Promise<EventRecord | null> {17951796  const promise = new Promise<EventRecord | null>(async (resolve) => {1797    const unsubscribe = await api.query.system.events(eventRecords => {1798      const neededEvent = eventRecords.find(r => {1799        return r.event.section == eventSection && r.event.method == eventMethod;1800      });18011802      if (neededEvent) {1803        unsubscribe();1804        resolve(neededEvent);1805      }18061807      if (maxBlocksToWait > 0) {1808        maxBlocksToWait--;1809      } else {1810        unsubscribe();1811        resolve(null);1812      }1813    });1814  });1815  return promise;1816}18171818export async function repartitionRFT(1819  api: ApiPromise,1820  collectionId: number,1821  sender: IKeyringPair,1822  tokenId: number,1823  amount: bigint,1824): Promise<boolean> {1825  const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1826  const events = await submitTransactionAsync(sender, tx);1827  const result = getGenericResult(events);18281829  return result.success;1830}18311832export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1833  let i: any = it;1834  if (opts.only) i = i.only;1835  else if (opts.skip) i = i.skip;1836  i(name, async () => {1837    await usingApi(async (api, privateKeyWrapper) => {1838      await cb({api, privateKeyWrapper});1839    });1840  });1841}18421843itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1844itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});18451846let accountSeed = 10000;18471848const keyringEth = new Keyring({type: 'ethereum'});1849const keyringEd25519 = new Keyring({type: 'ed25519'});1850const keyringSr25519 = new Keyring({type: 'sr25519'});18511852export function generateKeyringPair(type: 'ethereum' | 'sr25519' | 'ed25519' = 'sr25519') {1853  const privateKey = `0xDEADBEEF${(accountSeed++).toString(16).padStart(56, '0')}`;1854  if (type == 'sr25519') {1855    return keyringSr25519.addFromUri(privateKey);1856  } else if (type == 'ed25519') {1857    return keyringEd25519.addFromUri(privateKey);1858  }1859  return keyringEth.addFromUri(privateKey);1860}
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, Keyring} 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.error('\x1b[38:5:208m%s\x1b[0m', skipMsg);9798    mocha.skip();99  }100}101102export function bigIntToSub(api: ApiPromise, number: bigint) {103  return api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();104}105106export function bigIntToDecimals(number: bigint, decimals = 18): string {107  const numberStr = number.toString();108  const dotPos = numberStr.length - decimals;109110  if (dotPos <= 0) {111    return '0.' + numberStr;112  } else {113    const intPart = numberStr.substring(0, dotPos);114    const fractPart = numberStr.substring(dotPos);115    return intPart + '.' + fractPart;116  }117}118119export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {120  if (typeof input === 'string') {121    if (input.length >= 47) {122      return {Substrate: input};123    } else if (input.length === 42 && input.startsWith('0x')) {124      return {Ethereum: input.toLowerCase()};125    } else if (input.length === 40 && !input.startsWith('0x')) {126      return {Ethereum: '0x' + input.toLowerCase()};127    } else {128      throw new Error(`Unknown address format: "${input}"`);129    }130  }131  if ('address' in input) {132    return {Substrate: input.address};133  }134  if ('Ethereum' in input) {135    return {136      Ethereum: input.Ethereum.toLowerCase(),137    };138  } else if ('ethereum' in input) {139    return {140      Ethereum: (input as any).ethereum.toLowerCase(),141    };142  } else if ('Substrate' in input) {143    return input;144  } else if ('substrate' in input) {145    return {146      Substrate: (input as any).substrate,147    };148  }149150  // AccountId151  return {Substrate: input.toString()};152}153export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {154  input = normalizeAccountId(input);155  if ('Substrate' in input) {156    return input.Substrate;157  } else {158    return evmToAddress(input.Ethereum);159  }160}161162export const U128_MAX = (1n << 128n) - 1n;163164const MICROUNIQUE = 1_000_000_000_000n;165const MILLIUNIQUE = 1_000n * MICROUNIQUE;166const CENTIUNIQUE = 10n * MILLIUNIQUE;167export const UNIQUE = 100n * CENTIUNIQUE;168169interface GenericResult<T> {170  success: boolean;171  data: T | null;172}173174interface CreateCollectionResult {175  success: boolean;176  collectionId: number;177}178179interface CreateItemResult {180  success: boolean;181  collectionId: number;182  itemId: number;183  recipient?: CrossAccountId;184  amount?: number;185}186187interface DestroyItemResult {188  success: boolean;189  collectionId: number;190  itemId: number;191  owner: CrossAccountId;192  amount: number;193}194195interface TransferResult {196  collectionId: number;197  itemId: number;198  sender?: CrossAccountId;199  recipient?: CrossAccountId;200  value: bigint;201}202203interface IReFungibleOwner {204  fraction: BN;205  owner: number[];206}207208interface IGetMessage {209  checkMsgUnqMethod: string;210  checkMsgTrsMethod: string;211  checkMsgSysMethod: string;212}213214export interface IFungibleTokenDataType {215  value: number;216}217218export interface IChainLimits {219  collectionNumbersLimit: number;220  accountTokenOwnershipLimit: number;221  collectionsAdminsLimit: number;222  customDataLimit: number;223  nftSponsorTransferTimeout: number;224  fungibleSponsorTransferTimeout: number;225  refungibleSponsorTransferTimeout: number;226  //offchainSchemaLimit: number;227  //constOnChainSchemaLimit: number;228}229230export interface IReFungibleTokenDataType {231  owner: IReFungibleOwner[];232}233234export function uniqueEventMessage(events: EventRecord[]): IGetMessage {235  let checkMsgUnqMethod = '';236  let checkMsgTrsMethod = '';237  let checkMsgSysMethod = '';238  events.forEach(({event: {method, section}}) => {239    if (section === 'common') {240      checkMsgUnqMethod = method;241    } else if (section === 'treasury') {242      checkMsgTrsMethod = method;243    } else if (section === 'system') {244      checkMsgSysMethod = method;245    } else { return null; }246  });247  const result: IGetMessage = {248    checkMsgUnqMethod,249    checkMsgTrsMethod,250    checkMsgSysMethod,251  };252  return result;253}254255export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {256  const event = events.find(r => check(r.event));257  if (!event) return;258  return event.event as T;259}260261export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;262export function getGenericResult<T>(263  events: EventRecord[],264  expectSection: string,265  expectMethod: string,266  extractAction: (data: GenericEventData) => T267): GenericResult<T>;268269export function getGenericResult<T>(270  events: EventRecord[],271  expectSection?: string,272  expectMethod?: string,273  extractAction?: (data: GenericEventData) => T,274): GenericResult<T> {275  let success = false;276  let successData = null;277278  events.forEach(({event: {data, method, section}}) => {279    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);280    if (method === 'ExtrinsicSuccess') {281      success = true;282    } else if ((expectSection == section) && (expectMethod == method)) {283      successData = extractAction!(data as any);284    }285  });286287  const result: GenericResult<T> = {288    success,289    data: successData,290  };291  return result;292}293294export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {295  const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));296  const result: CreateCollectionResult = {297    success: genericResult.success,298    collectionId: genericResult.data ?? 0,299  };300  return result;301}302303export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {304  const results: CreateItemResult[] = [];305  306  const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {307    const collectionId = parseInt(data[0].toString(), 10);308    const itemId = parseInt(data[1].toString(), 10);309    const recipient = normalizeAccountId(data[2].toJSON() as any);310    const amount = parseInt(data[3].toString(), 10);311312    const itemRes: CreateItemResult = {313      success: true,314      collectionId,315      itemId,316      recipient,317      amount,318    };319320    results.push(itemRes);321    return results;322  });323324  if (!genericResult.success) return [];325  return results;326}327328export function getCreateItemResult(events: EventRecord[]): CreateItemResult {329  const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));330  331  if (genericResult.data == null) 332    return {333      success: genericResult.success,334      collectionId: 0,335      itemId: 0,336      amount: 0,337    };338  else 339    return {340      success: genericResult.success,341      collectionId: genericResult.data[0] as number,342      itemId: genericResult.data[1] as number,343      recipient: normalizeAccountId(genericResult.data![2] as any),344      amount: genericResult.data[3] as number,345    };346}347348export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {349  const results: DestroyItemResult[] = [];350  351  const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {352    const collectionId = parseInt(data[0].toString(), 10);353    const itemId = parseInt(data[1].toString(), 10);354    const owner = normalizeAccountId(data[2].toJSON() as any);355    const amount = parseInt(data[3].toString(), 10);356357    const itemRes: DestroyItemResult = {358      success: true,359      collectionId,360      itemId,361      owner,362      amount,363    };364365    results.push(itemRes);366    return results;367  });368369  if (!genericResult.success) return [];370  return results;371}372373export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {374  for (const {event} of events) {375    if (api.events.common.Transfer.is(event)) {376      const [collection, token, sender, recipient, value] = event.data;377      return {378        collectionId: collection.toNumber(),379        itemId: token.toNumber(),380        sender: normalizeAccountId(sender.toJSON() as any),381        recipient: normalizeAccountId(recipient.toJSON() as any),382        value: value.toBigInt(),383      };384    }385  }386  throw new Error('no transfer event');387}388389interface Nft {390  type: 'NFT';391}392393interface Fungible {394  type: 'Fungible';395  decimalPoints: number;396}397398interface ReFungible {399  type: 'ReFungible';400}401402export type CollectionMode = Nft | Fungible | ReFungible;403404export type Property = {405  key: any,406  value: any,407};408409type Permission = {410  mutable: boolean;411  collectionAdmin: boolean;412  tokenOwner: boolean;413}414415type PropertyPermission = {416  key: any;417  permission: Permission;418}419420export type CreateCollectionParams = {421  mode: CollectionMode,422  name: string,423  description: string,424  tokenPrefix: string,425  properties?: Array<Property>,426  propPerm?: Array<PropertyPermission>427};428429const defaultCreateCollectionParams: CreateCollectionParams = {430  description: 'description',431  mode: {type: 'NFT'},432  name: 'name',433  tokenPrefix: 'prefix',434};435436export async function437createCollection(438  api: ApiPromise,439  sender: IKeyringPair,440  params: Partial<CreateCollectionParams> = {},441): Promise<CreateCollectionResult> {442  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};443444  let modeprm = {};445  if (mode.type === 'NFT') {446    modeprm = {nft: null};447  } else if (mode.type === 'Fungible') {448    modeprm = {fungible: mode.decimalPoints};449  } else if (mode.type === 'ReFungible') {450    modeprm = {refungible: null};451  }452453  const tx = api.tx.unique.createCollectionEx({454    name: strToUTF16(name),455    description: strToUTF16(description),456    tokenPrefix: strToUTF16(tokenPrefix),457    mode: modeprm as any,458  });459  const events = await executeTransaction(api, sender, tx);460  return getCreateCollectionResult(events);461}462463export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {464  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};465466  let collectionId = 0;467  await usingApi(async (api, privateKeyWrapper) => {468    // Get number of collections before the transaction469    const collectionCountBefore = await getCreatedCollectionCount(api);470471    // Run the CreateCollection transaction472    const alicePrivateKey = privateKeyWrapper('//Alice');473474    const result = await createCollection(api, alicePrivateKey, params);475476    // Get number of collections after the transaction477    const collectionCountAfter = await getCreatedCollectionCount(api);478479    // Get the collection480    const collection = await queryCollectionExpectSuccess(api, result.collectionId);481482    // What to expect483    // tslint:disable-next-line:no-unused-expression484    expect(result.success).to.be.true;485    expect(result.collectionId).to.be.equal(collectionCountAfter);486    // tslint:disable-next-line:no-unused-expression487    expect(collection).to.be.not.null;488    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');489    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));490    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);491    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);492    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);493494    collectionId = result.collectionId;495  });496497  return collectionId;498}499500export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {501  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};502503  let collectionId = 0;504  await usingApi(async (api, privateKeyWrapper) => {505    // Get number of collections before the transaction506    const collectionCountBefore = await getCreatedCollectionCount(api);507508    // Run the CreateCollection transaction509    const alicePrivateKey = privateKeyWrapper('//Alice');510511    let modeprm = {};512    if (mode.type === 'NFT') {513      modeprm = {nft: null};514    } else if (mode.type === 'Fungible') {515      modeprm = {fungible: mode.decimalPoints};516    } else if (mode.type === 'ReFungible') {517      modeprm = {refungible: null};518    }519520    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});521    const events = await submitTransactionAsync(alicePrivateKey, tx);522    const result = getCreateCollectionResult(events);523524    // Get number of collections after the transaction525    const collectionCountAfter = await getCreatedCollectionCount(api);526527    // Get the collection528    const collection = await queryCollectionExpectSuccess(api, result.collectionId);529530    // What to expect531    // tslint:disable-next-line:no-unused-expression532    expect(result.success).to.be.true;533    expect(result.collectionId).to.be.equal(collectionCountAfter);534    // tslint:disable-next-line:no-unused-expression535    expect(collection).to.be.not.null;536    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');537    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));538    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);539    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);540    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);541542543    collectionId = result.collectionId;544  });545546  return collectionId;547}548549export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {550  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};551552  await usingApi(async (api, privateKeyWrapper) => {553    // Get number of collections before the transaction554    const collectionCountBefore = await getCreatedCollectionCount(api);555556    // Run the CreateCollection transaction557    const alicePrivateKey = privateKeyWrapper('//Alice');558559    let modeprm = {};560    if (mode.type === 'NFT') {561      modeprm = {nft: null};562    } else if (mode.type === 'Fungible') {563      modeprm = {fungible: mode.decimalPoints};564    } else if (mode.type === 'ReFungible') {565      modeprm = {refungible: null};566    }567568    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});569    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;570571572    // Get number of collections after the transaction573    const collectionCountAfter = await getCreatedCollectionCount(api);574575    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');576  });577}578579export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {580  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};581582  let modeprm = {};583  if (mode.type === 'NFT') {584    modeprm = {nft: null};585  } else if (mode.type === 'Fungible') {586    modeprm = {fungible: mode.decimalPoints};587  } else if (mode.type === 'ReFungible') {588    modeprm = {refungible: null};589  }590591  await usingApi(async (api, privateKeyWrapper) => {592    // Get number of collections before the transaction593    const collectionCountBefore = await getCreatedCollectionCount(api);594595    // Run the CreateCollection transaction596    const alicePrivateKey = privateKeyWrapper('//Alice');597    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});598    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;599600    // Get number of collections after the transaction601    const collectionCountAfter = await getCreatedCollectionCount(api);602603    // What to expect604    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');605  });606}607608export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {609  let bal = 0n;610  let unused;611  do {612    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;613    unused = privateKeyWrapper(`//${randomSeed}`);614    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();615  } while (bal !== 0n);616  return unused;617}618619export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {620  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();621}622623export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {624  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));625}626627export async function findNotExistingCollection(api: ApiPromise): Promise<number> {628  const totalNumber = await getCreatedCollectionCount(api);629  const newCollection: number = totalNumber + 1;630  return newCollection;631}632633function getDestroyResult(events: EventRecord[]): boolean {634  let success = false;635  events.forEach(({event: {method}}) => {636    if (method == 'ExtrinsicSuccess') {637      success = true;638    }639  });640  return success;641}642643export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {644  await usingApi(async (api, privateKeyWrapper) => {645    // Run the DestroyCollection transaction646    const alicePrivateKey = privateKeyWrapper(senderSeed);647    const tx = api.tx.unique.destroyCollection(collectionId);648    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;649  });650}651652export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {653  await usingApi(async (api, privateKeyWrapper) => {654    // Run the DestroyCollection transaction655    const alicePrivateKey = privateKeyWrapper(senderSeed);656    const tx = api.tx.unique.destroyCollection(collectionId);657    const events = await submitTransactionAsync(alicePrivateKey, tx);658    const result = getDestroyResult(events);659    expect(result).to.be.true;660661    // What to expect662    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;663  });664}665666export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {667  await usingApi(async (api) => {668    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);669    const events = await submitTransactionAsync(sender, tx);670    const result = getGenericResult(events);671672    expect(result.success).to.be.true;673  });674}675676export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {677  await usingApi(async(api) => {678    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);679    const events = await submitTransactionAsync(sender, tx);680    const result = getGenericResult(events);681682    expect(result.success).to.be.true;683  });684};685686export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {687  await usingApi(async (api) => {688    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);689    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;690    const result = getGenericResult(events);691692    expect(result.success).to.be.false;693  });694}695696export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {697  await usingApi(async (api, privateKeyWrapper) => {698699    // Run the transaction700    const senderPrivateKey = privateKeyWrapper(sender);701    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);702    const events = await submitTransactionAsync(senderPrivateKey, tx);703    const result = getGenericResult(events);704705    // Get the collection706    const collection = await queryCollectionExpectSuccess(api, collectionId);707708    // What to expect709    expect(result.success).to.be.true;710    expect(collection.sponsorship.toJSON()).to.deep.equal({711      unconfirmed: sponsor,712    });713  });714}715716export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {717  await usingApi(async (api, privateKeyWrapper) => {718719    // Run the transaction720    const alicePrivateKey = privateKeyWrapper(sender);721    const tx = api.tx.unique.removeCollectionSponsor(collectionId);722    const events = await submitTransactionAsync(alicePrivateKey, tx);723    const result = getGenericResult(events);724725    // Get the collection726    const collection = await queryCollectionExpectSuccess(api, collectionId);727728    // What to expect729    expect(result.success).to.be.true;730    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});731  });732}733734export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {735  await usingApi(async (api, privateKeyWrapper) => {736737    // Run the transaction738    const alicePrivateKey = privateKeyWrapper(senderSeed);739    const tx = api.tx.unique.removeCollectionSponsor(collectionId);740    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;741  });742}743744export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {745  await usingApi(async (api, privateKeyWrapper) => {746747    // Run the transaction748    const alicePrivateKey = privateKeyWrapper(senderSeed);749    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);750    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;751  });752}753754export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {755  await usingApi(async (api, privateKeyWrapper) => {756757    // Run the transaction758    const sender = privateKeyWrapper(senderSeed);759    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);760  });761}762763export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {764  await usingApi(async (api, privateKeyWrapper) => {765766    // Run the transaction767    const tx = api.tx.unique.confirmSponsorship(collectionId);768    const events = await submitTransactionAsync(sender, tx);769    const result = getGenericResult(events);770771    // Get the collection772    const collection = await queryCollectionExpectSuccess(api, collectionId);773774    // What to expect775    expect(result.success).to.be.true;776    expect(collection.sponsorship.toJSON()).to.be.deep.equal({777      confirmed: sender.address,778    });779  });780}781782783export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {784  await usingApi(async (api, privateKeyWrapper) => {785786    // Run the transaction787    const sender = privateKeyWrapper(senderSeed);788    const tx = api.tx.unique.confirmSponsorship(collectionId);789    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;790  });791}792793export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {794  await usingApi(async (api) => {795    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);796    const events = await submitTransactionAsync(sender, tx);797    const result = getGenericResult(events);798799    expect(result.success).to.be.true;800  });801}802803export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {804  await usingApi(async (api) => {805    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);806    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;807    const result = getGenericResult(events);808809    expect(result.success).to.be.false;810  });811}812813export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {814815  await usingApi(async (api) => {816817    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);818    const events = await submitTransactionAsync(sender, tx);819    const result = getGenericResult(events);820821    expect(result.success).to.be.true;822  });823}824825export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {826827  await usingApi(async (api) => {828829    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);830    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;831    const result = getGenericResult(events);832833    expect(result.success).to.be.false;834  });835}836837export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {838  await usingApi(async (api) => {839    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);840    const events = await submitTransactionAsync(sender, tx);841    const result = getGenericResult(events);842843    expect(result.success).to.be.true;844  });845}846847export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {848  await usingApi(async (api) => {849    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);850    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;851    const result = getGenericResult(events);852853    expect(result.success).to.be.false;854  });855}856857export async function getNextSponsored(858  api: ApiPromise,859  collectionId: number,860  account: string | CrossAccountId,861  tokenId: number,862): Promise<number> {863  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));864}865866export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {867  await usingApi(async (api) => {868    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);869    const events = await submitTransactionAsync(sender, tx);870    const result = getGenericResult(events);871872    expect(result.success).to.be.true;873  });874}875876export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {877  let allowlisted = false;878  await usingApi(async (api) => {879    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;880  });881  return allowlisted;882}883884export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {885  await usingApi(async (api) => {886    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());887    const events = await submitTransactionAsync(sender, tx);888    const result = getGenericResult(events);889890    expect(result.success).to.be.true;891  });892}893894export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {895  await usingApi(async (api) => {896    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());897    const events = await submitTransactionAsync(sender, tx);898    const result = getGenericResult(events);899900    expect(result.success).to.be.true;901  });902}903904export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {905  await usingApi(async (api) => {906    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());907    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;908    const result = getGenericResult(events);909910    expect(result.success).to.be.false;911  });912}913914export interface CreateFungibleData {915  readonly Value: bigint;916}917918export interface CreateReFungibleData { }919export interface CreateNftData { }920921export type CreateItemData = {922  NFT: CreateNftData;923} | {924  Fungible: CreateFungibleData;925} | {926  ReFungible: CreateReFungibleData;927};928929export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {930  const tx = api.tx.unique.burnItem(collectionId, tokenId, value);931  const events = await submitTransactionAsync(sender, tx);932  return getGenericResult(events).success;933}934935export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {936  await usingApi(async (api) => {937    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);938    // if burning token by admin - use adminButnItemExpectSuccess939    expect(balanceBefore >= BigInt(value)).to.be.true;940941    expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;942943    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);944    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);945  });946}947948export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {949  await usingApi(async (api) => {950    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);951952    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;953    const result = getCreateCollectionResult(events);954    // tslint:disable-next-line:no-unused-expression955    expect(result.success).to.be.false;956  });957}958959export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {960  await usingApi(async (api) => {961    const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);962    const events = await submitTransactionAsync(sender, tx);963    return getGenericResult(events).success;964  });965}966967export async function968approve(969  api: ApiPromise,970  collectionId: number,971  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,972) {973  const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);974  const events = await submitTransactionAsync(owner, approveUniqueTx);975  return getGenericResult(events).success;976}977978export async function979approveExpectSuccess(980  collectionId: number,981  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,982) {983  await usingApi(async (api: ApiPromise) => {984    const result = await approve(api, collectionId, tokenId, owner, approved, amount);985    expect(result).to.be.true;986987    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));988  });989}990991export async function adminApproveFromExpectSuccess(992  collectionId: number,993  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,994) {995  await usingApi(async (api: ApiPromise) => {996    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);997    const events = await submitTransactionAsync(admin, approveUniqueTx);998    const result = getGenericResult(events);999    expect(result.success).to.be.true;10001001    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));1002  });1003}10041005export async function1006transferFrom(1007  api: ApiPromise,1008  collectionId: number,1009  tokenId: number,1010  accountApproved: IKeyringPair,1011  accountFrom: IKeyringPair | CrossAccountId,1012  accountTo: IKeyringPair | CrossAccountId,1013  value: number | bigint,1014) {1015  const from = normalizeAccountId(accountFrom);1016  const to = normalizeAccountId(accountTo);1017  const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);1018  const events = await submitTransactionAsync(accountApproved, transferFromTx);1019  return getGenericResult(events).success;1020}10211022export async function1023transferFromExpectSuccess(1024  collectionId: number,1025  tokenId: number,1026  accountApproved: IKeyringPair,1027  accountFrom: IKeyringPair | CrossAccountId,1028  accountTo: IKeyringPair | CrossAccountId,1029  value: number | bigint = 1,1030  type = 'NFT',1031) {1032  await usingApi(async (api: ApiPromise) => {1033    const from = normalizeAccountId(accountFrom);1034    const to = normalizeAccountId(accountTo);1035    let balanceBefore = 0n;1036    if (type === 'Fungible' || type === 'ReFungible') {1037      balanceBefore = await getBalance(api, collectionId, to, tokenId);1038    }1039    expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;1040    if (type === 'NFT') {1041      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1042    }1043    if (type === 'Fungible') {1044      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1045      if (JSON.stringify(to) !== JSON.stringify(from)) {1046        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1047      } else {1048        expect(balanceAfter).to.be.equal(balanceBefore);1049      }1050    }1051    if (type === 'ReFungible') {1052      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1053    }1054  });1055}10561057export async function1058transferFromExpectFail(1059  collectionId: number,1060  tokenId: number,1061  accountApproved: IKeyringPair,1062  accountFrom: IKeyringPair,1063  accountTo: IKeyringPair,1064  value: number | bigint = 1,1065) {1066  await usingApi(async (api: ApiPromise) => {1067    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1068    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1069    const result = getCreateCollectionResult(events);1070    // tslint:disable-next-line:no-unused-expression1071    expect(result.success).to.be.false;1072  });1073}10741075/* eslint no-async-promise-executor: "off" */1076export async function getBlockNumber(api: ApiPromise): Promise<number> {1077  return new Promise<number>(async (resolve) => {1078    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1079      unsubscribe();1080      resolve(head.number.toNumber());1081    });1082  });1083}10841085export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1086  await usingApi(async (api) => {1087    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1088    const events = await submitTransactionAsync(sender, changeAdminTx);1089    const result = getCreateCollectionResult(events);1090    expect(result.success).to.be.true;1091  });1092}10931094export async function adminApproveFromExpectFail(1095  collectionId: number,1096  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1097) {1098  await usingApi(async (api: ApiPromise) => {1099    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1100    const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1101    const result = getGenericResult(events);1102    expect(result.success).to.be.false;1103  });1104}11051106export async function1107getFreeBalance(account: IKeyringPair): Promise<bigint> {1108  let balance = 0n;1109  await usingApi(async (api) => {1110    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1111  });11121113  return balance;1114}11151116export async function paraSiblingSovereignAccount(paraid: number): Promise<string> {1117  return usingApi(async api => {1118    const siblingPrefix = '0x7369626c';1119    const encodedParaId = api.createType('u32', paraid).toHex(true).substring(2);1120    const suffix = '000000000000000000000000000000000000000000000000';11211122    return siblingPrefix + encodedParaId + suffix;1123  });1124}11251126export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1127  const tx = api.tx.balances.transfer(target, amount);1128  const events = await submitTransactionAsync(source, tx);1129  const result = getGenericResult(events);1130  expect(result.success).to.be.true;1131}11321133export async function1134scheduleExpectSuccess(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 ? [period, repetitions] : null, 1151      0, 1152      {Value: operationTx as any},1153    );11541155    const events = await submitTransactionAsync(sender, scheduleTx);1156    expect(getGenericResult(events).success).to.be.true;1157  });1158}11591160export async function1161scheduleExpectFailure(1162  operationTx: any,1163  sender: IKeyringPair,1164  blockSchedule: number,1165  scheduledId: string,1166  period = 1,1167  repetitions = 1,1168) {1169  await usingApi(async (api: ApiPromise) => {1170    const blockNumber: number | undefined = await getBlockNumber(api);1171    const expectedBlockNumber = blockNumber + blockSchedule;11721173    expect(blockNumber).to.be.greaterThan(0);1174    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1175      scheduledId,1176      expectedBlockNumber, 1177      repetitions <= 1 ? null : [period, repetitions], 1178      0, 1179      {Value: operationTx as any},1180    );11811182    //const events = 1183    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1184    //expect(getGenericResult(events).success).to.be.false;1185  });1186}11871188export async function1189scheduleTransferAndWaitExpectSuccess(1190  collectionId: number,1191  tokenId: number,1192  sender: IKeyringPair,1193  recipient: IKeyringPair,1194  value: number | bigint = 1,1195  blockSchedule: number,1196  scheduledId: string,1197) {1198  await usingApi(async (api: ApiPromise) => {1199    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);12001201    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();12021203    // sleep for n + 1 blocks1204    await waitNewBlocks(blockSchedule + 1);12051206    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();12071208    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1209    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1210  });1211}12121213export async function1214scheduleTransferExpectSuccess(1215  collectionId: number,1216  tokenId: number,1217  sender: IKeyringPair,1218  recipient: IKeyringPair,1219  value: number | bigint = 1,1220  blockSchedule: number,1221  scheduledId: string,1222) {1223  await usingApi(async (api: ApiPromise) => {1224    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);12251226    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);12271228    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1229  });1230}12311232export async function1233scheduleTransferFundsPeriodicExpectSuccess(1234  amount: bigint,1235  sender: IKeyringPair,1236  recipient: IKeyringPair,1237  blockSchedule: number,1238  scheduledId: string,1239  period: number,1240  repetitions: number,1241) {1242  await usingApi(async (api: ApiPromise) => {1243    const transferTx = api.tx.balances.transfer(recipient.address, amount);12441245    const balanceBefore = await getFreeBalance(recipient);1246    1247    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);12481249    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1250  });1251}12521253export async function1254transfer(1255  api: ApiPromise,1256  collectionId: number,1257  tokenId: number,1258  sender: IKeyringPair,1259  recipient: IKeyringPair | CrossAccountId,1260  value: number | bigint,1261) : Promise<boolean> {1262  const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1263  const events = await executeTransaction(api, sender, transferTx);1264  return getGenericResult(events).success;1265}12661267export async function1268transferExpectSuccess(1269  collectionId: number,1270  tokenId: number,1271  sender: IKeyringPair,1272  recipient: IKeyringPair | CrossAccountId,1273  value: number | bigint = 1,1274  type = 'NFT',1275) {1276  await usingApi(async (api: ApiPromise) => {1277    const from = normalizeAccountId(sender);1278    const to = normalizeAccountId(recipient);12791280    let balanceBefore = 0n;1281    if (type === 'Fungible' || type === 'ReFungible') {1282      balanceBefore = await getBalance(api, collectionId, to, tokenId);1283    }12841285    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1286    const events = await executeTransaction(api, sender, transferTx);1287    const result = getTransferResult(api, events);12881289    expect(result.collectionId).to.be.equal(collectionId);1290    expect(result.itemId).to.be.equal(tokenId);1291    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1292    expect(result.recipient).to.be.deep.equal(to);1293    expect(result.value).to.be.equal(BigInt(value));12941295    if (type === 'NFT') {1296      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1297    }1298    if (type === 'Fungible' || type === 'ReFungible') {1299      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1300      if (JSON.stringify(to) !== JSON.stringify(from)) {1301        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1302      } else {1303        expect(balanceAfter).to.be.equal(balanceBefore);1304      }1305    }1306  });1307}13081309export async function1310transferExpectFailure(1311  collectionId: number,1312  tokenId: number,1313  sender: IKeyringPair,1314  recipient: IKeyringPair | CrossAccountId,1315  value: number | bigint = 1,1316) {1317  await usingApi(async (api: ApiPromise) => {1318    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1319    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1320    const result = getGenericResult(events);1321    // if (events && Array.isArray(events)) {1322    //   const result = getCreateCollectionResult(events);1323    // tslint:disable-next-line:no-unused-expression1324    expect(result.success).to.be.false;1325    //}1326  });1327}13281329export async function1330approveExpectFail(1331  collectionId: number,1332  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1333) {1334  await usingApi(async (api: ApiPromise) => {1335    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1336    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1337    const result = getCreateCollectionResult(events);1338    // tslint:disable-next-line:no-unused-expression1339    expect(result.success).to.be.false;1340  });1341}13421343export async function getBalance(1344  api: ApiPromise,1345  collectionId: number,1346  owner: string | CrossAccountId | IKeyringPair,1347  token: number,1348): Promise<bigint> {1349  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1350}1351export async function getTokenOwner(1352  api: ApiPromise,1353  collectionId: number,1354  token: number,1355): Promise<CrossAccountId> {1356  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1357  if (owner == null) throw new Error('owner == null');1358  return normalizeAccountId(owner);1359}1360export async function getTopmostTokenOwner(1361  api: ApiPromise,1362  collectionId: number,1363  token: number,1364): Promise<CrossAccountId> {1365  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1366  if (owner == null) throw new Error('owner == null');1367  return normalizeAccountId(owner);1368}1369export async function getTokenChildren(1370  api: ApiPromise,1371  collectionId: number,1372  tokenId: number,1373): Promise<UpDataStructsTokenChild[]> {1374  return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1375}1376export async function isTokenExists(1377  api: ApiPromise,1378  collectionId: number,1379  token: number,1380): Promise<boolean> {1381  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1382}1383export async function getLastTokenId(1384  api: ApiPromise,1385  collectionId: number,1386): Promise<number> {1387  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1388}1389export async function getAdminList(1390  api: ApiPromise,1391  collectionId: number,1392): Promise<string[]> {1393  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1394}1395export async function getTokenProperties(1396  api: ApiPromise,1397  collectionId: number,1398  tokenId: number,1399  propertyKeys: string[],1400): Promise<UpDataStructsProperty[]> {1401  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1402}14031404export async function createFungibleItemExpectSuccess(1405  sender: IKeyringPair,1406  collectionId: number,1407  data: CreateFungibleData,1408  owner: CrossAccountId | string = sender.address,1409) {1410  return await usingApi(async (api) => {1411    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});14121413    const events = await submitTransactionAsync(sender, tx);1414    const result = getCreateItemResult(events);14151416    expect(result.success).to.be.true;1417    return result.itemId;1418  });1419}14201421export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1422  await usingApi(async (api) => {1423    const to = normalizeAccountId(owner);1424    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14251426    const events = await submitTransactionAsync(sender, tx);1427    expect(getGenericResult(events).success).to.be.true;1428  });1429}14301431export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1432  await usingApi(async (api) => {1433    const to = normalizeAccountId(owner);1434    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14351436    const events = await submitTransactionAsync(sender, tx);1437    const result = getCreateItemsResult(events);14381439    for (const res of result) {1440      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1441    }1442  });1443}14441445export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1446  await usingApi(async (api) => {1447    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);14481449    const events = await submitTransactionAsync(sender, tx);1450    const result = getCreateItemsResult(events);14511452    for (const res of result) {1453      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1454    }1455  });1456}14571458export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1459  let newItemId = 0;1460  await usingApi(async (api) => {1461    const to = normalizeAccountId(owner);1462    const itemCountBefore = await getLastTokenId(api, collectionId);1463    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14641465    let tx;1466    if (createMode === 'Fungible') {1467      const createData = {fungible: {value: 10}};1468      tx = api.tx.unique.createItem(collectionId, to, createData as any);1469    } else if (createMode === 'ReFungible') {1470      const createData = {refungible: {pieces: 100}};1471      tx = api.tx.unique.createItem(collectionId, to, createData as any);1472    } else {1473      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1474      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1475    }14761477    const events = await submitTransactionAsync(sender, tx);1478    const result = getCreateItemResult(events);14791480    const itemCountAfter = await getLastTokenId(api, collectionId);1481    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14821483    if (createMode === 'NFT') {1484      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1485    }14861487    // What to expect1488    // tslint:disable-next-line:no-unused-expression1489    expect(result.success).to.be.true;1490    if (createMode === 'Fungible') {1491      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1492    } else {1493      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1494    }1495    expect(collectionId).to.be.equal(result.collectionId);1496    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1497    expect(to).to.be.deep.equal(result.recipient);1498    newItemId = result.itemId;1499  });1500  return newItemId;1501}15021503export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1504  await usingApi(async (api) => {15051506    let tx;1507    if (createMode === 'NFT') {1508      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1509      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1510    } else {1511      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1512    }151315141515    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1516    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1517    const result = getCreateItemResult(events);15181519    expect(result.success).to.be.false;1520  });1521}15221523export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1524  let newItemId = 0;1525  await usingApi(async (api) => {1526    const to = normalizeAccountId(owner);1527    const itemCountBefore = await getLastTokenId(api, collectionId);1528    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);15291530    let tx;1531    if (createMode === 'Fungible') {1532      const createData = {fungible: {value: 10}};1533      tx = api.tx.unique.createItem(collectionId, to, createData as any);1534    } else if (createMode === 'ReFungible') {1535      const createData = {refungible: {pieces: 100}};1536      tx = api.tx.unique.createItem(collectionId, to, createData as any);1537    } else {1538      const createData = {nft: {}};1539      tx = api.tx.unique.createItem(collectionId, to, createData as any);1540    }15411542    const events = await executeTransaction(api, sender, tx);1543    const result = getCreateItemResult(events);15441545    const itemCountAfter = await getLastTokenId(api, collectionId);1546    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15471548    // What to expect1549    // tslint:disable-next-line:no-unused-expression1550    expect(result.success).to.be.true;1551    if (createMode === 'Fungible') {1552      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1553    } else {1554      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1555    }1556    expect(collectionId).to.be.equal(result.collectionId);1557    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1558    expect(to).to.be.deep.equal(result.recipient);1559    newItemId = result.itemId;1560  });1561  return newItemId;1562}15631564export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1565  const createData = {refungible: {pieces: amount}};1566  const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15671568  const events = await submitTransactionAsync(sender, tx);1569  return  getCreateItemResult(events);1570}15711572export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1573  await usingApi(async (api) => {1574    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15751576    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1577    const result = getCreateItemResult(events);15781579    expect(result.success).to.be.false;1580  });1581}15821583export async function setPublicAccessModeExpectSuccess(1584  sender: IKeyringPair, collectionId: number,1585  accessMode: 'Normal' | 'AllowList',1586) {1587  await usingApi(async (api) => {15881589    // Run the transaction1590    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1591    const events = await submitTransactionAsync(sender, tx);1592    const result = getGenericResult(events);15931594    // Get the collection1595    const collection = await queryCollectionExpectSuccess(api, collectionId);15961597    // What to expect1598    // tslint:disable-next-line:no-unused-expression1599    expect(result.success).to.be.true;1600    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1601  });1602}16031604export async function setPublicAccessModeExpectFail(1605  sender: IKeyringPair, collectionId: number,1606  accessMode: 'Normal' | 'AllowList',1607) {1608  await usingApi(async (api) => {16091610    // Run the transaction1611    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1612    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1613    const result = getGenericResult(events);16141615    // What to expect1616    // tslint:disable-next-line:no-unused-expression1617    expect(result.success).to.be.false;1618  });1619}16201621export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1622  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1623}16241625export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1626  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1627}16281629export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1630  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1631}16321633export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1634  await usingApi(async (api) => {16351636    // Run the transaction1637    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1638    const events = await submitTransactionAsync(sender, tx);1639    const result = getGenericResult(events);1640    expect(result.success).to.be.true;16411642    // Get the collection1643    const collection = await queryCollectionExpectSuccess(api, collectionId);16441645    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1646  });1647}16481649export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1650  await setMintPermissionExpectSuccess(sender, collectionId, true);1651}16521653export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1654  await usingApi(async (api) => {1655    // Run the transaction1656    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1657    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1658    const result = getCreateCollectionResult(events);1659    // tslint:disable-next-line:no-unused-expression1660    expect(result.success).to.be.false;1661  });1662}16631664export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1665  await usingApi(async (api) => {1666    // Run the transaction1667    const tx = api.tx.unique.setChainLimits(limits);1668    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1669    const result = getCreateCollectionResult(events);1670    // tslint:disable-next-line:no-unused-expression1671    expect(result.success).to.be.false;1672  });1673}16741675export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1676  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1677}16781679export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1680  await usingApi(async (api) => {1681    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16821683    // Run the transaction1684    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1685    const events = await submitTransactionAsync(sender, tx);1686    const result = getGenericResult(events);1687    expect(result.success).to.be.true;16881689    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1690  });1691}16921693export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1694  await usingApi(async (api) => {16951696    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;16971698    // Run the transaction1699    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1700    const events = await submitTransactionAsync(sender, tx);1701    const result = getGenericResult(events);1702    expect(result.success).to.be.true;17031704    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1705  });1706}17071708export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1709  await usingApi(async (api) => {17101711    // Run the transaction1712    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1713    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1714    const result = getGenericResult(events);17151716    // What to expect1717    // tslint:disable-next-line:no-unused-expression1718    expect(result.success).to.be.false;1719  });1720}17211722export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1723  await usingApi(async (api) => {1724    // Run the transaction1725    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1726    const events = await submitTransactionAsync(sender, tx);1727    const result = getGenericResult(events);17281729    // What to expect1730    // tslint:disable-next-line:no-unused-expression1731    expect(result.success).to.be.true;1732  });1733}17341735export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1736  await usingApi(async (api) => {1737    // Run the transaction1738    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1739    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1740    const result = getGenericResult(events);17411742    // What to expect1743    // tslint:disable-next-line:no-unused-expression1744    expect(result.success).to.be.false;1745  });1746}17471748export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1749  : Promise<UpDataStructsRpcCollection | null> => {1750  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1751};17521753export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1754  // set global object - collectionsCount1755  return (await api.rpc.unique.collectionStats()).created.toNumber();1756};17571758export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1759  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1760}17611762export const describe_xcm = (1763  process.env.RUN_XCM_TESTS1764    ? describe1765    : describe.skip1766);17671768export async function waitNewBlocks(blocksCount = 1): Promise<void> {1769  await usingApi(async (api) => {1770    const promise = new Promise<void>(async (resolve) => {1771      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1772        if (blocksCount > 0) {1773          blocksCount--;1774        } else {1775          unsubscribe();1776          resolve();1777        }1778      });1779    });1780    return promise;1781  });1782}17831784export async function waitEvent(1785  api: ApiPromise,1786  maxBlocksToWait: number,1787  eventSection: string,1788  eventMethod: string,1789): Promise<EventRecord | null> {17901791  const promise = new Promise<EventRecord | null>(async (resolve) => {1792    const unsubscribe = await api.rpc.chain.subscribeNewHeads(async header => {1793      const blockNumber = header.number.toHuman();1794      const blockHash = header.hash;1795      const eventIdStr = `${eventSection}.${eventMethod}`;1796      const waitLimitStr = `wait blocks remaining: ${maxBlocksToWait}`;17971798      console.log(`[Block #${blockNumber}] Waiting for event \`${eventIdStr}\` (${waitLimitStr})`);17991800      const apiAt = await api.at(blockHash);1801      const eventRecords = await apiAt.query.system.events();18021803      const neededEvent = eventRecords.find(r => {1804        return r.event.section == eventSection && r.event.method == eventMethod;1805      });18061807      if (neededEvent) {1808        console.log(`Event \`${eventIdStr}\` is found`);18091810        unsubscribe();1811        resolve(neededEvent);1812      } else if (maxBlocksToWait > 0) {1813        maxBlocksToWait--;1814      } else {1815        console.log(`Event \`${eventIdStr}\` is NOT found`);18161817        unsubscribe();1818        resolve(null);1819      }1820    });1821  });1822  return promise;1823}18241825export async function repartitionRFT(1826  api: ApiPromise,1827  collectionId: number,1828  sender: IKeyringPair,1829  tokenId: number,1830  amount: bigint,1831): Promise<boolean> {1832  const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1833  const events = await submitTransactionAsync(sender, tx);1834  const result = getGenericResult(events);18351836  return result.success;1837}18381839export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1840  let i: any = it;1841  if (opts.only) i = i.only;1842  else if (opts.skip) i = i.skip;1843  i(name, async () => {1844    await usingApi(async (api, privateKeyWrapper) => {1845      await cb({api, privateKeyWrapper});1846    });1847  });1848}18491850itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1851itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});18521853let accountSeed = 10000;18541855const keyringEth = new Keyring({type: 'ethereum'});1856const keyringEd25519 = new Keyring({type: 'ed25519'});1857const keyringSr25519 = new Keyring({type: 'sr25519'});18581859export function generateKeyringPair(type: 'ethereum' | 'sr25519' | 'ed25519' = 'sr25519') {1860  const privateKey = `0xDEADBEEF${(accountSeed++).toString(16).padStart(56, '0')}`;1861  if (type == 'sr25519') {1862    return keyringSr25519.addFromUri(privateKey);1863  } else if (type == 'ed25519') {1864    return keyringEd25519.addFromUri(privateKey);1865  }1866  return keyringEth.addFromUri(privateKey);1867}
modifiedtests/src/xcm/xcmQuartz.test.tsdiffbeforeafterboth
--- a/tests/src/xcm/xcmQuartz.test.ts
+++ b/tests/src/xcm/xcmQuartz.test.ts
@@ -26,6 +26,7 @@
 import {blake2AsHex} from '@polkadot/util-crypto';
 import waitNewBlocks from '../substrate/wait-new-blocks';
 import getBalance from '../substrate/get-balance';
+import {XcmV2TraitsOutcome, XcmV2TraitsError} from '../interfaces';
 
 chai.use(chaiAsPromised);
 const expect = chai.expect;
@@ -34,6 +35,7 @@
 const KARURA_CHAIN = 2000;
 const MOONRIVER_CHAIN = 2023;
 
+const RELAY_PORT = 9844;
 const KARURA_PORT = 9946;
 const MOONRIVER_PORT = 9947;
 
@@ -55,6 +57,10 @@
   return parachainApiOptions(MOONRIVER_PORT);
 }
 
+function relayOptions(): ApiOptions {
+  return parachainApiOptions(RELAY_PORT);
+}
+
 describe_xcm('Integration test: Exchanging tokens with Karura', () => {
   let alice: IKeyringPair;
   let randomAccount: IKeyringPair;
@@ -200,8 +206,8 @@
         const karFees = balanceKaruraTokenInit - balanceKaruraTokenMiddle;
         const qtzIncomeTransfer = balanceQuartzForeignTokenMiddle - balanceQuartzForeignTokenInit;
 
-        console.log('
-          [Quartz -> Karura] transaction fees on Karura: %s KAR',
+        console.log(
+          '[Quartz -> Karura] transaction fees on Karura: %s KAR',
           bigIntToDecimals(karFees, KARURA_DECIMALS),
         );
         console.log('[Quartz -> Karura] income %s QTZ', bigIntToDecimals(qtzIncomeTransfer));
@@ -281,10 +287,100 @@
       expect(qtzFees == 0n).to.be.true;
     });
   });
+});
+
+// These tests are relevant only when the foreign asset pallet is disabled
+describe('Integration test: Quartz rejects non-native tokens', () => {
+  let alice: IKeyringPair;
+
+  before(async () => {
+    await usingApi(async (api, privateKeyWrapper) => {
+      alice = privateKeyWrapper('//Alice');
+    });
+  });
+  
+  it('Quartz rejects tokens from the Relay', async () => {
+    await usingApi(async (api) => {
+      const destination = {
+        V1: {
+          parents: 0,
+          interior: {X1: {
+            Parachain: QUARTZ_CHAIN,
+          },
+          },
+        }};
+
+      const beneficiary = {
+        V1: {
+          parents: 0,
+          interior: {X1: {
+            AccountId32: {
+              network: 'Any',
+              id: alice.addressRaw,
+            },
+          }},
+        },
+      };
+
+      const assets = {
+        V1: [
+          {
+            id: {
+              Concrete: {
+                parents: 0,
+                interior: 'Here',
+              },
+            },
+            fun: {
+              Fungible: 50_000_000_000_000_000n,
+            },
+          },
+        ],
+      };
+
+      const feeAssetItem = 0;
+
+      const weightLimit = {
+        Limited: 5_000_000_000,
+      };
+
+      const tx = api.tx.xcmPallet.limitedReserveTransferAssets(destination, beneficiary, assets, feeAssetItem, weightLimit);
+      const events = await submitTransactionAsync(alice, tx);
+      const result = getGenericResult(events);
+      expect(result.success).to.be.true;
+    }, relayOptions());
+
+    await usingApi(async api => {
+      const maxWaitBlocks = 3;
+      const dmpQueueExecutedDownward = await waitEvent(
+        api,
+        maxWaitBlocks,
+        'dmpQueue',
+        'ExecutedDownward',
+      );
+
+      expect(
+        dmpQueueExecutedDownward != null,
+        '[Relay] dmpQueue.ExecutedDownward event is expected',
+      ).to.be.true;
+
+      const event = dmpQueueExecutedDownward!.event;
+      const outcome = event.data[1] as XcmV2TraitsOutcome;
+
+      expect(
+        outcome.isIncomplete,
+        '[Relay] The outcome of the XCM should be `Incomplete`',
+      ).to.be.true;
+
+      const incomplete = outcome.asIncomplete;
+      expect(
+        incomplete[1].toString() == 'AssetNotFound',
+        '[Relay] The XCM error should be `AssetNotFound`',
+      ).to.be.true;
+    });
+  });
 
   it('Quartz rejects KAR tokens from Karura', async () => {
-    // This test is relevant only when the foreign asset pallet is disabled
-
     await usingApi(async (api) => {
       const destination = {
         V1: {
@@ -295,7 +391,7 @@
               {
                 AccountId32: {
                   network: 'Any',
-                  id: randomAccount.addressRaw,
+                  id: alice.addressRaw,
                 },
               },
             ],
@@ -321,7 +417,15 @@
 
       expect(
         xcmpQueueFailEvent != null,
-        'Only native token is supported when the Foreign-Assets pallet is not connected',
+        '[Karura] xcmpQueue.FailEvent event is expected',
+      ).to.be.true;
+
+      const event = xcmpQueueFailEvent!.event;
+      const outcome = event.data[1] as XcmV2TraitsError;
+
+      expect(
+        outcome.isUntrustedReserveLocation,
+        '[Karura] The XCM error should be `UntrustedReserveLocation`',
       ).to.be.true;
     });
   });
modifiedtests/src/xcm/xcmUnique.test.tsdiffbeforeafterboth
--- a/tests/src/xcm/xcmUnique.test.ts
+++ b/tests/src/xcm/xcmUnique.test.ts
@@ -26,6 +26,7 @@
 import {blake2AsHex} from '@polkadot/util-crypto';
 import waitNewBlocks from '../substrate/wait-new-blocks';
 import getBalance from '../substrate/get-balance';
+import {XcmV2TraitsError, XcmV2TraitsOutcome} from '../interfaces';
 
 chai.use(chaiAsPromised);
 const expect = chai.expect;
@@ -34,6 +35,7 @@
 const ACALA_CHAIN = 2000;
 const MOONBEAM_CHAIN = 2004;
 
+const RELAY_PORT = 9844;
 const ACALA_PORT = 9946;
 const MOONBEAM_PORT = 9947;
 
@@ -55,6 +57,10 @@
   return parachainApiOptions(MOONBEAM_PORT);
 }
 
+function relayOptions(): ApiOptions {
+  return parachainApiOptions(RELAY_PORT);
+}
+
 describe_xcm('Integration test: Exchanging tokens with Acala', () => {
   let alice: IKeyringPair;
   let randomAccount: IKeyringPair;
@@ -281,10 +287,100 @@
       expect(unqFees == 0n).to.be.true;
     });
   });
+});
+
+// These tests are relevant only when the foreign asset pallet is disabled
+describe('Integration test: Unique rejects non-native tokens', () => {
+  let alice: IKeyringPair;
+
+  before(async () => {
+    await usingApi(async (api, privateKeyWrapper) => {
+      alice = privateKeyWrapper('//Alice');
+    });
+  });
+  
+  it('Unique rejects tokens from the Relay', async () => {
+    await usingApi(async (api) => {
+      const destination = {
+        V1: {
+          parents: 0,
+          interior: {X1: {
+            Parachain: UNIQUE_CHAIN,
+          },
+          },
+        }};
+
+      const beneficiary = {
+        V1: {
+          parents: 0,
+          interior: {X1: {
+            AccountId32: {
+              network: 'Any',
+              id: alice.addressRaw,
+            },
+          }},
+        },
+      };
+
+      const assets = {
+        V1: [
+          {
+            id: {
+              Concrete: {
+                parents: 0,
+                interior: 'Here',
+              },
+            },
+            fun: {
+              Fungible: 50_000_000_000_000_000n,
+            },
+          },
+        ],
+      };
+
+      const feeAssetItem = 0;
+
+      const weightLimit = {
+        Limited: 5_000_000_000,
+      };
+
+      const tx = api.tx.xcmPallet.limitedReserveTransferAssets(destination, beneficiary, assets, feeAssetItem, weightLimit);
+      const events = await submitTransactionAsync(alice, tx);
+      const result = getGenericResult(events);
+      expect(result.success).to.be.true;
+    }, relayOptions());
+
+    await usingApi(async api => {
+      const maxWaitBlocks = 3;
+      const dmpQueueExecutedDownward = await waitEvent(
+        api,
+        maxWaitBlocks,
+        'dmpQueue',
+        'ExecutedDownward',
+      );
+
+      expect(
+        dmpQueueExecutedDownward != null,
+        '[Relay] dmpQueue.ExecutedDownward event is expected',
+      ).to.be.true;
+
+      const event = dmpQueueExecutedDownward!.event;
+      const outcome = event.data[1] as XcmV2TraitsOutcome;
+
+      expect(
+        outcome.isIncomplete,
+        '[Relay] The outcome of the XCM should be `Incomplete`',
+      ).to.be.true;
+
+      const incomplete = outcome.asIncomplete;
+      expect(
+        incomplete[1].toString() == 'AssetNotFound',
+        '[Relay] The XCM error should be `AssetNotFound`',
+      ).to.be.true;
+    });
+  });
 
   it('Unique rejects ACA tokens from Acala', async () => {
-    // This test is relevant only when the foreign asset pallet is disabled
-
     await usingApi(async (api) => {
       const destination = {
         V1: {
@@ -295,7 +391,7 @@
               {
                 AccountId32: {
                   network: 'Any',
-                  id: randomAccount.addressRaw,
+                  id: alice.addressRaw,
                 },
               },
             ],
@@ -321,7 +417,15 @@
 
       expect(
         xcmpQueueFailEvent != null,
-        'Only native token is supported when the Foreign-Assets pallet is not connected',
+        '[Acala] xcmpQueue.FailEvent event is expected',
+      ).to.be.true;
+
+      const event = xcmpQueueFailEvent!.event;
+      const outcome = event.data[1] as XcmV2TraitsError;
+
+      expect(
+        outcome.isUntrustedReserveLocation,
+        '[Acala] The XCM error should be `UntrustedReserveLocation`',
       ).to.be.true;
     });
   });