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

difftreelog

source

tests/src/util/helpers.ts65.2 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import 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}