git.delta.rocks / unique-network / refs/commits / 081dbb6ae4fb

difftreelog

source

tests/src/util/helpers.ts62.9 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise} 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  AppPromotion = 'promotion',52}5354export async function isUnique(): Promise<boolean> {55  return usingApi(async api => {56    const chain = await api.rpc.system.chain();5758    return chain.eq('UNIQUE');59  });60}6162export async function isQuartz(): Promise<boolean> {63  return usingApi(async api => {64    const chain = await api.rpc.system.chain();65    66    return chain.eq('QUARTZ');67  });68}6970let modulesNames: any;71export function getModuleNames(api: ApiPromise): string[] {72  if (typeof modulesNames === 'undefined') 73    modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());74  return modulesNames;75}7677export async function missingRequiredPallets(requiredPallets: string[]): Promise<string[]> {78  return await usingApi(async api => {79    const pallets = getModuleNames(api);8081    return requiredPallets.filter(p => !pallets.includes(p));82  });83}8485export async function checkPalletsPresence(requiredPallets: string[]): Promise<boolean> {86  return (await missingRequiredPallets(requiredPallets)).length == 0;87}8889export async function requirePallets(mocha: Context, requiredPallets: string[]) {90  const missingPallets = await missingRequiredPallets(requiredPallets);9192  if (missingPallets.length > 0) {93    const skippingTestMsg = `\tSkipping test "${mocha.test?.title}".`;94    const missingPalletsMsg = `\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;95    const skipMsg = `${skippingTestMsg}\n${missingPalletsMsg}`;9697    console.error('\x1b[38:5:208m%s\x1b[0m', skipMsg);9899    mocha.skip();100  }101}102103export function bigIntToSub(api: ApiPromise, number: bigint) {104  return api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();105}106107export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {108  if (typeof input === 'string') {109    if (input.length >= 47) {110      return {Substrate: input};111    } else if (input.length === 42 && input.startsWith('0x')) {112      return {Ethereum: input.toLowerCase()};113    } else if (input.length === 40 && !input.startsWith('0x')) {114      return {Ethereum: '0x' + input.toLowerCase()};115    } else {116      throw new Error(`Unknown address format: "${input}"`);117    }118  }119  if ('address' in input) {120    return {Substrate: input.address};121  }122  if ('Ethereum' in input) {123    return {124      Ethereum: input.Ethereum.toLowerCase(),125    };126  } else if ('ethereum' in input) {127    return {128      Ethereum: (input as any).ethereum.toLowerCase(),129    };130  } else if ('Substrate' in input) {131    return input;132  } else if ('substrate' in input) {133    return {134      Substrate: (input as any).substrate,135    };136  }137138  // AccountId139  return {Substrate: input.toString()};140}141export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {142  input = normalizeAccountId(input);143  if ('Substrate' in input) {144    return input.Substrate;145  } else {146    return evmToAddress(input.Ethereum);147  }148}149150export const U128_MAX = (1n << 128n) - 1n;151152const MICROUNIQUE = 1_000_000_000_000n;153const MILLIUNIQUE = 1_000n * MICROUNIQUE;154const CENTIUNIQUE = 10n * MILLIUNIQUE;155export const UNIQUE = 100n * CENTIUNIQUE;156157interface GenericResult<T> {158  success: boolean;159  data: T | null;160}161162interface CreateCollectionResult {163  success: boolean;164  collectionId: number;165}166167interface CreateItemResult {168  success: boolean;169  collectionId: number;170  itemId: number;171  recipient?: CrossAccountId;172  amount?: number;173}174175interface DestroyItemResult {176  success: boolean;177  collectionId: number;178  itemId: number;179  owner: CrossAccountId;180  amount: number;181}182183interface TransferResult {184  collectionId: number;185  itemId: number;186  sender?: CrossAccountId;187  recipient?: CrossAccountId;188  value: bigint;189}190191interface IReFungibleOwner {192  fraction: BN;193  owner: number[];194}195196interface IGetMessage {197  checkMsgUnqMethod: string;198  checkMsgTrsMethod: string;199  checkMsgSysMethod: string;200}201202export interface IFungibleTokenDataType {203  value: number;204}205206export interface IChainLimits {207  collectionNumbersLimit: number;208  accountTokenOwnershipLimit: number;209  collectionsAdminsLimit: number;210  customDataLimit: number;211  nftSponsorTransferTimeout: number;212  fungibleSponsorTransferTimeout: number;213  refungibleSponsorTransferTimeout: number;214  //offchainSchemaLimit: number;215  //constOnChainSchemaLimit: number;216}217218export interface IReFungibleTokenDataType {219  owner: IReFungibleOwner[];220}221222export function uniqueEventMessage(events: EventRecord[]): IGetMessage {223  let checkMsgUnqMethod = '';224  let checkMsgTrsMethod = '';225  let checkMsgSysMethod = '';226  events.forEach(({event: {method, section}}) => {227    if (section === 'common') {228      checkMsgUnqMethod = method;229    } else if (section === 'treasury') {230      checkMsgTrsMethod = method;231    } else if (section === 'system') {232      checkMsgSysMethod = method;233    } else { return null; }234  });235  const result: IGetMessage = {236    checkMsgUnqMethod,237    checkMsgTrsMethod,238    checkMsgSysMethod,239  };240  return result;241}242243export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {244  const event = events.find(r => check(r.event));245  if (!event) return;246  return event.event as T;247}248249export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;250export function getGenericResult<T>(251  events: EventRecord[],252  expectSection: string,253  expectMethod: string,254  extractAction: (data: GenericEventData) => T255): GenericResult<T>;256257export function getGenericResult<T>(258  events: EventRecord[],259  expectSection?: string,260  expectMethod?: string,261  extractAction?: (data: GenericEventData) => T,262): GenericResult<T> {263  let success = false;264  let successData = null;265266  events.forEach(({event: {data, method, section}}) => {267    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);268    if (method === 'ExtrinsicSuccess') {269      success = true;270    } else if ((expectSection == section) && (expectMethod == method)) {271      successData = extractAction!(data as any);272    }273  });274275  const result: GenericResult<T> = {276    success,277    data: successData,278  };279  return result;280}281282export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {283  const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));284  const result: CreateCollectionResult = {285    success: genericResult.success,286    collectionId: genericResult.data ?? 0,287  };288  return result;289}290291export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {292  const results: CreateItemResult[] = [];293  294  const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {295    const collectionId = parseInt(data[0].toString(), 10);296    const itemId = parseInt(data[1].toString(), 10);297    const recipient = normalizeAccountId(data[2].toJSON() as any);298    const amount = parseInt(data[3].toString(), 10);299300    const itemRes: CreateItemResult = {301      success: true,302      collectionId,303      itemId,304      recipient,305      amount,306    };307308    results.push(itemRes);309    return results;310  });311312  if (!genericResult.success) return [];313  return results;314}315316export function getCreateItemResult(events: EventRecord[]): CreateItemResult {317  const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));318  319  if (genericResult.data == null) 320    return {321      success: genericResult.success,322      collectionId: 0,323      itemId: 0,324      amount: 0,325    };326  else 327    return {328      success: genericResult.success,329      collectionId: genericResult.data[0] as number,330      itemId: genericResult.data[1] as number,331      recipient: normalizeAccountId(genericResult.data![2] as any),332      amount: genericResult.data[3] as number,333    };334}335336export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {337  const results: DestroyItemResult[] = [];338  339  const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {340    const collectionId = parseInt(data[0].toString(), 10);341    const itemId = parseInt(data[1].toString(), 10);342    const owner = normalizeAccountId(data[2].toJSON() as any);343    const amount = parseInt(data[3].toString(), 10);344345    const itemRes: DestroyItemResult = {346      success: true,347      collectionId,348      itemId,349      owner,350      amount,351    };352353    results.push(itemRes);354    return results;355  });356357  if (!genericResult.success) return [];358  return results;359}360361export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {362  for (const {event} of events) {363    if (api.events.common.Transfer.is(event)) {364      const [collection, token, sender, recipient, value] = event.data;365      return {366        collectionId: collection.toNumber(),367        itemId: token.toNumber(),368        sender: normalizeAccountId(sender.toJSON() as any),369        recipient: normalizeAccountId(recipient.toJSON() as any),370        value: value.toBigInt(),371      };372    }373  }374  throw new Error('no transfer event');375}376377interface Nft {378  type: 'NFT';379}380381interface Fungible {382  type: 'Fungible';383  decimalPoints: number;384}385386interface ReFungible {387  type: 'ReFungible';388}389390export type CollectionMode = Nft | Fungible | ReFungible;391392export type Property = {393  key: any,394  value: any,395};396397type Permission = {398  mutable: boolean;399  collectionAdmin: boolean;400  tokenOwner: boolean;401}402403type PropertyPermission = {404  key: any;405  permission: Permission;406}407408export type CreateCollectionParams = {409  mode: CollectionMode,410  name: string,411  description: string,412  tokenPrefix: string,413  properties?: Array<Property>,414  propPerm?: Array<PropertyPermission>415};416417const defaultCreateCollectionParams: CreateCollectionParams = {418  description: 'description',419  mode: {type: 'NFT'},420  name: 'name',421  tokenPrefix: 'prefix',422};423424export async function425createCollection(426  api: ApiPromise,427  sender: IKeyringPair,428  params: Partial<CreateCollectionParams> = {},429): Promise<CreateCollectionResult> {430  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};431432  let modeprm = {};433  if (mode.type === 'NFT') {434    modeprm = {nft: null};435  } else if (mode.type === 'Fungible') {436    modeprm = {fungible: mode.decimalPoints};437  } else if (mode.type === 'ReFungible') {438    modeprm = {refungible: null};439  }440441  const tx = api.tx.unique.createCollectionEx({442    name: strToUTF16(name),443    description: strToUTF16(description),444    tokenPrefix: strToUTF16(tokenPrefix),445    mode: modeprm as any,446  });447  const events = await executeTransaction(api, sender, tx);448  return getCreateCollectionResult(events);449}450451export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {452  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};453454  let collectionId = 0;455  await usingApi(async (api, privateKeyWrapper) => {456    // Get number of collections before the transaction457    const collectionCountBefore = await getCreatedCollectionCount(api);458459    // Run the CreateCollection transaction460    const alicePrivateKey = privateKeyWrapper('//Alice');461462    const result = await createCollection(api, alicePrivateKey, params);463464    // Get number of collections after the transaction465    const collectionCountAfter = await getCreatedCollectionCount(api);466467    // Get the collection468    const collection = await queryCollectionExpectSuccess(api, result.collectionId);469470    // What to expect471    // tslint:disable-next-line:no-unused-expression472    expect(result.success).to.be.true;473    expect(result.collectionId).to.be.equal(collectionCountAfter);474    // tslint:disable-next-line:no-unused-expression475    expect(collection).to.be.not.null;476    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');477    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));478    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);479    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);480    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);481482    collectionId = result.collectionId;483  });484485  return collectionId;486}487488export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {489  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};490491  let collectionId = 0;492  await usingApi(async (api, privateKeyWrapper) => {493    // Get number of collections before the transaction494    const collectionCountBefore = await getCreatedCollectionCount(api);495496    // Run the CreateCollection transaction497    const alicePrivateKey = privateKeyWrapper('//Alice');498499    let modeprm = {};500    if (mode.type === 'NFT') {501      modeprm = {nft: null};502    } else if (mode.type === 'Fungible') {503      modeprm = {fungible: mode.decimalPoints};504    } else if (mode.type === 'ReFungible') {505      modeprm = {refungible: null};506    }507508    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});509    const events = await submitTransactionAsync(alicePrivateKey, tx);510    const result = getCreateCollectionResult(events);511512    // Get number of collections after the transaction513    const collectionCountAfter = await getCreatedCollectionCount(api);514515    // Get the collection516    const collection = await queryCollectionExpectSuccess(api, result.collectionId);517518    // What to expect519    // tslint:disable-next-line:no-unused-expression520    expect(result.success).to.be.true;521    expect(result.collectionId).to.be.equal(collectionCountAfter);522    // tslint:disable-next-line:no-unused-expression523    expect(collection).to.be.not.null;524    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');525    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));526    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);527    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);528    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);529530531    collectionId = result.collectionId;532  });533534  return collectionId;535}536537export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {538  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};539540  await usingApi(async (api, privateKeyWrapper) => {541    // Get number of collections before the transaction542    const collectionCountBefore = await getCreatedCollectionCount(api);543544    // Run the CreateCollection transaction545    const alicePrivateKey = privateKeyWrapper('//Alice');546547    let modeprm = {};548    if (mode.type === 'NFT') {549      modeprm = {nft: null};550    } else if (mode.type === 'Fungible') {551      modeprm = {fungible: mode.decimalPoints};552    } else if (mode.type === 'ReFungible') {553      modeprm = {refungible: null};554    }555556    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});557    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;558559560    // Get number of collections after the transaction561    const collectionCountAfter = await getCreatedCollectionCount(api);562563    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');564  });565}566567export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {568  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};569570  let modeprm = {};571  if (mode.type === 'NFT') {572    modeprm = {nft: null};573  } else if (mode.type === 'Fungible') {574    modeprm = {fungible: mode.decimalPoints};575  } else if (mode.type === 'ReFungible') {576    modeprm = {refungible: null};577  }578579  await usingApi(async (api, privateKeyWrapper) => {580    // Get number of collections before the transaction581    const collectionCountBefore = await getCreatedCollectionCount(api);582583    // Run the CreateCollection transaction584    const alicePrivateKey = privateKeyWrapper('//Alice');585    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});586    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;587588    // Get number of collections after the transaction589    const collectionCountAfter = await getCreatedCollectionCount(api);590591    // What to expect592    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');593  });594}595596export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {597  let bal = 0n;598  let unused;599  do {600    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;601    unused = privateKeyWrapper(`//${randomSeed}`);602    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();603  } while (bal !== 0n);604  return unused;605}606607export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {608  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();609}610611export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {612  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));613}614615export async function findNotExistingCollection(api: ApiPromise): Promise<number> {616  const totalNumber = await getCreatedCollectionCount(api);617  const newCollection: number = totalNumber + 1;618  return newCollection;619}620621function getDestroyResult(events: EventRecord[]): boolean {622  let success = false;623  events.forEach(({event: {method}}) => {624    if (method == 'ExtrinsicSuccess') {625      success = true;626    }627  });628  return success;629}630631export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {632  await usingApi(async (api, privateKeyWrapper) => {633    // Run the DestroyCollection transaction634    const alicePrivateKey = privateKeyWrapper(senderSeed);635    const tx = api.tx.unique.destroyCollection(collectionId);636    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;637  });638}639640export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {641  await usingApi(async (api, privateKeyWrapper) => {642    // Run the DestroyCollection transaction643    const alicePrivateKey = privateKeyWrapper(senderSeed);644    const tx = api.tx.unique.destroyCollection(collectionId);645    const events = await submitTransactionAsync(alicePrivateKey, tx);646    const result = getDestroyResult(events);647    expect(result).to.be.true;648649    // What to expect650    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;651  });652}653654export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {655  await usingApi(async (api) => {656    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);657    const events = await submitTransactionAsync(sender, tx);658    const result = getGenericResult(events);659660    expect(result.success).to.be.true;661  });662}663664export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {665  await usingApi(async(api) => {666    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);667    const events = await submitTransactionAsync(sender, tx);668    const result = getGenericResult(events);669670    expect(result.success).to.be.true;671  });672};673674export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {675  await usingApi(async (api) => {676    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);677    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;678    const result = getGenericResult(events);679680    expect(result.success).to.be.false;681  });682}683684export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {685  await usingApi(async (api, privateKeyWrapper) => {686687    // Run the transaction688    const senderPrivateKey = privateKeyWrapper(sender);689    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);690    const events = await submitTransactionAsync(senderPrivateKey, tx);691    const result = getGenericResult(events);692693    // Get the collection694    const collection = await queryCollectionExpectSuccess(api, collectionId);695696    // What to expect697    expect(result.success).to.be.true;698    expect(collection.sponsorship.toJSON()).to.deep.equal({699      unconfirmed: sponsor,700    });701  });702}703704export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {705  await usingApi(async (api, privateKeyWrapper) => {706707    // Run the transaction708    const alicePrivateKey = privateKeyWrapper(sender);709    const tx = api.tx.unique.removeCollectionSponsor(collectionId);710    const events = await submitTransactionAsync(alicePrivateKey, tx);711    const result = getGenericResult(events);712713    // Get the collection714    const collection = await queryCollectionExpectSuccess(api, collectionId);715716    // What to expect717    expect(result.success).to.be.true;718    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});719  });720}721722export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {723  await usingApi(async (api, privateKeyWrapper) => {724725    // Run the transaction726    const alicePrivateKey = privateKeyWrapper(senderSeed);727    const tx = api.tx.unique.removeCollectionSponsor(collectionId);728    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;729  });730}731732export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {733  await usingApi(async (api, privateKeyWrapper) => {734735    // Run the transaction736    const alicePrivateKey = privateKeyWrapper(senderSeed);737    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);738    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;739  });740}741742export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {743  await usingApi(async (api, privateKeyWrapper) => {744745    // Run the transaction746    const sender = privateKeyWrapper(senderSeed);747    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);748  });749}750751export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {752  await usingApi(async (api, privateKeyWrapper) => {753754    // Run the transaction755    const tx = api.tx.unique.confirmSponsorship(collectionId);756    const events = await submitTransactionAsync(sender, tx);757    const result = getGenericResult(events);758759    // Get the collection760    const collection = await queryCollectionExpectSuccess(api, collectionId);761762    // What to expect763    expect(result.success).to.be.true;764    expect(collection.sponsorship.toJSON()).to.be.deep.equal({765      confirmed: sender.address,766    });767  });768}769770771export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {772  await usingApi(async (api, privateKeyWrapper) => {773774    // Run the transaction775    const sender = privateKeyWrapper(senderSeed);776    const tx = api.tx.unique.confirmSponsorship(collectionId);777    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;778  });779}780781export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {782  await usingApi(async (api) => {783    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);784    const events = await submitTransactionAsync(sender, tx);785    const result = getGenericResult(events);786787    expect(result.success).to.be.true;788  });789}790791export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {792  await usingApi(async (api) => {793    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);794    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;795    const result = getGenericResult(events);796797    expect(result.success).to.be.false;798  });799}800801export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {802803  await usingApi(async (api) => {804805    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);806    const events = await submitTransactionAsync(sender, tx);807    const result = getGenericResult(events);808809    expect(result.success).to.be.true;810  });811}812813export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {814815  await usingApi(async (api) => {816817    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);818    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;819    const result = getGenericResult(events);820821    expect(result.success).to.be.false;822  });823}824825export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {826  await usingApi(async (api) => {827    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);828    const events = await submitTransactionAsync(sender, tx);829    const result = getGenericResult(events);830831    expect(result.success).to.be.true;832  });833}834835export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {836  await usingApi(async (api) => {837    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);838    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;839    const result = getGenericResult(events);840841    expect(result.success).to.be.false;842  });843}844845export async function getNextSponsored(846  api: ApiPromise,847  collectionId: number,848  account: string | CrossAccountId,849  tokenId: number,850): Promise<number> {851  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));852}853854export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {855  await usingApi(async (api) => {856    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);857    const events = await submitTransactionAsync(sender, tx);858    const result = getGenericResult(events);859860    expect(result.success).to.be.true;861  });862}863864export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {865  let allowlisted = false;866  await usingApi(async (api) => {867    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;868  });869  return allowlisted;870}871872export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {873  await usingApi(async (api) => {874    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());875    const events = await submitTransactionAsync(sender, tx);876    const result = getGenericResult(events);877878    expect(result.success).to.be.true;879  });880}881882export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {883  await usingApi(async (api) => {884    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());885    const events = await submitTransactionAsync(sender, tx);886    const result = getGenericResult(events);887888    expect(result.success).to.be.true;889  });890}891892export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {893  await usingApi(async (api) => {894    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());895    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;896    const result = getGenericResult(events);897898    expect(result.success).to.be.false;899  });900}901902export interface CreateFungibleData {903  readonly Value: bigint;904}905906export interface CreateReFungibleData { }907export interface CreateNftData { }908909export type CreateItemData = {910  NFT: CreateNftData;911} | {912  Fungible: CreateFungibleData;913} | {914  ReFungible: CreateReFungibleData;915};916917export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {918  const tx = api.tx.unique.burnItem(collectionId, tokenId, value);919  const events = await submitTransactionAsync(sender, tx);920  return getGenericResult(events).success;921}922923export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {924  await usingApi(async (api) => {925    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);926    // if burning token by admin - use adminButnItemExpectSuccess927    expect(balanceBefore >= BigInt(value)).to.be.true;928929    expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;930931    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);932    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);933  });934}935936export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {937  await usingApi(async (api) => {938    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);939940    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;941    const result = getCreateCollectionResult(events);942    // tslint:disable-next-line:no-unused-expression943    expect(result.success).to.be.false;944  });945}946947export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {948  await usingApi(async (api) => {949    const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);950    const events = await submitTransactionAsync(sender, tx);951    return getGenericResult(events).success;952  });953}954955export async function956approve(957  api: ApiPromise,958  collectionId: number,959  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,960) {961  const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);962  const events = await submitTransactionAsync(owner, approveUniqueTx);963  return getGenericResult(events).success;964}965966export async function967approveExpectSuccess(968  collectionId: number,969  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,970) {971  await usingApi(async (api: ApiPromise) => {972    const result = await approve(api, collectionId, tokenId, owner, approved, amount);973    expect(result).to.be.true;974975    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));976  });977}978979export async function adminApproveFromExpectSuccess(980  collectionId: number,981  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,982) {983  await usingApi(async (api: ApiPromise) => {984    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);985    const events = await submitTransactionAsync(admin, approveUniqueTx);986    const result = getGenericResult(events);987    expect(result.success).to.be.true;988989    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));990  });991}992993export async function994transferFrom(995  api: ApiPromise,996  collectionId: number,997  tokenId: number,998  accountApproved: IKeyringPair,999  accountFrom: IKeyringPair | CrossAccountId,1000  accountTo: IKeyringPair | CrossAccountId,1001  value: number | bigint,1002) {1003  const from = normalizeAccountId(accountFrom);1004  const to = normalizeAccountId(accountTo);1005  const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);1006  const events = await submitTransactionAsync(accountApproved, transferFromTx);1007  return getGenericResult(events).success;1008}10091010export async function1011transferFromExpectSuccess(1012  collectionId: number,1013  tokenId: number,1014  accountApproved: IKeyringPair,1015  accountFrom: IKeyringPair | CrossAccountId,1016  accountTo: IKeyringPair | CrossAccountId,1017  value: number | bigint = 1,1018  type = 'NFT',1019) {1020  await usingApi(async (api: ApiPromise) => {1021    const from = normalizeAccountId(accountFrom);1022    const to = normalizeAccountId(accountTo);1023    let balanceBefore = 0n;1024    if (type === 'Fungible' || type === 'ReFungible') {1025      balanceBefore = await getBalance(api, collectionId, to, tokenId);1026    }1027    expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;1028    if (type === 'NFT') {1029      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1030    }1031    if (type === 'Fungible') {1032      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1033      if (JSON.stringify(to) !== JSON.stringify(from)) {1034        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1035      } else {1036        expect(balanceAfter).to.be.equal(balanceBefore);1037      }1038    }1039    if (type === 'ReFungible') {1040      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1041    }1042  });1043}10441045export async function1046transferFromExpectFail(1047  collectionId: number,1048  tokenId: number,1049  accountApproved: IKeyringPair,1050  accountFrom: IKeyringPair,1051  accountTo: IKeyringPair,1052  value: number | bigint = 1,1053) {1054  await usingApi(async (api: ApiPromise) => {1055    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1056    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1057    const result = getCreateCollectionResult(events);1058    // tslint:disable-next-line:no-unused-expression1059    expect(result.success).to.be.false;1060  });1061}10621063/* eslint no-async-promise-executor: "off" */1064export async function getBlockNumber(api: ApiPromise): Promise<number> {1065  return new Promise<number>(async (resolve) => {1066    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1067      unsubscribe();1068      resolve(head.number.toNumber());1069    });1070  });1071}10721073export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1074  await usingApi(async (api) => {1075    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1076    const events = await submitTransactionAsync(sender, changeAdminTx);1077    const result = getCreateCollectionResult(events);1078    expect(result.success).to.be.true;1079  });1080}10811082export async function adminApproveFromExpectFail(1083  collectionId: number,1084  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1085) {1086  await usingApi(async (api: ApiPromise) => {1087    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1088    const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1089    const result = getGenericResult(events);1090    expect(result.success).to.be.false;1091  });1092}10931094export async function1095getFreeBalance(account: IKeyringPair): Promise<bigint> {1096  let balance = 0n;1097  await usingApi(async (api) => {1098    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1099  });11001101  return balance;1102}11031104export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1105  const tx = api.tx.balances.transfer(target, amount);1106  const events = await submitTransactionAsync(source, tx);1107  const result = getGenericResult(events);1108  expect(result.success).to.be.true;1109}11101111export async function1112scheduleExpectSuccess(1113  operationTx: any,1114  sender: IKeyringPair,1115  blockSchedule: number,1116  scheduledId: string,1117  period = 1,1118  repetitions = 1,1119) {1120  await usingApi(async (api: ApiPromise) => {1121    const blockNumber: number | undefined = await getBlockNumber(api);1122    const expectedBlockNumber = blockNumber + blockSchedule;11231124    expect(blockNumber).to.be.greaterThan(0);1125    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1126      scheduledId,1127      expectedBlockNumber, 1128      repetitions > 1 ? [period, repetitions] : null, 1129      0, 1130      {Value: operationTx as any},1131    );11321133    const events = await submitTransactionAsync(sender, scheduleTx);1134    expect(getGenericResult(events).success).to.be.true;1135  });1136}11371138export async function1139scheduleExpectFailure(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 ? null : [period, repetitions], 1156      0, 1157      {Value: operationTx as any},1158    );11591160    //const events = 1161    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1162    //expect(getGenericResult(events).success).to.be.false;1163  });1164}11651166export async function1167scheduleTransferAndWaitExpectSuccess(1168  collectionId: number,1169  tokenId: number,1170  sender: IKeyringPair,1171  recipient: IKeyringPair,1172  value: number | bigint = 1,1173  blockSchedule: number,1174  scheduledId: string,1175) {1176  await usingApi(async (api: ApiPromise) => {1177    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);11781179    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();11801181    // sleep for n + 1 blocks1182    await waitNewBlocks(blockSchedule + 1);11831184    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();11851186    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1187    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1188  });1189}11901191export async function1192scheduleTransferExpectSuccess(1193  collectionId: number,1194  tokenId: number,1195  sender: IKeyringPair,1196  recipient: IKeyringPair,1197  value: number | bigint = 1,1198  blockSchedule: number,1199  scheduledId: string,1200) {1201  await usingApi(async (api: ApiPromise) => {1202    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);12031204    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);12051206    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1207  });1208}12091210export async function1211scheduleTransferFundsPeriodicExpectSuccess(1212  amount: bigint,1213  sender: IKeyringPair,1214  recipient: IKeyringPair,1215  blockSchedule: number,1216  scheduledId: string,1217  period: number,1218  repetitions: number,1219) {1220  await usingApi(async (api: ApiPromise) => {1221    const transferTx = api.tx.balances.transfer(recipient.address, amount);12221223    const balanceBefore = await getFreeBalance(recipient);1224    1225    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);12261227    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1228  });1229}12301231export async function1232transfer(1233  api: ApiPromise,1234  collectionId: number,1235  tokenId: number,1236  sender: IKeyringPair,1237  recipient: IKeyringPair | CrossAccountId,1238  value: number | bigint,1239) : Promise<boolean> {1240  const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1241  const events = await executeTransaction(api, sender, transferTx);1242  return getGenericResult(events).success;1243}12441245export async function1246transferExpectSuccess(1247  collectionId: number,1248  tokenId: number,1249  sender: IKeyringPair,1250  recipient: IKeyringPair | CrossAccountId,1251  value: number | bigint = 1,1252  type = 'NFT',1253) {1254  await usingApi(async (api: ApiPromise) => {1255    const from = normalizeAccountId(sender);1256    const to = normalizeAccountId(recipient);12571258    let balanceBefore = 0n;1259    if (type === 'Fungible' || type === 'ReFungible') {1260      balanceBefore = await getBalance(api, collectionId, to, tokenId);1261    }12621263    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1264    const events = await executeTransaction(api, sender, transferTx);1265    const result = getTransferResult(api, events);12661267    expect(result.collectionId).to.be.equal(collectionId);1268    expect(result.itemId).to.be.equal(tokenId);1269    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1270    expect(result.recipient).to.be.deep.equal(to);1271    expect(result.value).to.be.equal(BigInt(value));12721273    if (type === 'NFT') {1274      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1275    }1276    if (type === 'Fungible' || type === 'ReFungible') {1277      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1278      if (JSON.stringify(to) !== JSON.stringify(from)) {1279        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1280      } else {1281        expect(balanceAfter).to.be.equal(balanceBefore);1282      }1283    }1284  });1285}12861287export async function1288transferExpectFailure(1289  collectionId: number,1290  tokenId: number,1291  sender: IKeyringPair,1292  recipient: IKeyringPair | CrossAccountId,1293  value: number | bigint = 1,1294) {1295  await usingApi(async (api: ApiPromise) => {1296    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1297    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1298    const result = getGenericResult(events);1299    // if (events && Array.isArray(events)) {1300    //   const result = getCreateCollectionResult(events);1301    // tslint:disable-next-line:no-unused-expression1302    expect(result.success).to.be.false;1303    //}1304  });1305}13061307export async function1308approveExpectFail(1309  collectionId: number,1310  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1311) {1312  await usingApi(async (api: ApiPromise) => {1313    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1314    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1315    const result = getCreateCollectionResult(events);1316    // tslint:disable-next-line:no-unused-expression1317    expect(result.success).to.be.false;1318  });1319}13201321export async function getBalance(1322  api: ApiPromise,1323  collectionId: number,1324  owner: string | CrossAccountId | IKeyringPair,1325  token: number,1326): Promise<bigint> {1327  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1328}1329export async function getTokenOwner(1330  api: ApiPromise,1331  collectionId: number,1332  token: number,1333): Promise<CrossAccountId> {1334  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1335  if (owner == null) throw new Error('owner == null');1336  return normalizeAccountId(owner);1337}1338export async function getTopmostTokenOwner(1339  api: ApiPromise,1340  collectionId: number,1341  token: number,1342): Promise<CrossAccountId> {1343  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1344  if (owner == null) throw new Error('owner == null');1345  return normalizeAccountId(owner);1346}1347export async function getTokenChildren(1348  api: ApiPromise,1349  collectionId: number,1350  tokenId: number,1351): Promise<UpDataStructsTokenChild[]> {1352  return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1353}1354export async function isTokenExists(1355  api: ApiPromise,1356  collectionId: number,1357  token: number,1358): Promise<boolean> {1359  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1360}1361export async function getLastTokenId(1362  api: ApiPromise,1363  collectionId: number,1364): Promise<number> {1365  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1366}1367export async function getAdminList(1368  api: ApiPromise,1369  collectionId: number,1370): Promise<string[]> {1371  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1372}1373export async function getTokenProperties(1374  api: ApiPromise,1375  collectionId: number,1376  tokenId: number,1377  propertyKeys: string[],1378): Promise<UpDataStructsProperty[]> {1379  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1380}13811382export async function createFungibleItemExpectSuccess(1383  sender: IKeyringPair,1384  collectionId: number,1385  data: CreateFungibleData,1386  owner: CrossAccountId | string = sender.address,1387) {1388  return await usingApi(async (api) => {1389    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});13901391    const events = await submitTransactionAsync(sender, tx);1392    const result = getCreateItemResult(events);13931394    expect(result.success).to.be.true;1395    return result.itemId;1396  });1397}13981399export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1400  await usingApi(async (api) => {1401    const to = normalizeAccountId(owner);1402    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14031404    const events = await submitTransactionAsync(sender, tx);1405    expect(getGenericResult(events).success).to.be.true;1406  });1407}14081409export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1410  await usingApi(async (api) => {1411    const to = normalizeAccountId(owner);1412    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14131414    const events = await submitTransactionAsync(sender, tx);1415    const result = getCreateItemsResult(events);14161417    for (const res of result) {1418      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1419    }1420  });1421}14221423export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1424  await usingApi(async (api) => {1425    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);14261427    const events = await submitTransactionAsync(sender, tx);1428    const result = getCreateItemsResult(events);14291430    for (const res of result) {1431      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1432    }1433  });1434}14351436export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1437  let newItemId = 0;1438  await usingApi(async (api) => {1439    const to = normalizeAccountId(owner);1440    const itemCountBefore = await getLastTokenId(api, collectionId);1441    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14421443    let tx;1444    if (createMode === 'Fungible') {1445      const createData = {fungible: {value: 10}};1446      tx = api.tx.unique.createItem(collectionId, to, createData as any);1447    } else if (createMode === 'ReFungible') {1448      const createData = {refungible: {pieces: 100}};1449      tx = api.tx.unique.createItem(collectionId, to, createData as any);1450    } else {1451      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1452      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1453    }14541455    const events = await submitTransactionAsync(sender, tx);1456    const result = getCreateItemResult(events);14571458    const itemCountAfter = await getLastTokenId(api, collectionId);1459    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14601461    if (createMode === 'NFT') {1462      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1463    }14641465    // What to expect1466    // tslint:disable-next-line:no-unused-expression1467    expect(result.success).to.be.true;1468    if (createMode === 'Fungible') {1469      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1470    } else {1471      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1472    }1473    expect(collectionId).to.be.equal(result.collectionId);1474    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1475    expect(to).to.be.deep.equal(result.recipient);1476    newItemId = result.itemId;1477  });1478  return newItemId;1479}14801481export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1482  await usingApi(async (api) => {14831484    let tx;1485    if (createMode === 'NFT') {1486      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1487      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1488    } else {1489      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1490    }149114921493    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1494    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1495    const result = getCreateItemResult(events);14961497    expect(result.success).to.be.false;1498  });1499}15001501export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1502  let newItemId = 0;1503  await usingApi(async (api) => {1504    const to = normalizeAccountId(owner);1505    const itemCountBefore = await getLastTokenId(api, collectionId);1506    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);15071508    let tx;1509    if (createMode === 'Fungible') {1510      const createData = {fungible: {value: 10}};1511      tx = api.tx.unique.createItem(collectionId, to, createData as any);1512    } else if (createMode === 'ReFungible') {1513      const createData = {refungible: {pieces: 100}};1514      tx = api.tx.unique.createItem(collectionId, to, createData as any);1515    } else {1516      const createData = {nft: {}};1517      tx = api.tx.unique.createItem(collectionId, to, createData as any);1518    }15191520    const events = await executeTransaction(api, sender, tx);1521    const result = getCreateItemResult(events);15221523    const itemCountAfter = await getLastTokenId(api, collectionId);1524    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15251526    // What to expect1527    // tslint:disable-next-line:no-unused-expression1528    expect(result.success).to.be.true;1529    if (createMode === 'Fungible') {1530      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1531    } else {1532      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1533    }1534    expect(collectionId).to.be.equal(result.collectionId);1535    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1536    expect(to).to.be.deep.equal(result.recipient);1537    newItemId = result.itemId;1538  });1539  return newItemId;1540}15411542export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1543  const createData = {refungible: {pieces: amount}};1544  const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15451546  const events = await submitTransactionAsync(sender, tx);1547  return  getCreateItemResult(events);1548}15491550export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1551  await usingApi(async (api) => {1552    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15531554    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1555    const result = getCreateItemResult(events);15561557    expect(result.success).to.be.false;1558  });1559}15601561export async function setPublicAccessModeExpectSuccess(1562  sender: IKeyringPair, collectionId: number,1563  accessMode: 'Normal' | 'AllowList',1564) {1565  await usingApi(async (api) => {15661567    // Run the transaction1568    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1569    const events = await submitTransactionAsync(sender, tx);1570    const result = getGenericResult(events);15711572    // Get the collection1573    const collection = await queryCollectionExpectSuccess(api, collectionId);15741575    // What to expect1576    // tslint:disable-next-line:no-unused-expression1577    expect(result.success).to.be.true;1578    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1579  });1580}15811582export async function setPublicAccessModeExpectFail(1583  sender: IKeyringPair, collectionId: number,1584  accessMode: 'Normal' | 'AllowList',1585) {1586  await usingApi(async (api) => {15871588    // Run the transaction1589    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1590    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1591    const result = getGenericResult(events);15921593    // What to expect1594    // tslint:disable-next-line:no-unused-expression1595    expect(result.success).to.be.false;1596  });1597}15981599export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1600  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1601}16021603export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1604  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1605}16061607export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1608  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1609}16101611export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1612  await usingApi(async (api) => {16131614    // Run the transaction1615    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1616    const events = await submitTransactionAsync(sender, tx);1617    const result = getGenericResult(events);1618    expect(result.success).to.be.true;16191620    // Get the collection1621    const collection = await queryCollectionExpectSuccess(api, collectionId);16221623    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1624  });1625}16261627export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1628  await setMintPermissionExpectSuccess(sender, collectionId, true);1629}16301631export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1632  await usingApi(async (api) => {1633    // Run the transaction1634    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1635    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1636    const result = getCreateCollectionResult(events);1637    // tslint:disable-next-line:no-unused-expression1638    expect(result.success).to.be.false;1639  });1640}16411642export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1643  await usingApi(async (api) => {1644    // Run the transaction1645    const tx = api.tx.unique.setChainLimits(limits);1646    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1647    const result = getCreateCollectionResult(events);1648    // tslint:disable-next-line:no-unused-expression1649    expect(result.success).to.be.false;1650  });1651}16521653export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1654  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1655}16561657export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1658  await usingApi(async (api) => {1659    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16601661    // Run the transaction1662    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1663    const events = await submitTransactionAsync(sender, tx);1664    const result = getGenericResult(events);1665    expect(result.success).to.be.true;16661667    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1668  });1669}16701671export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1672  await usingApi(async (api) => {16731674    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;16751676    // Run the transaction1677    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1678    const events = await submitTransactionAsync(sender, tx);1679    const result = getGenericResult(events);1680    expect(result.success).to.be.true;16811682    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1683  });1684}16851686export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1687  await usingApi(async (api) => {16881689    // Run the transaction1690    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1691    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1692    const result = getGenericResult(events);16931694    // What to expect1695    // tslint:disable-next-line:no-unused-expression1696    expect(result.success).to.be.false;1697  });1698}16991700export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1701  await usingApi(async (api) => {1702    // Run the transaction1703    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1704    const events = await submitTransactionAsync(sender, tx);1705    const result = getGenericResult(events);17061707    // What to expect1708    // tslint:disable-next-line:no-unused-expression1709    expect(result.success).to.be.true;1710  });1711}17121713export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1714  await usingApi(async (api) => {1715    // Run the transaction1716    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1717    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1718    const result = getGenericResult(events);17191720    // What to expect1721    // tslint:disable-next-line:no-unused-expression1722    expect(result.success).to.be.false;1723  });1724}17251726export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1727  : Promise<UpDataStructsRpcCollection | null> => {1728  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1729};17301731export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1732  // set global object - collectionsCount1733  return (await api.rpc.unique.collectionStats()).created.toNumber();1734};17351736export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1737  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1738}17391740export async function waitNewBlocks(blocksCount = 1): Promise<void> {1741  await usingApi(async (api) => {1742    const promise = new Promise<void>(async (resolve) => {1743      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1744        if (blocksCount > 0) {1745          blocksCount--;1746        } else {1747          unsubscribe();1748          resolve();1749        }1750      });1751    });1752    return promise;1753  });1754}17551756export async function repartitionRFT(1757  api: ApiPromise,1758  collectionId: number,1759  sender: IKeyringPair,1760  tokenId: number,1761  amount: bigint,1762): Promise<boolean> {1763  const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1764  const events = await submitTransactionAsync(sender, tx);1765  const result = getGenericResult(events);17661767  return result.success;1768}17691770export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1771  let i: any = it;1772  if (opts.only) i = i.only;1773  else if (opts.skip) i = i.skip;1774  i(name, async () => {1775    await usingApi(async (api, privateKeyWrapper) => {1776      await cb({api, privateKeyWrapper});1777    });1778  });1779}17801781itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1782itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});