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

difftreelog

Fix test and improve throwing errors

Max Andreev2023-02-13parent: #fd5def0.patch.diff
in: master

3 files changed

modifiedtests/src/sub/appPromotion/appPromotion.test.tsdiffbeforeafterboth
--- a/tests/src/sub/appPromotion/appPromotion.test.ts
+++ b/tests/src/sub/appPromotion/appPromotion.test.ts
@@ -247,7 +247,7 @@
         // unstake has no effect if no stakes at all
         testCase.method === 'unstakeAll'
           ? await helper.staking.unstakeAll(staker)
-          : await helper.staking.unstakePartial(staker, 100n * nominal);
+          : await expect(helper.staking.unstakePartial(staker, 100n * nominal)).to.be.rejectedWith('Arithmetic: Underflow');
 
         expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(0n);
         expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n); // TODO bigint closeTo helper
@@ -262,7 +262,7 @@
           await helper.staking.unstakeAll(staker);
         } else {
           await helper.staking.unstakePartial(staker, 100n * nominal);
-          await helper.staking.unstakePartial(staker, 100n * nominal);
+          await expect(helper.staking.unstakePartial(staker, 100n * nominal)).to.be.rejectedWith('Arithmetic: Underflow');
         }
 
         expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);
modifiedtests/src/util/playgrounds/types.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -21,7 +21,7 @@
       }[];
   },
   blockHash: string,
-  moduleError?: string;
+  moduleError?: string | object;
 }
 
 export interface ISubscribeBlockEventsData {
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
after · tests/src/util/playgrounds/unique.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {hexToU8a} from '@polkadot/util/hex';13import {u8aConcat} from '@polkadot/util/u8a';14import {15  IApiListeners,16  IBlock,17  IEvent,18  IChainProperties,19  ICollectionCreationOptions,20  ICollectionLimits,21  ICollectionPermissions,22  ICrossAccountId,23  ICrossAccountIdLower,24  ILogger,25  INestingPermissions,26  IProperty,27  IStakingInfo,28  ISchedulerOptions,29  ISubstrateBalance,30  IToken,31  ITokenPropertyPermission,32  ITransactionResult,33  IUniqueHelperLog,34  TApiAllowedListeners,35  TEthereumAccount,36  TSigner,37  TSubstrateAccount,38  TNetworks,39  IForeignAssetMetadata,40  AcalaAssetMetadata,41  MoonbeamAssetInfo,42  DemocracyStandardAccountVote,43  IEthCrossAccountId,44} from './types';45import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';46import type {Vec} from '@polkadot/types-codec';47import {FrameSystemEventRecord} from '@polkadot/types/lookup';4849export class CrossAccountId implements ICrossAccountId {50  Substrate?: TSubstrateAccount;51  Ethereum?: TEthereumAccount;5253  constructor(account: ICrossAccountId) {54    if (account.Substrate) this.Substrate = account.Substrate;55    if (account.Ethereum) this.Ethereum = account.Ethereum;56  }5758  static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {59    switch (domain) {60      case 'Substrate': return new CrossAccountId({Substrate: account.address});61      case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();62    }63  }6465  static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {66    return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});67  }6869  static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {70    return encodeAddress(decodeAddress(address), ss58Format);71  }7273  static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {74    return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});75  }7677  withNormalizedSubstrate(ss58Format = 42): CrossAccountId {78    if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);79    return this;80  }8182  static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {83    return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));84  }8586  toEthereum(): CrossAccountId {87    if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});88    return this;89  }9091  static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {92    return evmToAddress(address, ss58Format);93  }9495  toSubstrate(ss58Format?: number): CrossAccountId {96    if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});97    return this;98  }99100  toLowerCase(): CrossAccountId {101    if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();102    if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();103    return this;104  }105}106107const nesting = {108  toChecksumAddress(address: string): string {109    if (typeof address === 'undefined') return '';110111    if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);112113    address = address.toLowerCase().replace(/^0x/i,'');114    const addressHash = keccakAsHex(address).replace(/^0x/i,'');115    const checksumAddress = ['0x'];116117    for (let i = 0; i < address.length; i++) {118      // If ith character is 8 to f then make it uppercase119      if (parseInt(addressHash[i], 16) > 7) {120        checksumAddress.push(address[i].toUpperCase());121      } else {122        checksumAddress.push(address[i]);123      }124    }125    return checksumAddress.join('');126  },127  tokenIdToAddress(collectionId: number, tokenId: number) {128    return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);129  },130};131132class UniqueUtil {133  static transactionStatus = {134    NOT_READY: 'NotReady',135    FAIL: 'Fail',136    SUCCESS: 'Success',137  };138139  static chainLogType = {140    EXTRINSIC: 'extrinsic',141    RPC: 'rpc',142  };143144  static getTokenAccount(token: IToken): CrossAccountId {145    return new CrossAccountId({Ethereum: this.getTokenAddress(token)});146  }147148  static getTokenAddress(token: IToken): string {149    return nesting.tokenIdToAddress(token.collectionId, token.tokenId);150  }151152  static getDefaultLogger(): ILogger {153    return {154      log(msg: any, level = 'INFO') {155        console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));156      },157      level: {158        ERROR: 'ERROR',159        WARNING: 'WARNING',160        INFO: 'INFO',161      },162    };163  }164165  static vec2str(arr: string[] | number[]) {166    return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');167  }168169  static str2vec(string: string) {170    if (typeof string !== 'string') return string;171    return Array.from(string).map(x => x.charCodeAt(0));172  }173174  static fromSeed(seed: string, ss58Format = 42) {175    const keyring = new Keyring({type: 'sr25519', ss58Format});176    return keyring.addFromUri(seed);177  }178179  static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {180    if (creationResult.status !== this.transactionStatus.SUCCESS) {181      throw Error('Unable to create collection!');182    }183184    let collectionId = null;185    creationResult.result.events.forEach(({event: {data, method, section}}) => {186      if ((section === 'common') && (method === 'CollectionCreated')) {187        collectionId = parseInt(data[0].toString(), 10);188      }189    });190191    if (collectionId === null) {192      throw Error('No CollectionCreated event was found!');193    }194195    return collectionId;196  }197198  static extractTokensFromCreationResult(creationResult: ITransactionResult): {199    success: boolean,200    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],201  } {202    if (creationResult.status !== this.transactionStatus.SUCCESS) {203      throw Error('Unable to create tokens!');204    }205    let success = false;206    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];207    creationResult.result.events.forEach(({event: {data, method, section}}) => {208      if (method === 'ExtrinsicSuccess') {209        success = true;210      } else if ((section === 'common') && (method === 'ItemCreated')) {211        tokens.push({212          collectionId: parseInt(data[0].toString(), 10),213          tokenId: parseInt(data[1].toString(), 10),214          owner: data[2].toHuman(),215          amount: data[3].toBigInt(),216        });217      }218    });219    return {success, tokens};220  }221222  static extractTokensFromBurnResult(burnResult: ITransactionResult): {223    success: boolean,224    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],225  } {226    if (burnResult.status !== this.transactionStatus.SUCCESS) {227      throw Error('Unable to burn tokens!');228    }229    let success = false;230    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];231    burnResult.result.events.forEach(({event: {data, method, section}}) => {232      if (method === 'ExtrinsicSuccess') {233        success = true;234      } else if ((section === 'common') && (method === 'ItemDestroyed')) {235        tokens.push({236          collectionId: parseInt(data[0].toString(), 10),237          tokenId: parseInt(data[1].toString(), 10),238          owner: data[2].toHuman(),239          amount: data[3].toBigInt(),240        });241      }242    });243    return {success, tokens};244  }245246  static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {247    let eventId = null;248    events.forEach(({event: {data, method, section}}) => {249      if ((section === expectedSection) && (method === expectedMethod)) {250        eventId = parseInt(data[0].toString(), 10);251      }252    });253254    if (eventId === null) {255      throw Error(`No ${expectedMethod} event was found!`);256    }257    return eventId === collectionId;258  }259260  static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {261    const normalizeAddress = (address: string | ICrossAccountId) => {262      if(typeof address === 'string') return address;263      const obj = {} as any;264      Object.keys(address).forEach(k => {265        obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];266      });267      if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);268      if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();269      return address;270    };271    let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;272    events.forEach(({event: {data, method, section}}) => {273      if ((section === 'common') && (method === 'Transfer')) {274        const hData = (data as any).toJSON();275        transfer = {276          collectionId: hData[0],277          tokenId: hData[1],278          from: normalizeAddress(hData[2]),279          to: normalizeAddress(hData[3]),280          amount: BigInt(hData[4]),281        };282      }283    });284    let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;285    isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);286    isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);287    isSuccess = isSuccess && amount === transfer.amount;288    return isSuccess;289  }290291  static bigIntToDecimals(number: bigint, decimals = 18) {292    const numberStr = number.toString();293    const dotPos = numberStr.length - decimals;294295    if (dotPos <= 0) {296      return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;297    } else {298      const intPart = numberStr.substring(0, dotPos);299      const fractPart = numberStr.substring(dotPos);300      return intPart + '.' + fractPart;301    }302  }303}304305class UniqueEventHelper {306  private static extractIndex(index: any): [number, number] | string {307    if(index.toRawType() === '[u8;2]') return [index[0], index[1]];308    return index.toJSON();309  }310311  private static extractSub(data: any, subTypes: any): {[key: string]: any} {312    let obj: any = {};313    let index = 0;314315    if (data.entries) {316      for(const [key, value] of data.entries()) {317        obj[key] = this.extractData(value, subTypes[index]);318        index++;319      }320    } else obj = data.toJSON();321322    return obj;323  }324325  private static toHuman(data: any) {326    return data && data.toHuman ? data.toHuman() : `${data}`;327  }328329  private static extractData(data: any, type: any): any {330    if(!type) return this.toHuman(data);331    if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();332    if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();333    if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);334    return this.toHuman(data);335  }336337  public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {338    const parsedEvents: IEvent[] = [];339340    events.forEach((record) => {341      const {event, phase} = record;342      const types = event.typeDef;343344      const eventData: IEvent = {345        section: event.section.toString(),346        method: event.method.toString(),347        index: this.extractIndex(event.index),348        data: [],349        phase: phase.toJSON(),350      };351352      event.data.forEach((val: any, index: number) => {353        eventData.data.push(this.extractData(val, types[index]));354      });355356      parsedEvents.push(eventData);357    });358359    return parsedEvents;360  }361}362363export class ChainHelperBase {364  helperBase: any;365366  transactionStatus = UniqueUtil.transactionStatus;367  chainLogType = UniqueUtil.chainLogType;368  util: typeof UniqueUtil;369  eventHelper: typeof UniqueEventHelper;370  logger: ILogger;371  api: ApiPromise | null;372  forcedNetwork: TNetworks | null;373  network: TNetworks | null;374  wsEndpoint: string | null;375  chainLog: IUniqueHelperLog[];376  children: ChainHelperBase[];377  address: AddressGroup;378  chain: ChainGroup;379380  constructor(logger?: ILogger, helperBase?: any) {381    this.helperBase = helperBase;382383    this.util = UniqueUtil;384    this.eventHelper = UniqueEventHelper;385    if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();386    this.logger = logger;387    this.api = null;388    this.forcedNetwork = null;389    this.network = null;390    this.wsEndpoint = null;391    this.chainLog = [];392    this.children = [];393    this.address = new AddressGroup(this);394    this.chain = new ChainGroup(this);395  }396397  clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {398    Object.setPrototypeOf(helperCls.prototype, this);399    const newHelper = new helperCls(this.logger, options);400401    newHelper.api = this.api;402    newHelper.network = this.network;403    newHelper.forceNetwork = this.forceNetwork;404405    this.children.push(newHelper);406407    return newHelper;408  }409410  getEndpoint(): string {411    if (this.wsEndpoint === null) throw Error('No connection was established');412    return this.wsEndpoint;413  }414415  getApi(): ApiPromise {416    if(this.api === null) throw Error('API not initialized');417    return this.api;418  }419420  async subscribeEvents(expectedEvents: {section: string, names: string[]}[]) {421    const collectedEvents: IEvent[] = [];422    const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {423      const ievents = this.eventHelper.extractEvents(events);424      ievents.forEach((event) => {425        expectedEvents.forEach((e => {426          if (event.section === e.section && e.names.includes(event.method)) {427            collectedEvents.push(event);428          }429        }));430      });431    });432    return {unsubscribe: unsubscribe as any, collectedEvents};433  }434435  clearChainLog(): void {436    this.chainLog = [];437  }438439  forceNetwork(value: TNetworks): void {440    this.forcedNetwork = value;441  }442443  async connect(wsEndpoint: string, listeners?: IApiListeners) {444    if (this.api !== null) throw Error('Already connected');445    const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);446    this.wsEndpoint = wsEndpoint;447    this.api = api;448    this.network = network;449  }450451  async disconnect() {452    for (const child of this.children) {453      child.clearApi();454    }455456    if (this.api === null) return;457    await this.api.disconnect();458    this.clearApi();459  }460461  clearApi() {462    this.api = null;463    this.network = null;464  }465466  static async detectNetwork(api: ApiPromise): Promise<TNetworks> {467    const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;468    const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];469470    if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;471472    if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;473    return 'opal';474  }475476  static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {477    const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});478    await api.isReady;479480    const network = await this.detectNetwork(api);481482    await api.disconnect();483484    return network;485  }486487  static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{488    api: ApiPromise;489    network: TNetworks;490  }> {491    if(typeof network === 'undefined' || network === null) network = 'opal';492    const supportedRPC = {493      opal: {494        unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,495      },496      quartz: {497        unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,498      },499      unique: {500        unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,501      },502      rococo: {},503      westend: {},504      moonbeam: {},505      moonriver: {},506      acala: {},507      karura: {},508      westmint: {},509    };510    if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);511    const rpc = supportedRPC[network];512513    // TODO: investigate how to replace rpc in runtime514    // api._rpcCore.addUserInterfaces(rpc);515516    const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});517518    await api.isReadyOrError;519520    if (typeof listeners === 'undefined') listeners = {};521    for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {522      if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;523      api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);524    }525526    return {api, network};527  }528529  getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {530    const {events, status} = data;531    if (status.isReady) {532      return this.transactionStatus.NOT_READY;533    }534    if (status.isBroadcast) {535      return this.transactionStatus.NOT_READY;536    }537    if (status.isInBlock || status.isFinalized) {538      const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');539      if (errors.length > 0) {540        return this.transactionStatus.FAIL;541      }542      if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {543        return this.transactionStatus.SUCCESS;544      }545    }546547    return this.transactionStatus.FAIL;548  }549550  signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {551    const sign = (callback: any) => {552      if(options !== null) return transaction.signAndSend(sender, options, callback);553      return transaction.signAndSend(sender, callback);554    };555    // eslint-disable-next-line no-async-promise-executor556    return new Promise(async (resolve, reject) => {557      try {558        const unsub = await sign((result: any) => {559          const status = this.getTransactionStatus(result);560561          if (status === this.transactionStatus.SUCCESS) {562            this.logger.log(`${label} successful`);563            unsub();564            resolve({result, status, blockHash: result.status.asInBlock.toHuman()});565          } else if (status === this.transactionStatus.FAIL) {566            let moduleError = null;567568            if (result.hasOwnProperty('dispatchError')) {569              const dispatchError = result['dispatchError'];570571              if (dispatchError) {572                if (dispatchError.isModule) {573                  const modErr = dispatchError.asModule;574                  const errorMeta = dispatchError.registry.findMetaError(modErr);575576                  moduleError = `${errorMeta.section}.${errorMeta.name}`;577                } else {578                  moduleError = dispatchError.toHuman();579                }580              } else {581                this.logger.log(result, this.logger.level.ERROR);582              }583            }584585            this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);586            unsub();587            reject({status, moduleError, result});588          }589        });590      } catch (e) {591        this.logger.log(e, this.logger.level.ERROR);592        reject(e);593      }594    });595  }596597  async signTransactionWithoutSending(signer: TSigner, tx: any) {598    const api = this.getApi();599    const signingInfo = await api.derive.tx.signingInfo(signer.address);600601    tx.sign(signer, {602      blockHash: api.genesisHash,603      genesisHash: api.genesisHash,604      runtimeVersion: api.runtimeVersion,605      nonce: signingInfo.nonce,606    });607608    return tx.toHex();609  }610611  async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {612    const api = this.getApi();613    const signingInfo = await api.derive.tx.signingInfo(signer.address);614615    // We need to sign the tx because616    // unsigned transactions does not have an inclusion fee617    tx.sign(signer, {618      blockHash: api.genesisHash,619      genesisHash: api.genesisHash,620      runtimeVersion: api.runtimeVersion,621      nonce: signingInfo.nonce,622    });623624    if (len === null) {625      return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;626    } else {627      return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;628    }629  }630631  constructApiCall(apiCall: string, params: any[]) {632    if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);633    let call = this.getApi() as any;634    for(const part of apiCall.slice(4).split('.')) {635      call = call[part];636      if (!call) {637        const advice = part.includes('_') ? ' Looks like it needs to be converted to camel case.' : '';638        throw Error(`Function ${part} of api call ${apiCall} not found.${advice}`);639      }640    }641    return call(...params);642  }643644  async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {645    if(this.api === null) throw Error('API not initialized');646    if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);647648    const startTime = (new Date()).getTime();649    let result: ITransactionResult;650    let events: IEvent[] = [];651    try {652      result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;653      events = this.eventHelper.extractEvents(result.result.events);654      const errorEvent = events.find((event) => event.method == 'ExecutedFailed' || event.method == 'CreatedFailed');655      if (errorEvent)656        throw Error(errorEvent.method + ': ' + extrinsic);657    }658    catch(e) {659      if(!(e as object).hasOwnProperty('status')) throw e;660      result = e as ITransactionResult;661    }662663    const endTime = (new Date()).getTime();664665    const log = {666      executedAt: endTime,667      executionTime: endTime - startTime,668      type: this.chainLogType.EXTRINSIC,669      status: result.status,670      call: extrinsic,671      signer: this.getSignerAddress(sender),672      params,673    } as IUniqueHelperLog;674675    let errorMessage = '';676677    if(result.status !== this.transactionStatus.SUCCESS) {678      if (result.moduleError) {679        errorMessage = typeof result.moduleError === 'string'680          ? result.moduleError681          : `${Object.keys(result.moduleError)[0]}: ${Object.values(result.moduleError)[0]}`;682        log.moduleError = errorMessage;683      }684      else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;685    }686    if(events.length > 0) log.events = events;687688    this.chainLog.push(log);689690    if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {691      if (result.moduleError) throw Error(`${errorMessage}`);692      else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));693    }694    return result;695  }696697  async callRpc(rpc: string, params?: any[]) {698    if(typeof params === 'undefined') params = [];699    if(this.api === null) throw Error('API not initialized');700    if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);701702    const startTime = (new Date()).getTime();703    let result;704    let error = null;705    const log = {706      type: this.chainLogType.RPC,707      call: rpc,708      params,709    } as IUniqueHelperLog;710711    try {712      result = await this.constructApiCall(rpc, params);713    }714    catch(e) {715      error = e;716    }717718    const endTime = (new Date()).getTime();719720    log.executedAt = endTime;721    log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';722    log.executionTime = endTime - startTime;723724    this.chainLog.push(log);725726    if(error !== null) throw error;727728    return result;729  }730731  getSignerAddress(signer: IKeyringPair | string): string {732    if(typeof signer === 'string') return signer;733    return signer.address;734  }735736  fetchAllPalletNames(): string[] {737    if(this.api === null) throw Error('API not initialized');738    return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());739  }740741  fetchMissingPalletNames(requiredPallets: string[]): string[] {742    const palletNames = this.fetchAllPalletNames();743    return requiredPallets.filter(p => !palletNames.includes(p));744  }745}746747748class HelperGroup<T extends ChainHelperBase> {749  helper: T;750751  constructor(uniqueHelper: T) {752    this.helper = uniqueHelper;753  }754}755756757class CollectionGroup extends HelperGroup<UniqueHelper> {758  /**759 * Get number of blocks when sponsored transaction is available.760 *761 * @param collectionId ID of collection762 * @param tokenId ID of token763 * @param addressObj address for which the sponsorship is checked764 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});765 * @returns number of blocks or null if sponsorship hasn't been set766 */767  async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {768    return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();769  }770771  /**772   * Get the number of created collections.773   *774   * @returns number of created collections775   */776  async getTotalCount(): Promise<number> {777    return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();778  }779780  /**781   * Get information about the collection with additional data,782   * including the number of tokens it contains, its administrators,783   * the normalized address of the collection's owner, and decoded name and description.784   *785   * @param collectionId ID of collection786   * @example await getData(2)787   * @returns collection information object788   */789  async getData(collectionId: number): Promise<{790    id: number;791    name: string;792    description: string;793    tokensCount: number;794    admins: CrossAccountId[];795    normalizedOwner: TSubstrateAccount;796    raw: any797  } | null> {798    const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);799    const humanCollection = collection.toHuman(), collectionData = {800      id: collectionId, name: null, description: null, tokensCount: 0, admins: [],801      raw: humanCollection,802    } as any, jsonCollection = collection.toJSON();803    if (humanCollection === null) return null;804    collectionData.raw.limits = jsonCollection.limits;805    collectionData.raw.permissions = jsonCollection.permissions;806    collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);807    for (const key of ['name', 'description']) {808      collectionData[key] = this.helper.util.vec2str(humanCollection[key]);809    }810811    collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))812      ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)813      : 0;814    collectionData.admins = await this.getAdmins(collectionId);815816    return collectionData;817  }818819  /**820   * Get the addresses of the collection's administrators, optionally normalized.821   *822   * @param collectionId ID of collection823   * @param normalize whether to normalize the addresses to the default ss58 format824   * @example await getAdmins(1)825   * @returns array of administrators826   */827  async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {828    const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();829830    return normalize831      ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())832      : admins;833  }834835  /**836   * Get the addresses added to the collection allow-list, optionally normalized.837   * @param collectionId ID of collection838   * @param normalize whether to normalize the addresses to the default ss58 format839   * @example await getAllowList(1)840   * @returns array of allow-listed addresses841   */842  async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {843    const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();844    return normalize845      ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())846      : allowListed;847  }848849  /**850   * Get the effective limits of the collection instead of null for default values851   *852   * @param collectionId ID of collection853   * @example await getEffectiveLimits(2)854   * @returns object of collection limits855   */856  async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {857    return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();858  }859860  /**861   * Burns the collection if the signer has sufficient permissions and collection is empty.862   *863   * @param signer keyring of signer864   * @param collectionId ID of collection865   * @example await helper.collection.burn(aliceKeyring, 3);866   * @returns ```true``` if extrinsic success, otherwise ```false```867   */868  async burn(signer: TSigner, collectionId: number): Promise<boolean> {869    const result = await this.helper.executeExtrinsic(870      signer,871      'api.tx.unique.destroyCollection', [collectionId],872      true,873    );874875    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');876  }877878  /**879   * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.880   *881   * @param signer keyring of signer882   * @param collectionId ID of collection883   * @param sponsorAddress Sponsor substrate address884   * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")885   * @returns ```true``` if extrinsic success, otherwise ```false```886   */887  async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {888    const result = await this.helper.executeExtrinsic(889      signer,890      'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],891      true,892    );893894    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');895  }896897  /**898   * Confirms consent to sponsor the collection on behalf of the signer.899   *900   * @param signer keyring of signer901   * @param collectionId ID of collection902   * @example confirmSponsorship(aliceKeyring, 10)903   * @returns ```true``` if extrinsic success, otherwise ```false```904   */905  async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {906    const result = await this.helper.executeExtrinsic(907      signer,908      'api.tx.unique.confirmSponsorship', [collectionId],909      true,910    );911912    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');913  }914915  /**916   * Removes the sponsor of a collection, regardless if it consented or not.917   *918   * @param signer keyring of signer919   * @param collectionId ID of collection920   * @example removeSponsor(aliceKeyring, 10)921   * @returns ```true``` if extrinsic success, otherwise ```false```922   */923  async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {924    const result = await this.helper.executeExtrinsic(925      signer,926      'api.tx.unique.removeCollectionSponsor', [collectionId],927      true,928    );929930    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');931  }932933  /**934   * Sets the limits of the collection. At least one limit must be specified for a correct call.935   *936   * @param signer keyring of signer937   * @param collectionId ID of collection938   * @param limits collection limits object939   * @example940   * await setLimits(941   *   aliceKeyring,942   *   10,943   *   {944   *     sponsorTransferTimeout: 0,945   *     ownerCanDestroy: false946   *   }947   * )948   * @returns ```true``` if extrinsic success, otherwise ```false```949   */950  async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {951    const result = await this.helper.executeExtrinsic(952      signer,953      'api.tx.unique.setCollectionLimits', [collectionId, limits],954      true,955    );956957    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');958  }959960  /**961   * Changes the owner of the collection to the new Substrate address.962   *963   * @param signer keyring of signer964   * @param collectionId ID of collection965   * @param ownerAddress substrate address of new owner966   * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")967   * @returns ```true``` if extrinsic success, otherwise ```false```968   */969  async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {970    const result = await this.helper.executeExtrinsic(971      signer,972      'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],973      true,974    );975976    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');977  }978979  /**980   * Adds a collection administrator.981   *982   * @param signer keyring of signer983   * @param collectionId ID of collection984   * @param adminAddressObj Administrator address (substrate or ethereum)985   * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})986   * @returns ```true``` if extrinsic success, otherwise ```false```987   */988  async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {989    const result = await this.helper.executeExtrinsic(990      signer,991      'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],992      true,993    );994995    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');996  }997998  /**999   * Removes a collection administrator.1000   *1001   * @param signer keyring of signer1002   * @param collectionId ID of collection1003   * @param adminAddressObj Administrator address (substrate or ethereum)1004   * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})1005   * @returns ```true``` if extrinsic success, otherwise ```false```1006   */1007  async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1008    const result = await this.helper.executeExtrinsic(1009      signer,1010      'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],1011      true,1012    );10131014    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');1015  }10161017  /**1018   * Check if user is in allow list.1019   *1020   * @param collectionId ID of collection1021   * @param user Account to check1022   * @example await getAdmins(1)1023   * @returns is user in allow list1024   */1025  async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {1026    return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();1027  }10281029  /**1030   * Adds an address to allow list1031   * @param signer keyring of signer1032   * @param collectionId ID of collection1033   * @param addressObj address to add to the allow list1034   * @returns ```true``` if extrinsic success, otherwise ```false```1035   */1036  async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1037    const result = await this.helper.executeExtrinsic(1038      signer,1039      'api.tx.unique.addToAllowList', [collectionId, addressObj],1040      true,1041    );10421043    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1044  }10451046  /**1047   * Removes an address from allow list1048   *1049   * @param signer keyring of signer1050   * @param collectionId ID of collection1051   * @param addressObj address to remove from the allow list1052   * @returns ```true``` if extrinsic success, otherwise ```false```1053   */1054  async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1055    const result = await this.helper.executeExtrinsic(1056      signer,1057      'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1058      true,1059    );10601061    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1062  }10631064  /**1065   * Sets onchain permissions for selected collection.1066   *1067   * @param signer keyring of signer1068   * @param collectionId ID of collection1069   * @param permissions collection permissions object1070   * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1071   * @returns ```true``` if extrinsic success, otherwise ```false```1072   */1073  async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1074    const result = await this.helper.executeExtrinsic(1075      signer,1076      'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1077      true,1078    );10791080    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1081  }10821083  /**1084   * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1085   *1086   * @param signer keyring of signer1087   * @param collectionId ID of collection1088   * @param permissions nesting permissions object1089   * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1090   * @returns ```true``` if extrinsic success, otherwise ```false```1091   */1092  async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1093    return await this.setPermissions(signer, collectionId, {nesting: permissions});1094  }10951096  /**1097   * Disables nesting for selected collection.1098   *1099   * @param signer keyring of signer1100   * @param collectionId ID of collection1101   * @example disableNesting(aliceKeyring, 10);1102   * @returns ```true``` if extrinsic success, otherwise ```false```1103   */1104  async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1105    return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1106  }11071108  /**1109   * Sets onchain properties to the collection.1110   *1111   * @param signer keyring of signer1112   * @param collectionId ID of collection1113   * @param properties array of property objects1114   * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1115   * @returns ```true``` if extrinsic success, otherwise ```false```1116   */1117  async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1118    const result = await this.helper.executeExtrinsic(1119      signer,1120      'api.tx.unique.setCollectionProperties', [collectionId, properties],1121      true,1122    );11231124    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1125  }11261127  /**1128   * Get collection properties.1129   *1130   * @param collectionId ID of collection1131   * @param propertyKeys optionally filter the returned properties to only these keys1132   * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1133   * @returns array of key-value pairs1134   */1135  async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1136    return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1137  }11381139  async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1140    const api = this.helper.getApi();1141    const props = (await api.query.common.collectionProperties(collectionId)).toJSON();11421143    return (props! as any).consumedSpace;1144  }11451146  async getCollectionOptions(collectionId: number) {1147    return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1148  }11491150  /**1151   * Deletes onchain properties from the collection.1152   *1153   * @param signer keyring of signer1154   * @param collectionId ID of collection1155   * @param propertyKeys array of property keys to delete1156   * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1157   * @returns ```true``` if extrinsic success, otherwise ```false```1158   */1159  async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1160    const result = await this.helper.executeExtrinsic(1161      signer,1162      'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1163      true,1164    );11651166    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1167  }11681169  /**1170   * Changes the owner of the token.1171   *1172   * @param signer keyring of signer1173   * @param collectionId ID of collection1174   * @param tokenId ID of token1175   * @param addressObj address of a new owner1176   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1177   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1178   * @returns true if the token success, otherwise false1179   */1180  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1181    const result = await this.helper.executeExtrinsic(1182      signer,1183      'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1184      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1185    );11861187    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1188  }11891190  /**1191   *1192   * Change ownership of a token(s) on behalf of the owner.1193   *1194   * @param signer keyring of signer1195   * @param collectionId ID of collection1196   * @param tokenId ID of token1197   * @param fromAddressObj address on behalf of which the token will be sent1198   * @param toAddressObj new token owner1199   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1200   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1201   * @returns true if the token success, otherwise false1202   */1203  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1204    const result = await this.helper.executeExtrinsic(1205      signer,1206      'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1207      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1208    );1209    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1210  }12111212  /**1213   *1214   * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1215   *1216   * @param signer keyring of signer1217   * @param collectionId ID of collection1218   * @param tokenId ID of token1219   * @param amount amount of tokens to be burned. For NFT must be set to 1n1220   * @example burnToken(aliceKeyring, 10, 5);1221   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1222   */1223  async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1224    const burnResult = await this.helper.executeExtrinsic(1225      signer,1226      'api.tx.unique.burnItem', [collectionId, tokenId, amount],1227      true, // `Unable to burn token for ${label}`,1228    );1229    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1230    if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1231    return burnedTokens.success;1232  }12331234  /**1235   * Destroys a concrete instance of NFT on behalf of the owner1236   *1237   * @param signer keyring of signer1238   * @param collectionId ID of collection1239   * @param tokenId ID of token1240   * @param fromAddressObj address on behalf of which the token will be burnt1241   * @param amount amount of tokens to be burned. For NFT must be set to 1n1242   * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1243   * @returns ```true``` if extrinsic success, otherwise ```false```1244   */1245  async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1246    const burnResult = await this.helper.executeExtrinsic(1247      signer,1248      'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1249      true, // `Unable to burn token from for ${label}`,1250    );1251    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1252    return burnedTokens.success && burnedTokens.tokens.length > 0;1253  }12541255  /**1256   * Set, change, or remove approved address to transfer the ownership of the NFT.1257   *1258   * @param signer keyring of signer1259   * @param collectionId ID of collection1260   * @param tokenId ID of token1261   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1262   * @param amount amount of token to be approved. For NFT must be set to 1n1263   * @returns ```true``` if extrinsic success, otherwise ```false```1264   */1265  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1266    const approveResult = await this.helper.executeExtrinsic(1267      signer,1268      'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1269      true, // `Unable to approve token for ${label}`,1270    );12711272    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1273  }12741275  /**1276   * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1277   *1278   * @param signer keyring of signer1279   * @param collectionId ID of collection1280   * @param tokenId ID of token1281   * @param fromAddressObj Signer's Ethereum address containing her tokens1282   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1283   * @param amount amount of token to be approved. For NFT must be set to 1n1284   * @returns ```true``` if extrinsic success, otherwise ```false```1285   */1286  async approveTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1287    const approveResult = await this.helper.executeExtrinsic(1288      signer,1289      'api.tx.unique.approveFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1290      true, // `Unable to approve token for ${label}`,1291    );12921293    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1294  }12951296  /**1297   * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1298   *1299   * @param signer keyring of signer1300   * @param collectionId ID of collection1301   * @param tokenId ID of token1302   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1303   * @param amount amount of token to be approved. For NFT must be set to 1n1304   * @returns ```true``` if extrinsic success, otherwise ```false```1305   */1306  async approveTokenFromEth(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1307    const ethMirror = CrossAccountId.fromKeyring(signer).toEthereum();1308    return await this.approveTokenFrom(signer, collectionId, tokenId, ethMirror, toAddressObj, amount);1309  }13101311  /**1312   * Get the amount of token pieces approved to transfer or burn. Normally 0.1313   *1314   * @param collectionId ID of collection1315   * @param tokenId ID of token1316   * @param toAccountObj address which is approved to use token pieces1317   * @param fromAccountObj address which may have allowed the use of its owned tokens1318   * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1319   * @returns number of approved to transfer pieces1320   */1321  async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1322    return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1323  }13241325  /**1326   * Get the last created token ID in a collection1327   *1328   * @param collectionId ID of collection1329   * @example getLastTokenId(10);1330   * @returns id of the last created token1331   */1332  async getLastTokenId(collectionId: number): Promise<number> {1333    return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1334  }13351336  /**1337   * Check if token exists1338   *1339   * @param collectionId ID of collection1340   * @param tokenId ID of token1341   * @example doesTokenExist(10, 20);1342   * @returns true if the token exists, otherwise false1343   */1344  async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1345    return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1346  }1347}13481349class NFTnRFT extends CollectionGroup {1350  /**1351   * Get tokens owned by account1352   *1353   * @param collectionId ID of collection1354   * @param addressObj tokens owner1355   * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1356   * @returns array of token ids owned by account1357   */1358  async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1359    return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1360  }13611362  /**1363   * Get token data1364   *1365   * @param collectionId ID of collection1366   * @param tokenId ID of token1367   * @param propertyKeys optionally filter the token properties to only these keys1368   * @param blockHashAt optionally query the data at some block with this hash1369   * @example getToken(10, 5);1370   * @returns human readable token data1371   */1372  async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1373    properties: IProperty[];1374    owner: CrossAccountId;1375    normalizedOwner: CrossAccountId;1376  }| null> {1377    let tokenData;1378    if(typeof blockHashAt === 'undefined') {1379      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1380    }1381    else {1382      if(propertyKeys.length == 0) {1383        const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1384        if(!collection) return null;1385        propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1386      }1387      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1388    }1389    tokenData = tokenData.toHuman();1390    if (tokenData === null || tokenData.owner === null) return null;1391    const owner = {} as any;1392    for (const key of Object.keys(tokenData.owner)) {1393      owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1394        ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1395        : tokenData.owner[key];1396    }1397    tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1398    return tokenData;1399  }14001401  /**1402   * Get token's owner1403   * @param collectionId ID of collection1404   * @param tokenId ID of token1405   * @param blockHashAt optionally query the data at the block with this hash1406   * @example getTokenOwner(10, 5);1407   * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1408   */1409  async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1410    let owner;1411    if (typeof blockHashAt === 'undefined') {1412      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1413    } else {1414      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1415    }1416    return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1417  }14181419  /**1420   * Recursively find the address that owns the token1421   * @param collectionId ID of collection1422   * @param tokenId ID of token1423   * @param blockHashAt1424   * @example getTokenTopmostOwner(10, 5);1425   * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1426   */1427  async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1428    let owner;1429    if (typeof blockHashAt === 'undefined') {1430      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1431    } else {1432      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1433    }14341435    if (owner === null) return null;14361437    return owner.toHuman();1438  }14391440  /**1441   * Nest one token into another1442   * @param signer keyring of signer1443   * @param tokenObj token to be nested1444   * @param rootTokenObj token to be parent1445   * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1446   * @returns ```true``` if extrinsic success, otherwise ```false```1447   */1448  async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1449    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1450    const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1451    if(!result) {1452      throw Error('Unable to nest token!');1453    }1454    return result;1455  }14561457  /**1458     * Remove token from nested state1459     * @param signer keyring of signer1460     * @param tokenObj token to unnest1461     * @param rootTokenObj parent of a token1462     * @param toAddressObj address of a new token owner1463     * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1464     * @returns ```true``` if extrinsic success, otherwise ```false```1465     */1466  async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1467    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1468    const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1469    if(!result) {1470      throw Error('Unable to unnest token!');1471    }1472    return result;1473  }14741475  /**1476   * Set permissions to change token properties1477   *1478   * @param signer keyring of signer1479   * @param collectionId ID of collection1480   * @param permissions permissions to change a property by the collection admin or token owner1481   * @example setTokenPropertyPermissions(1482   *   aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1483   * )1484   * @returns true if extrinsic success otherwise false1485   */1486  async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1487    const result = await this.helper.executeExtrinsic(1488      signer,1489      'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1490      true,1491    );14921493    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1494  }14951496  /**1497   * Get token property permissions.1498   *1499   * @param collectionId ID of collection1500   * @param propertyKeys optionally filter the returned property permissions to only these keys1501   * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1502   * @returns array of key-permission pairs1503   */1504  async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1505    return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1506  }15071508  /**1509   * Set token properties1510   *1511   * @param signer keyring of signer1512   * @param collectionId ID of collection1513   * @param tokenId ID of token1514   * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1515   * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1516   * @returns ```true``` if extrinsic success, otherwise ```false```1517   */1518  async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1519    const result = await this.helper.executeExtrinsic(1520      signer,1521      'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1522      true,1523    );15241525    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1526  }15271528  /**1529   * Get properties, metadata assigned to a token.1530   *1531   * @param collectionId ID of collection1532   * @param tokenId ID of token1533   * @param propertyKeys optionally filter the returned properties to only these keys1534   * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1535   * @returns array of key-value pairs1536   */1537  async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1538    return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1539  }15401541  /**1542   * Delete the provided properties of a token1543   * @param signer keyring of signer1544   * @param collectionId ID of collection1545   * @param tokenId ID of token1546   * @param propertyKeys property keys to be deleted1547   * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1548   * @returns ```true``` if extrinsic success, otherwise ```false```1549   */1550  async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1551    const result = await this.helper.executeExtrinsic(1552      signer,1553      'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1554      true,1555    );15561557    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1558  }15591560  /**1561   * Mint new collection1562   *1563   * @param signer keyring of signer1564   * @param collectionOptions basic collection options and properties1565   * @param mode NFT or RFT type of a collection1566   * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1567   * @returns object of the created collection1568   */1569  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1570    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1571    collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1572    for (const key of ['name', 'description', 'tokenPrefix']) {1573      if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1574    }1575    const creationResult = await this.helper.executeExtrinsic(1576      signer,1577      'api.tx.unique.createCollectionEx', [collectionOptions],1578      true, // errorLabel,1579    );1580    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1581  }15821583  getCollectionObject(_collectionId: number): any {1584    return null;1585  }15861587  getTokenObject(_collectionId: number, _tokenId: number): any {1588    return null;1589  }15901591  /**1592   * Tells whether the given `owner` approves the `operator`.1593   * @param collectionId ID of collection1594   * @param owner owner address1595   * @param operator operator addrees1596   * @returns true if operator is enabled1597   */1598  async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1599    return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1600  }16011602  /** Sets or unsets the approval of a given operator.1603   *  The `operator` is allowed to transfer all tokens of the `caller` on their behalf.1604   *  @param operator Operator1605   *  @param approved Should operator status be granted or revoked?1606   *  @returns ```true``` if extrinsic success, otherwise ```false```1607   */1608  async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1609    const result = await this.helper.executeExtrinsic(1610      signer,1611      'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1612      true,1613    );1614    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1615  }1616}161716181619class NFTGroup extends NFTnRFT {1620  /**1621   * Get collection object1622   * @param collectionId ID of collection1623   * @example getCollectionObject(2);1624   * @returns instance of UniqueNFTCollection1625   */1626  getCollectionObject(collectionId: number): UniqueNFTCollection {1627    return new UniqueNFTCollection(collectionId, this.helper);1628  }16291630  /**1631   * Get token object1632   * @param collectionId ID of collection1633   * @param tokenId ID of token1634   * @example getTokenObject(10, 5);1635   * @returns instance of UniqueNFTToken1636   */1637  getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1638    return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1639  }16401641  /**1642   * Is token approved to transfer1643   * @param collectionId ID of collection1644   * @param tokenId ID of token1645   * @param toAccountObj address to be approved1646   * @returns ```true``` if extrinsic success, otherwise ```false```1647   */1648  async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1649    return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1650  }16511652  /**1653   * Changes the owner of the token.1654   *1655   * @param signer keyring of signer1656   * @param collectionId ID of collection1657   * @param tokenId ID of token1658   * @param addressObj address of a new owner1659   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1660   * @returns ```true``` if extrinsic success, otherwise ```false```1661   */1662  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1663    return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1664  }16651666  /**1667   *1668   * Change ownership of a NFT on behalf of the owner.1669   *1670   * @param signer keyring of signer1671   * @param collectionId ID of collection1672   * @param tokenId ID of token1673   * @param fromAddressObj address on behalf of which the token will be sent1674   * @param toAddressObj new token owner1675   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1676   * @returns ```true``` if extrinsic success, otherwise ```false```1677   */1678  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1679    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1680  }16811682  /**1683   * Get tokens nested in the provided token1684   * @param collectionId ID of collection1685   * @param tokenId ID of token1686   * @param blockHashAt optionally query the data at the block with this hash1687   * @example getTokenChildren(10, 5);1688   * @returns tokens whose depth of nesting is <= 51689   */1690  async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1691    let children;1692    if(typeof blockHashAt === 'undefined') {1693      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1694    } else {1695      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1696    }16971698    return children.toJSON().map((x: any) => {1699      return {collectionId: x.collection, tokenId: x.token};1700    });1701  }17021703  /**1704   * Mint new collection1705   * @param signer keyring of signer1706   * @param collectionOptions Collection options1707   * @example1708   * mintCollection(aliceKeyring, {1709   *   name: 'New',1710   *   description: 'New collection',1711   *   tokenPrefix: 'NEW',1712   * })1713   * @returns object of the created collection1714   */1715  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1716    return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1717  }17181719  /**1720   * Mint new token1721   * @param signer keyring of signer1722   * @param data token data1723   * @returns created token object1724   */1725  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1726    const creationResult = await this.helper.executeExtrinsic(1727      signer,1728      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1729        nft: {1730          properties: data.properties,1731        },1732      }],1733      true,1734    );1735    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1736    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1737    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1738    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1739  }17401741  /**1742   * Mint multiple NFT tokens1743   * @param signer keyring of signer1744   * @param collectionId ID of collection1745   * @param tokens array of tokens with owner and properties1746   * @example1747   * mintMultipleTokens(aliceKeyring, 10, [{1748   *     owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1749   *     properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1750   *   },{1751   *     owner: {Ethereum: "0x9F0583DbB855d..."},1752   *     properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1753   * }]);1754   * @returns ```true``` if extrinsic success, otherwise ```false```1755   */1756  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1757    const creationResult = await this.helper.executeExtrinsic(1758      signer,1759      'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1760      true,1761    );1762    const collection = this.getCollectionObject(collectionId);1763    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1764  }17651766  /**1767   * Mint multiple NFT tokens with one owner1768   * @param signer keyring of signer1769   * @param collectionId ID of collection1770   * @param owner tokens owner1771   * @param tokens array of tokens with owner and properties1772   * @example1773   * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1774   *   properties: [{1775   *   key: "gender",1776   *   value: "female",1777   *  },{1778   *   key: "age",1779   *   value: "33",1780   *  }],1781   * }]);1782   * @returns array of newly created tokens1783   */1784  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1785    const rawTokens = [];1786    for (const token of tokens) {1787      const raw = {NFT: {properties: token.properties}};1788      rawTokens.push(raw);1789    }1790    const creationResult = await this.helper.executeExtrinsic(1791      signer,1792      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1793      true,1794    );1795    const collection = this.getCollectionObject(collectionId);1796    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1797  }17981799  /**1800   * Set, change, or remove approved address to transfer the ownership of the NFT.1801   *1802   * @param signer keyring of signer1803   * @param collectionId ID of collection1804   * @param tokenId ID of token1805   * @param toAddressObj address to approve1806   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1807   * @returns ```true``` if extrinsic success, otherwise ```false```1808   */1809  approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1810    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1811  }1812}181318141815class RFTGroup extends NFTnRFT {1816  /**1817   * Get collection object1818   * @param collectionId ID of collection1819   * @example getCollectionObject(2);1820   * @returns instance of UniqueRFTCollection1821   */1822  getCollectionObject(collectionId: number): UniqueRFTCollection {1823    return new UniqueRFTCollection(collectionId, this.helper);1824  }18251826  /**1827   * Get token object1828   * @param collectionId ID of collection1829   * @param tokenId ID of token1830   * @example getTokenObject(10, 5);1831   * @returns instance of UniqueNFTToken1832   */1833  getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1834    return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1835  }18361837  /**1838   * Get top 10 token owners with the largest number of pieces1839   * @param collectionId ID of collection1840   * @param tokenId ID of token1841   * @example getTokenTop10Owners(10, 5);1842   * @returns array of top 10 owners1843   */1844  async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1845    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1846  }18471848  /**1849   * Get number of pieces owned by address1850   * @param collectionId ID of collection1851   * @param tokenId ID of token1852   * @param addressObj address token owner1853   * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1854   * @returns number of pieces ownerd by address1855   */1856  async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1857    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1858  }18591860  /**1861   * Transfer pieces of token to another address1862   * @param signer keyring of signer1863   * @param collectionId ID of collection1864   * @param tokenId ID of token1865   * @param addressObj address of a new owner1866   * @param amount number of pieces to be transfered1867   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1868   * @returns ```true``` if extrinsic success, otherwise ```false```1869   */1870  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1871    return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1872  }18731874  /**1875   * Change ownership of some pieces of RFT on behalf of the owner.1876   * @param signer keyring of signer1877   * @param collectionId ID of collection1878   * @param tokenId ID of token1879   * @param fromAddressObj address on behalf of which the token will be sent1880   * @param toAddressObj new token owner1881   * @param amount number of pieces to be transfered1882   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1883   * @returns ```true``` if extrinsic success, otherwise ```false```1884   */1885  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1886    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1887  }18881889  /**1890   * Mint new collection1891   * @param signer keyring of signer1892   * @param collectionOptions Collection options1893   * @example1894   * mintCollection(aliceKeyring, {1895   *   name: 'New',1896   *   description: 'New collection',1897   *   tokenPrefix: 'NEW',1898   * })1899   * @returns object of the created collection1900   */1901  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1902    return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1903  }19041905  /**1906   * Mint new token1907   * @param signer keyring of signer1908   * @param data token data1909   * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1910   * @returns created token object1911   */1912  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1913    const creationResult = await this.helper.executeExtrinsic(1914      signer,1915      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1916        refungible: {1917          pieces: data.pieces,1918          properties: data.properties,1919        },1920      }],1921      true,1922    );1923    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1924    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1925    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1926    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1927  }19281929  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1930    throw Error('Not implemented');1931    const creationResult = await this.helper.executeExtrinsic(1932      signer,1933      'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1934      true, // `Unable to mint RFT tokens for ${label}`,1935    );1936    const collection = this.getCollectionObject(collectionId);1937    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1938  }19391940  /**1941   * Mint multiple RFT tokens with one owner1942   * @param signer keyring of signer1943   * @param collectionId ID of collection1944   * @param owner tokens owner1945   * @param tokens array of tokens with properties and pieces1946   * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1947   * @returns array of newly created RFT tokens1948   */1949  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1950    const rawTokens = [];1951    for (const token of tokens) {1952      const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1953      rawTokens.push(raw);1954    }1955    const creationResult = await this.helper.executeExtrinsic(1956      signer,1957      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1958      true,1959    );1960    const collection = this.getCollectionObject(collectionId);1961    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1962  }19631964  /**1965   * Destroys a concrete instance of RFT.1966   * @param signer keyring of signer1967   * @param collectionId ID of collection1968   * @param tokenId ID of token1969   * @param amount number of pieces to be burnt1970   * @example burnToken(aliceKeyring, 10, 5);1971   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1972   */1973  async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1974    return await super.burnToken(signer, collectionId, tokenId, amount);1975  }19761977  /**1978   * Destroys a concrete instance of RFT on behalf of the owner.1979   * @param signer keyring of signer1980   * @param collectionId ID of collection1981   * @param tokenId ID of token1982   * @param fromAddressObj address on behalf of which the token will be burnt1983   * @param amount number of pieces to be burnt1984   * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1985   * @returns ```true``` if extrinsic success, otherwise ```false```1986   */1987  async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1988    return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1989  }19901991  /**1992   * Set, change, or remove approved address to transfer the ownership of the RFT.1993   *1994   * @param signer keyring of signer1995   * @param collectionId ID of collection1996   * @param tokenId ID of token1997   * @param toAddressObj address to approve1998   * @param amount number of pieces to be approved1999   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);2000   * @returns true if the token success, otherwise false2001   */2002  approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2003    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);2004  }20052006  /**2007   * Get total number of pieces2008   * @param collectionId ID of collection2009   * @param tokenId ID of token2010   * @example getTokenTotalPieces(10, 5);2011   * @returns number of pieces2012   */2013  async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {2014    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();2015  }20162017  /**2018   * Change number of token pieces. Signer must be the owner of all token pieces.2019   * @param signer keyring of signer2020   * @param collectionId ID of collection2021   * @param tokenId ID of token2022   * @param amount new number of pieces2023   * @example repartitionToken(aliceKeyring, 10, 5, 12345n);2024   * @returns true if the repartion was success, otherwise false2025   */2026  async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {2027    const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);2028    const repartitionResult = await this.helper.executeExtrinsic(2029      signer,2030      'api.tx.unique.repartition', [collectionId, tokenId, amount],2031      true,2032    );2033    if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');2034    return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');2035  }2036}203720382039class FTGroup extends CollectionGroup {2040  /**2041   * Get collection object2042   * @param collectionId ID of collection2043   * @example getCollectionObject(2);2044   * @returns instance of UniqueFTCollection2045   */2046  getCollectionObject(collectionId: number): UniqueFTCollection {2047    return new UniqueFTCollection(collectionId, this.helper);2048  }20492050  /**2051   * Mint new fungible collection2052   * @param signer keyring of signer2053   * @param collectionOptions Collection options2054   * @param decimalPoints number of token decimals2055   * @example2056   * mintCollection(aliceKeyring, {2057   *   name: 'New',2058   *   description: 'New collection',2059   *   tokenPrefix: 'NEW',2060   * }, 18)2061   * @returns newly created fungible collection2062   */2063  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {2064    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object2065    if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');2066    collectionOptions.mode = {fungible: decimalPoints};2067    for (const key of ['name', 'description', 'tokenPrefix']) {2068      if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);2069    }2070    const creationResult = await this.helper.executeExtrinsic(2071      signer,2072      'api.tx.unique.createCollectionEx', [collectionOptions],2073      true,2074    );2075    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2076  }20772078  /**2079   * Mint tokens2080   * @param signer keyring of signer2081   * @param collectionId ID of collection2082   * @param owner address owner of new tokens2083   * @param amount amount of tokens to be meanted2084   * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);2085   * @returns ```true``` if extrinsic success, otherwise ```false```2086   */2087  async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2088    const creationResult = await this.helper.executeExtrinsic(2089      signer,2090      'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2091        fungible: {2092          value: amount,2093        },2094      }],2095      true, // `Unable to mint fungible tokens for ${label}`,2096    );2097    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2098  }20992100  /**2101   * Mint multiple Fungible tokens with one owner2102   * @param signer keyring of signer2103   * @param collectionId ID of collection2104   * @param owner tokens owner2105   * @param tokens array of tokens with properties and pieces2106   * @returns ```true``` if extrinsic success, otherwise ```false```2107   */2108  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {2109    const rawTokens = [];2110    for (const token of tokens) {2111      const raw = {Fungible: {Value: token.value}};2112      rawTokens.push(raw);2113    }2114    const creationResult = await this.helper.executeExtrinsic(2115      signer,2116      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2117      true,2118    );2119    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2120  }21212122  /**2123   * Get the top 10 owners with the largest balance for the Fungible collection2124   * @param collectionId ID of collection2125   * @example getTop10Owners(10);2126   * @returns array of ```ICrossAccountId```2127   */2128  async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2129    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2130  }21312132  /**2133   * Get account balance2134   * @param collectionId ID of collection2135   * @param addressObj address of owner2136   * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2137   * @returns amount of fungible tokens owned by address2138   */2139  async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2140    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2141  }21422143  /**2144   * Transfer tokens to address2145   * @param signer keyring of signer2146   * @param collectionId ID of collection2147   * @param toAddressObj address recipient2148   * @param amount amount of tokens to be sent2149   * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2150   * @returns ```true``` if extrinsic success, otherwise ```false```2151   */2152  async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2153    return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2154  }21552156  /**2157   * Transfer some tokens on behalf of the owner.2158   * @param signer keyring of signer2159   * @param collectionId ID of collection2160   * @param fromAddressObj address on behalf of which tokens will be sent2161   * @param toAddressObj address where token to be sent2162   * @param amount number of tokens to be sent2163   * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2164   * @returns ```true``` if extrinsic success, otherwise ```false```2165   */2166  async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2167    return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2168  }21692170  /**2171   * Destroy some amount of tokens2172   * @param signer keyring of signer2173   * @param collectionId ID of collection2174   * @param amount amount of tokens to be destroyed2175   * @example burnTokens(aliceKeyring, 10, 1000n);2176   * @returns ```true``` if extrinsic success, otherwise ```false```2177   */2178  async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2179    return await super.burnToken(signer, collectionId, 0, amount);2180  }21812182  /**2183   * Burn some tokens on behalf of the owner.2184   * @param signer keyring of signer2185   * @param collectionId ID of collection2186   * @param fromAddressObj address on behalf of which tokens will be burnt2187   * @param amount amount of tokens to be burnt2188   * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2189   * @returns ```true``` if extrinsic success, otherwise ```false```2190   */2191  async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2192    return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2193  }21942195  /**2196   * Get total collection supply2197   * @param collectionId2198   * @returns2199   */2200  async getTotalPieces(collectionId: number): Promise<bigint> {2201    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2202  }22032204  /**2205   * Set, change, or remove approved address to transfer tokens.2206   *2207   * @param signer keyring of signer2208   * @param collectionId ID of collection2209   * @param toAddressObj address to be approved2210   * @param amount amount of tokens to be approved2211   * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2212   * @returns ```true``` if extrinsic success, otherwise ```false```2213   */2214  approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2215    return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2216  }22172218  /**2219   * Get amount of fungible tokens approved to transfer2220   * @param collectionId ID of collection2221   * @param fromAddressObj owner of tokens2222   * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2223   * @returns number of tokens approved for the transfer2224   */2225  getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2226    return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2227  }2228}222922302231class ChainGroup extends HelperGroup<ChainHelperBase> {2232  /**2233   * Get system properties of a chain2234   * @example getChainProperties();2235   * @returns ss58Format, token decimals, and token symbol2236   */2237  getChainProperties(): IChainProperties {2238    const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2239    return {2240      ss58Format: properties.ss58Format.toJSON(),2241      tokenDecimals: properties.tokenDecimals.toJSON(),2242      tokenSymbol: properties.tokenSymbol.toJSON(),2243    };2244  }22452246  /**2247   * Get chain header2248   * @example getLatestBlockNumber();2249   * @returns the number of the last block2250   */2251  async getLatestBlockNumber(): Promise<number> {2252    return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2253  }22542255  /**2256   * Get block hash by block number2257   * @param blockNumber number of block2258   * @example getBlockHashByNumber(12345);2259   * @returns hash of a block2260   */2261  async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2262    const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2263    if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2264    return blockHash;2265  }22662267  // TODO add docs2268  async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2269    const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2270    if (!blockHash) return null;2271    return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2272  }22732274  /**2275   * Get latest relay block2276   * @returns {number} relay block2277   */2278  async getRelayBlockNumber(): Promise<bigint> {2279    const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2280    return BigInt(blockNumber);2281  }22822283  /**2284   * Get account nonce2285   * @param address substrate address2286   * @example getNonce("5GrwvaEF5zXb26Fz...");2287   * @returns number, account's nonce2288   */2289  async getNonce(address: TSubstrateAccount): Promise<number> {2290    return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2291  }2292}22932294class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2295  /**2296 * Get substrate address balance2297 * @param address substrate address2298 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2299 * @returns amount of tokens on address2300 */2301  async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2302    return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2303  }23042305  /**2306   * Transfer tokens to substrate address2307   * @param signer keyring of signer2308   * @param address substrate address of a recipient2309   * @param amount amount of tokens to be transfered2310   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2311   * @returns ```true``` if extrinsic success, otherwise ```false```2312   */2313  async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2314    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true/*, `Unable to transfer balance from ${this.helper.getSignerAddress(signer)} to ${address}`*/);23152316    let transfer = {from: null, to: null, amount: 0n} as any;2317    result.result.events.forEach(({event: {data, method, section}}) => {2318      if ((section === 'balances') && (method === 'Transfer')) {2319        transfer = {2320          from: this.helper.address.normalizeSubstrate(data[0]),2321          to: this.helper.address.normalizeSubstrate(data[1]),2322          amount: BigInt(data[2]),2323        };2324      }2325    });2326    const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2327      && this.helper.address.normalizeSubstrate(address) === transfer.to2328      && BigInt(amount) === transfer.amount;2329    return isSuccess;2330  }23312332  /**2333   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2334   * @param address substrate address2335   * @returns2336   */2337  async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2338    const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2339    return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2340  }23412342  async getLocked(address: TSubstrateAccount): Promise<[{id: string, amount: bigint, reason: string}]> {2343    const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2344    return locks.map((lock: any) => {return {id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons};});2345  }2346}23472348class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2349  /**2350   * Get ethereum address balance2351   * @param address ethereum address2352   * @example getEthereum("0x9F0583DbB855d...")2353   * @returns amount of tokens on address2354   */2355  async getEthereum(address: TEthereumAccount): Promise<bigint> {2356    return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2357  }23582359  /**2360   * Transfer tokens to address2361   * @param signer keyring of signer2362   * @param address Ethereum address of a recipient2363   * @param amount amount of tokens to be transfered2364   * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2365   * @returns ```true``` if extrinsic success, otherwise ```false```2366   */2367  async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2368    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);23692370    let transfer = {from: null, to: null, amount: 0n} as any;2371    result.result.events.forEach(({event: {data, method, section}}) => {2372      if ((section === 'balances') && (method === 'Transfer')) {2373        transfer = {2374          from: data[0].toString(),2375          to: data[1].toString(),2376          amount: BigInt(data[2]),2377        };2378      }2379    });2380    const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2381      && address === transfer.to2382      && BigInt(amount) === transfer.amount;2383    return isSuccess;2384  }2385}23862387class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2388  subBalanceGroup: SubstrateBalanceGroup<T>;2389  ethBalanceGroup: EthereumBalanceGroup<T>;23902391  constructor(helper: T) {2392    super(helper);2393    this.subBalanceGroup = new SubstrateBalanceGroup(helper);2394    this.ethBalanceGroup = new EthereumBalanceGroup(helper);2395  }23962397  getCollectionCreationPrice(): bigint {2398    return 2n * this.getOneTokenNominal();2399  }2400  /**2401   * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2402   * @example getOneTokenNominal()2403   * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2404   */2405  getOneTokenNominal(): bigint {2406    const chainProperties = this.helper.chain.getChainProperties();2407    return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2408  }24092410  /**2411   * Get substrate address balance2412   * @param address substrate address2413   * @example getSubstrate("5GrwvaEF5zXb26Fz...")2414   * @returns amount of tokens on address2415   */2416  getSubstrate(address: TSubstrateAccount): Promise<bigint> {2417    return this.subBalanceGroup.getSubstrate(address);2418  }24192420  /**2421   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2422   * @param address substrate address2423   * @returns2424   */2425  getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2426    return this.subBalanceGroup.getSubstrateFull(address);2427  }24282429  /**2430   * Get locked balances2431   * @param address substrate address2432   * @returns locked balances with reason via api.query.balances.locks2433   */2434  getLocked(address: TSubstrateAccount) {2435    return this.subBalanceGroup.getLocked(address);2436  }24372438  /**2439   * Get ethereum address balance2440   * @param address ethereum address2441   * @example getEthereum("0x9F0583DbB855d...")2442   * @returns amount of tokens on address2443   */2444  getEthereum(address: TEthereumAccount): Promise<bigint> {2445    return this.ethBalanceGroup.getEthereum(address);2446  }24472448  /**2449   * Transfer tokens to substrate address2450   * @param signer keyring of signer2451   * @param address substrate address of a recipient2452   * @param amount amount of tokens to be transfered2453   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2454   * @returns ```true``` if extrinsic success, otherwise ```false```2455   */2456  transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2457    return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2458  }24592460  async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2461    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);24622463    let transfer = {from: null, to: null, amount: 0n} as any;2464    result.result.events.forEach(({event: {data, method, section}}) => {2465      if ((section === 'balances') && (method === 'Transfer')) {2466        transfer = {2467          from: this.helper.address.normalizeSubstrate(data[0]),2468          to: this.helper.address.normalizeSubstrate(data[1]),2469          amount: BigInt(data[2]),2470        };2471      }2472    });2473    let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2474    isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2475    isSuccess = isSuccess && BigInt(amount) === transfer.amount;2476    return isSuccess;2477  }24782479  /**2480   * Transfer tokens with the unlock period2481   * @param signer signers Keyring2482   * @param address Substrate address of recipient2483   * @param schedule Schedule params2484   * @example vestedTransfer(signer, recepient.address, 20000, 100, 10, 50 * nominal); // total amount of vested tokens will be 100 * 50 = 50002485   */2486  async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: {start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}): Promise<void> {2487    const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2488    const event = result.result.events2489      .find(e => e.event.section === 'vesting' &&2490            e.event.method === 'VestingScheduleAdded' &&2491            e.event.data[0].toHuman() === signer.address);2492    if (!event) throw Error('Cannot find transfer in events');2493  }24942495  /**2496   * Get schedule for recepient of vested transfer2497   * @param address Substrate address of recipient2498   * @returns2499   */2500  async getVestingSchedules(address: TSubstrateAccount): Promise<{start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}[]> {2501    const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2502    return schedule.map((schedule: any) => {2503      return {2504        start: BigInt(schedule.start),2505        period: BigInt(schedule.period),2506        periodCount: BigInt(schedule.periodCount),2507        perPeriod: BigInt(schedule.perPeriod),2508      };2509    });2510  }25112512  /**2513   * Claim vested tokens2514   * @param signer signers Keyring2515   */2516  async claim(signer: TSigner) {2517    const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2518    const event = result.result.events2519      .find(e => e.event.section === 'vesting' &&2520            e.event.method === 'Claimed' &&2521            e.event.data[0].toHuman() === signer.address);2522    if (!event) throw Error('Cannot find claim in events');2523  }2524}25252526class AddressGroup extends HelperGroup<ChainHelperBase> {2527  /**2528   * Normalizes the address to the specified ss58 format, by default ```42```.2529   * @param address substrate address2530   * @param ss58Format format for address conversion, by default ```42```2531   * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2532   * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2533   */2534  normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2535    return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2536  }25372538  /**2539   * Get address in the connected chain format2540   * @param address substrate address2541   * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2542   * @returns address in chain format2543   */2544  normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2545    return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2546  }25472548  /**2549   * Get substrate mirror of an ethereum address2550   * @param ethAddress ethereum address2551   * @param toChainFormat false for normalized account2552   * @example ethToSubstrate('0x9F0583DbB855d...')2553   * @returns substrate mirror of a provided ethereum address2554   */2555  ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2556    return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2557  }25582559  /**2560   * Get ethereum mirror of a substrate address2561   * @param subAddress substrate account2562   * @example substrateToEth("5DnSF6RRjwteE3BrC...")2563   * @returns ethereum mirror of a provided substrate address2564   */2565  substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2566    return CrossAccountId.translateSubToEth(subAddress);2567  }25682569  /**2570   * Encode key to substrate address2571   * @param key key for encoding address2572   * @param ss58Format prefix for encoding to the address of the corresponding network2573   * @returns encoded substrate address2574   */2575  encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2576    const u8a :Uint8Array = typeof key === 'string'2577      ? hexToU8a(key)2578      : typeof key === 'bigint'2579        ? hexToU8a(key.toString(16))2580        : key;25812582    if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2583      throw new Error(`ss58Format is not valid, received ${typeof ss58Format} "${ss58Format}"`);2584    }25852586    const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2587    if (!allowedDecodedLengths.includes(u8a.length)) {2588      throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2589    }25902591    const u8aPrefix = ss58Format < 642592      ? new Uint8Array([ss58Format])2593      : new Uint8Array([2594        ((ss58Format & 0xfc) >> 2) | 0x40,2595        (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2596      ]);25972598    const input = u8aConcat(u8aPrefix, u8a);25992600    return base58Encode(u8aConcat(2601      input,2602      blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2603    ));2604  }26052606  /**2607   * Restore substrate address from bigint representation2608   * @param number decimal representation of substrate address2609   * @returns substrate address2610   */2611  restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2612    if (this.helper.api === null) {2613      throw 'Not connected';2614    }2615    const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2616    if (res === undefined || res === null) {2617      throw 'Restore address error';2618    }2619    return res.toString();2620  }26212622  /**2623   * Convert etherium cross account id to substrate cross account id2624   * @param ethCrossAccount etherium cross account2625   * @returns substrate cross account id2626   */2627  convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2628    if (ethCrossAccount.sub === '0') {2629      return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2630    }26312632    const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2633    return {Substrate: ss58};2634  }26352636  paraSiblingSovereignAccount(paraid: number) {2637    // We are getting a *sibling* parachain sovereign account,2638    // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2639    const siblingPrefix = '0x7369626c';26402641    const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2642    const suffix = '000000000000000000000000000000000000000000000000';26432644    return siblingPrefix + encodedParaId + suffix;2645  }2646}26472648class StakingGroup extends HelperGroup<UniqueHelper> {2649  /**2650   * Stake tokens for App Promotion2651   * @param signer keyring of signer2652   * @param amountToStake amount of tokens to stake2653   * @param label extra label for log2654   * @returns2655   */2656  async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2657    if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2658    const _stakeResult = await this.helper.executeExtrinsic(2659      signer, 'api.tx.appPromotion.stake',2660      [amountToStake], true,2661    );2662    // TODO extract info from stakeResult2663    return true;2664  }26652666  /**2667   * Unstake all staked tokens2668   * @param signer keyring of signer2669   * @param amountToUnstake amount of tokens to unstake2670   * @param label extra label for log2671   * @returns block hash where unstake happened2672   */2673  async unstakeAll(signer: TSigner, label?: string): Promise<string> {2674    if(typeof label === 'undefined') label = `${signer.address}`;2675    const unstakeResult = await this.helper.executeExtrinsic(2676      signer, 'api.tx.appPromotion.unstakeAll',2677      [], true,2678    );2679    return unstakeResult.blockHash;2680  }26812682  /**2683   * Unstake the part of a staked tokens2684   * @param signer keyring of signer2685   * @param amount amount of tokens to unstake2686   * @param label extra label for log2687   * @returns block hash where unstake happened2688   */2689  async unstakePartial(signer: TSigner, amount: bigint, label?: string): Promise<string> {2690    if(typeof label === 'undefined') label = `${signer.address}`;2691    const unstakeResult = await this.helper.executeExtrinsic(2692      signer, 'api.tx.appPromotion.unstakePartial',2693      [amount], true,2694    );2695    return unstakeResult.blockHash;2696  }26972698  /**2699   * Get total number of active stakes2700   * @param address substrate address2701   * @returns {number}2702   */2703  async getStakesNumber(address: ICrossAccountId): Promise<number> {2704    if (address.Ethereum) throw Error('only substrate address');2705    return (await this.helper.callRpc('api.query.appPromotion.stakesPerAccount', [address.Substrate])).toNumber();2706  }27072708  /**2709   * Get total staked amount for address2710   * @param address substrate or ethereum address2711   * @returns total staked amount2712   */2713  async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2714    if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2715    return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2716  }27172718  /**2719   * Get total staked per block2720   * @param address substrate or ethereum address2721   * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2722   */2723  async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2724    const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2725    return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2726      return {2727        block: block.toBigInt(),2728        amount: amount.toBigInt(),2729      };2730    });2731  }27322733  /**2734   * Get total pending unstake amount for address2735   * @param address substrate or ethereum address2736   * @returns total pending unstake amount2737   */2738  async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2739    return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2740  }27412742  /**2743   * Get pending unstake amount per block for address2744   * @param address substrate or ethereum address2745   * @returns array of pending stakes. `block` – the number of the block in which the unstake was made. `amount` - the number of tokens unstaked in the block2746   */2747  async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2748    const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2749    const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2750      return {2751        block: block.toBigInt(),2752        amount: amount.toBigInt(),2753      };2754    });2755    return result;2756  }2757}27582759class SchedulerGroup extends HelperGroup<UniqueHelper> {2760  constructor(helper: UniqueHelper) {2761    super(helper);2762  }27632764  cancelScheduled(signer: TSigner, scheduledId: string) {2765    return this.helper.executeExtrinsic(2766      signer,2767      'api.tx.scheduler.cancelNamed',2768      [scheduledId],2769      true,2770    );2771  }27722773  changePriority(signer: TSigner, scheduledId: string, priority: number) {2774    return this.helper.executeExtrinsic(2775      signer,2776      'api.tx.scheduler.changeNamedPriority',2777      [scheduledId, priority],2778      true,2779    );2780  }27812782  scheduleAt<T extends UniqueHelper>(2783    executionBlockNumber: number,2784    options: ISchedulerOptions = {},2785  ) {2786    return this.schedule<T>('schedule', executionBlockNumber, options);2787  }27882789  scheduleAfter<T extends UniqueHelper>(2790    blocksBeforeExecution: number,2791    options: ISchedulerOptions = {},2792  ) {2793    return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2794  }27952796  schedule<T extends UniqueHelper>(2797    scheduleFn: 'schedule' | 'scheduleAfter',2798    blocksNum: number,2799    options: ISchedulerOptions = {},2800  ) {2801    // eslint-disable-next-line @typescript-eslint/naming-convention2802    const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2803    return this.helper.clone(ScheduledHelperType, {2804      scheduleFn,2805      blocksNum,2806      options,2807    }) as T;2808  }2809}28102811class CollatorSelectionGroup extends HelperGroup<UniqueHelper> {2812  //todo:collator documentation2813  addInvulnerable(signer: TSigner, address: string) {2814    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.addInvulnerable', [address]);2815  }28162817  removeInvulnerable(signer: TSigner, address: string) {2818    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.removeInvulnerable', [address]);2819  }28202821  async getInvulnerables(): Promise<string[]> {2822    return (await this.helper.callRpc('api.query.collatorSelection.invulnerables')).map((x: any) => x.toHuman());2823  }28242825  /** and also total max invulnerables */2826  maxCollators(): number {2827    return (this.helper.getApi().consts.configuration.defaultCollatorSelectionMaxCollators.toJSON() as number);2828  }28292830  async getDesiredCollators(): Promise<number> {2831    return (await this.helper.callRpc('api.query.configuration.collatorSelectionDesiredCollatorsOverride')).toNumber();2832  }28332834  setLicenseBond(signer: TSigner, amount: bigint) {2835    return this.helper.executeExtrinsic(signer, 'api.tx.configuration.setCollatorSelectionLicenseBond', [amount]);2836  }28372838  async getLicenseBond(): Promise<bigint> {2839    return (await this.helper.callRpc('api.query.configuration.collatorSelectionLicenseBondOverride')).toBigInt();2840  }28412842  obtainLicense(signer: TSigner) {2843    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.getLicense', []);2844  }28452846  releaseLicense(signer: TSigner) {2847    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.releaseLicense', []);2848  }28492850  forceReleaseLicense(signer: TSigner, released: string) {2851    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.forceReleaseLicense', [released]);2852  }28532854  async hasLicense(address: string): Promise<bigint> {2855    return (await this.helper.callRpc('api.query.collatorSelection.licenseDepositOf', [address])).toBigInt();2856  }28572858  onboard(signer: TSigner) {2859    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.onboard', []);2860  }28612862  offboard(signer: TSigner) {2863    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.offboard', []);2864  }28652866  async getCandidates(): Promise<string[]> {2867    return (await this.helper.callRpc('api.query.collatorSelection.candidates')).map((x: any) => x.toHuman());2868  }2869}28702871class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2872  async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2873    await this.helper.executeExtrinsic(2874      signer,2875      'api.tx.foreignAssets.registerForeignAsset',2876      [ownerAddress, location, metadata],2877      true,2878    );2879  }28802881  async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2882    await this.helper.executeExtrinsic(2883      signer,2884      'api.tx.foreignAssets.updateForeignAsset',2885      [foreignAssetId, location, metadata],2886      true,2887    );2888  }2889}28902891class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2892  palletName: string;28932894  constructor(helper: T, palletName: string) {2895    super(helper);28962897    this.palletName = palletName;2898  }28992900  async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {2901    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);2902  }29032904  async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {2905    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);2906  }29072908  async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint) {2909    const destination = {2910      V1: {2911        parents: 0,2912        interior: {2913          X1: {2914            Parachain: destinationParaId,2915          },2916        },2917      },2918    };29192920    const beneficiary = {2921      V1: {2922        parents: 0,2923        interior: {2924          X1: {2925            AccountId32: {2926              network: 'Any',2927              id: targetAccount,2928            },2929          },2930        },2931      },2932    };29332934    const assets = {2935      V1: [2936        {2937          id: {2938            Concrete: {2939              parents: 0,2940              interior: 'Here',2941            },2942          },2943          fun: {2944            Fungible: amount,2945          },2946        },2947      ],2948    };29492950    const feeAssetItem = 0;29512952    await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);2953  }2954}29552956class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2957  async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {2958    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2959  }29602961  async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {2962    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2963  }29642965  async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {2966    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2967  }2968}29692970class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2971  async accounts(address: string, currencyId: any) {2972    const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2973    return BigInt(free);2974  }2975}29762977class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2978  async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2979    await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2980  }29812982  async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2983    await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2984  }29852986  async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2987    await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2988  }29892990  async account(assetId: string | number, address: string) {2991    const accountAsset = (2992      await this.helper.callRpc('api.query.assets.account', [assetId, address])2993    ).toJSON()! as any;29942995    if (accountAsset !== null) {2996      return BigInt(accountAsset['balance']);2997    } else {2998      return null;2999    }3000  }3001}30023003class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {3004  async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {3005    await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);3006  }3007}30083009class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {3010  makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {3011    const apiPrefix = 'api.tx.assetManager.';30123013    const registerTx = this.helper.constructApiCall(3014      apiPrefix + 'registerForeignAsset',3015      [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],3016    );30173018    const setUnitsTx = this.helper.constructApiCall(3019      apiPrefix + 'setAssetUnitsPerSecond',3020      [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],3021    );30223023    const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);3024    const encodedProposal = batchCall?.method.toHex() || '';3025    return encodedProposal;3026  }30273028  async assetTypeId(location: any) {3029    return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);3030  }3031}30323033class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {3034  notePreimagePallet: string;30353036  constructor(helper: MoonbeamHelper, options: {[key: string]: any} = {}) {3037    super(helper);3038    this.notePreimagePallet = options.notePreimagePallet;3039  }30403041  async notePreimage(signer: TSigner, encodedProposal: string) {3042    await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);3043  }30443045  externalProposeMajority(proposal: any) {3046    return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);3047  }30483049  fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {3050    return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);3051  }30523053  async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {3054    await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);3055  }3056}30573058class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {3059  collective: string;30603061  constructor(helper: MoonbeamHelper, collective: string) {3062    super(helper);30633064    this.collective = collective;3065  }30663067  async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {3068    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);3069  }30703071  async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {3072    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);3073  }30743075  async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {3076    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);3077  }30783079  async proposalCount() {3080    return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));3081  }3082}30833084export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;3085export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;30863087export class UniqueHelper extends ChainHelperBase {3088  balance: BalanceGroup<UniqueHelper>;3089  collection: CollectionGroup;3090  nft: NFTGroup;3091  rft: RFTGroup;3092  ft: FTGroup;3093  staking: StakingGroup;3094  scheduler: SchedulerGroup;3095  collatorSelection: CollatorSelectionGroup;3096  foreignAssets: ForeignAssetsGroup;3097  xcm: XcmGroup<UniqueHelper>;3098  xTokens: XTokensGroup<UniqueHelper>;3099  tokens: TokensGroup<UniqueHelper>;31003101  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3102    super(logger, options.helperBase ?? UniqueHelper);31033104    this.balance = new BalanceGroup(this);3105    this.collection = new CollectionGroup(this);3106    this.nft = new NFTGroup(this);3107    this.rft = new RFTGroup(this);3108    this.ft = new FTGroup(this);3109    this.staking = new StakingGroup(this);3110    this.scheduler = new SchedulerGroup(this);3111    this.collatorSelection = new CollatorSelectionGroup(this);3112    this.foreignAssets = new ForeignAssetsGroup(this);3113    this.xcm = new XcmGroup(this, 'polkadotXcm');3114    this.xTokens = new XTokensGroup(this);3115    this.tokens = new TokensGroup(this);3116  }31173118  getSudo<T extends UniqueHelper>() {3119    // eslint-disable-next-line @typescript-eslint/naming-convention3120    const SudoHelperType = SudoHelper(this.helperBase);3121    return this.clone(SudoHelperType) as T;3122  }3123}31243125export class XcmChainHelper extends ChainHelperBase {3126  async connect(wsEndpoint: string, _listeners?: any): Promise<void> {3127    const wsProvider = new WsProvider(wsEndpoint);3128    this.api = new ApiPromise({3129      provider: wsProvider,3130    });3131    await this.api.isReadyOrError;3132    this.network = await UniqueHelper.detectNetwork(this.api);3133  }3134}31353136export class RelayHelper extends XcmChainHelper {3137  balance: SubstrateBalanceGroup<RelayHelper>;3138  xcm: XcmGroup<RelayHelper>;31393140  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3141    super(logger, options.helperBase ?? RelayHelper);31423143    this.balance = new SubstrateBalanceGroup(this);3144    this.xcm = new XcmGroup(this, 'xcmPallet');3145  }3146}31473148export class WestmintHelper extends XcmChainHelper {3149  balance: SubstrateBalanceGroup<WestmintHelper>;3150  xcm: XcmGroup<WestmintHelper>;3151  assets: AssetsGroup<WestmintHelper>;3152  xTokens: XTokensGroup<WestmintHelper>;31533154  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3155    super(logger, options.helperBase ?? WestmintHelper);31563157    this.balance = new SubstrateBalanceGroup(this);3158    this.xcm = new XcmGroup(this, 'polkadotXcm');3159    this.assets = new AssetsGroup(this);3160    this.xTokens = new XTokensGroup(this);3161  }3162}31633164export class MoonbeamHelper extends XcmChainHelper {3165  balance: EthereumBalanceGroup<MoonbeamHelper>;3166  assetManager: MoonbeamAssetManagerGroup;3167  assets: AssetsGroup<MoonbeamHelper>;3168  xTokens: XTokensGroup<MoonbeamHelper>;3169  democracy: MoonbeamDemocracyGroup;3170  collective: {3171    council: MoonbeamCollectiveGroup,3172    techCommittee: MoonbeamCollectiveGroup,3173  };31743175  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3176    super(logger, options.helperBase ?? MoonbeamHelper);31773178    this.balance = new EthereumBalanceGroup(this);3179    this.assetManager = new MoonbeamAssetManagerGroup(this);3180    this.assets = new AssetsGroup(this);3181    this.xTokens = new XTokensGroup(this);3182    this.democracy = new MoonbeamDemocracyGroup(this, options);3183    this.collective = {3184      council: new MoonbeamCollectiveGroup(this, 'councilCollective'),3185      techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),3186    };3187  }3188}31893190export class AcalaHelper extends XcmChainHelper {3191  balance: SubstrateBalanceGroup<AcalaHelper>;3192  assetRegistry: AcalaAssetRegistryGroup;3193  xTokens: XTokensGroup<AcalaHelper>;3194  tokens: TokensGroup<AcalaHelper>;31953196  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3197    super(logger, options.helperBase ?? AcalaHelper);31983199    this.balance = new SubstrateBalanceGroup(this);3200    this.assetRegistry = new AcalaAssetRegistryGroup(this);3201    this.xTokens = new XTokensGroup(this);3202    this.tokens = new TokensGroup(this);3203  }32043205  getSudo<T extends AcalaHelper>() {3206    // eslint-disable-next-line @typescript-eslint/naming-convention3207    const SudoHelperType = SudoHelper(this.helperBase);3208    return this.clone(SudoHelperType) as T;3209  }3210}32113212// eslint-disable-next-line @typescript-eslint/naming-convention3213function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3214  return class extends Base {3215    scheduleFn: 'schedule' | 'scheduleAfter';3216    blocksNum: number;3217    options: ISchedulerOptions;32183219    constructor(...args: any[]) {3220      const logger = args[0] as ILogger;3221      const options = args[1] as {3222        scheduleFn: 'schedule' | 'scheduleAfter',3223        blocksNum: number,3224        options: ISchedulerOptions3225      };32263227      super(logger);32283229      this.scheduleFn = options.scheduleFn;3230      this.blocksNum = options.blocksNum;3231      this.options = options.options;3232    }32333234    executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3235      const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);32363237      const mandatorySchedArgs = [3238        this.blocksNum,3239        this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3240        this.options.priority ?? null,3241        scheduledTx,3242      ];32433244      let schedArgs;3245      let scheduleFn;32463247      if (this.options.scheduledId) {3248        schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];32493250        if (this.scheduleFn == 'schedule') {3251          scheduleFn = 'scheduleNamed';3252        } else if (this.scheduleFn == 'scheduleAfter') {3253          scheduleFn = 'scheduleNamedAfter';3254        }3255      } else {3256        schedArgs = mandatorySchedArgs;3257        scheduleFn = this.scheduleFn;3258      }32593260      const extrinsic = 'api.tx.scheduler.' +  scheduleFn;32613262      return super.executeExtrinsic(3263        sender,3264        extrinsic,3265        schedArgs,3266        expectSuccess,3267      );3268    }3269  };3270}32713272// eslint-disable-next-line @typescript-eslint/naming-convention3273function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3274  return class extends Base {3275    constructor(...args: any[]) {3276      super(...args);3277    }32783279    async executeExtrinsic(3280      sender: IKeyringPair,3281      extrinsic: string,3282      params: any[],3283      expectSuccess?: boolean,3284      options: Partial<SignerOptions>|null = null,3285    ): Promise<ITransactionResult> {3286      const call = this.constructApiCall(extrinsic, params);3287      const result = await super.executeExtrinsic(3288        sender,3289        'api.tx.sudo.sudo',3290        [call],3291        expectSuccess,3292        options,3293      );32943295      if (result.status === 'Fail') return result;32963297      const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;3298      if (data.isErr) {3299        if (data.asErr.isModule) {3300          const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;3301          const metaError = super.getApi()?.registry.findMetaError(error);3302          throw new Error(`${metaError.section}.${metaError.name}`);3303        } else {3304          throw new Error(data.asErr.toHuman());3305        }3306      }3307      return result;3308    }3309  };3310}33113312export class UniqueBaseCollection {3313  helper: UniqueHelper;3314  collectionId: number;33153316  constructor(collectionId: number, uniqueHelper: UniqueHelper) {3317    this.collectionId = collectionId;3318    this.helper = uniqueHelper;3319  }33203321  async getData() {3322    return await this.helper.collection.getData(this.collectionId);3323  }33243325  async getLastTokenId() {3326    return await this.helper.collection.getLastTokenId(this.collectionId);3327  }33283329  async doesTokenExist(tokenId: number) {3330    return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3331  }33323333  async getAdmins() {3334    return await this.helper.collection.getAdmins(this.collectionId);3335  }33363337  async getAllowList() {3338    return await this.helper.collection.getAllowList(this.collectionId);3339  }33403341  async getEffectiveLimits() {3342    return await this.helper.collection.getEffectiveLimits(this.collectionId);3343  }33443345  async getProperties(propertyKeys?: string[] | null) {3346    return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3347  }33483349  async getPropertiesConsumedSpace() {3350    return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3351  }33523353  async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3354    return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3355  }33563357  async getOptions() {3358    return await this.helper.collection.getCollectionOptions(this.collectionId);3359  }33603361  async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3362    return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3363  }33643365  async confirmSponsorship(signer: TSigner) {3366    return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3367  }33683369  async removeSponsor(signer: TSigner) {3370    return await this.helper.collection.removeSponsor(signer, this.collectionId);3371  }33723373  async setLimits(signer: TSigner, limits: ICollectionLimits) {3374    return await this.helper.collection.setLimits(signer, this.collectionId, limits);3375  }33763377  async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3378    return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3379  }33803381  async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3382    return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3383  }33843385  async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3386    return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3387  }33883389  async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3390    return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3391  }33923393  async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3394    return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3395  }33963397  async setProperties(signer: TSigner, properties: IProperty[]) {3398    return await this.helper.collection.setProperties(signer, this.collectionId, properties);3399  }34003401  async deleteProperties(signer: TSigner, propertyKeys: string[]) {3402    return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3403  }34043405  async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3406    return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3407  }34083409  async enableNesting(signer: TSigner, permissions: INestingPermissions) {3410    return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3411  }34123413  async disableNesting(signer: TSigner) {3414    return await this.helper.collection.disableNesting(signer, this.collectionId);3415  }34163417  async burn(signer: TSigner) {3418    return await this.helper.collection.burn(signer, this.collectionId);3419  }34203421  scheduleAt<T extends UniqueHelper>(3422    executionBlockNumber: number,3423    options: ISchedulerOptions = {},3424  ) {3425    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3426    return new UniqueBaseCollection(this.collectionId, scheduledHelper);3427  }34283429  scheduleAfter<T extends UniqueHelper>(3430    blocksBeforeExecution: number,3431    options: ISchedulerOptions = {},3432  ) {3433    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3434    return new UniqueBaseCollection(this.collectionId, scheduledHelper);3435  }34363437  getSudo<T extends UniqueHelper>() {3438    return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3439  }3440}344134423443export class UniqueNFTCollection extends UniqueBaseCollection {3444  getTokenObject(tokenId: number) {3445    return new UniqueNFToken(tokenId, this);3446  }34473448  async getTokensByAddress(addressObj: ICrossAccountId) {3449    return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3450  }34513452  async getToken(tokenId: number, blockHashAt?: string) {3453    return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3454  }34553456  async getTokenOwner(tokenId: number, blockHashAt?: string) {3457    return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3458  }34593460  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3461    return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3462  }34633464  async getTokenChildren(tokenId: number, blockHashAt?: string) {3465    return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3466  }34673468  async getPropertyPermissions(propertyKeys: string[] | null = null) {3469    return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3470  }34713472  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3473    return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3474  }34753476  async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3477    const api = this.helper.getApi();3478    const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();34793480    return (props! as any).consumedSpace;3481  }34823483  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3484    return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3485  }34863487  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3488    return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3489  }34903491  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3492    return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3493  }34943495  async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3496    return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3497  }34983499  async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3500    return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3501  }35023503  async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3504    return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3505  }35063507  async burnToken(signer: TSigner, tokenId: number) {3508    return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3509  }35103511  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3512    return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3513  }35143515  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3516    return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3517  }35183519  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3520    return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3521  }35223523  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3524    return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3525  }35263527  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3528    return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3529  }35303531  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3532    return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3533  }35343535  scheduleAt<T extends UniqueHelper>(3536    executionBlockNumber: number,3537    options: ISchedulerOptions = {},3538  ) {3539    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3540    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3541  }35423543  scheduleAfter<T extends UniqueHelper>(3544    blocksBeforeExecution: number,3545    options: ISchedulerOptions = {},3546  ) {3547    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3548    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3549  }35503551  getSudo<T extends UniqueHelper>() {3552    return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3553  }3554}355535563557export class UniqueRFTCollection extends UniqueBaseCollection {3558  getTokenObject(tokenId: number) {3559    return new UniqueRFToken(tokenId, this);3560  }35613562  async getToken(tokenId: number, blockHashAt?: string) {3563    return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3564  }35653566  async getTokenOwner(tokenId: number, blockHashAt?: string) {3567    return await this.helper.rft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3568  }35693570  async getTokensByAddress(addressObj: ICrossAccountId) {3571    return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3572  }35733574  async getTop10TokenOwners(tokenId: number) {3575    return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3576  }35773578  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3579    return await this.helper.rft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3580  }35813582  async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3583    return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3584  }35853586  async getTokenTotalPieces(tokenId: number) {3587    return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3588  }35893590  async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3591    return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3592  }35933594  async getPropertyPermissions(propertyKeys: string[] | null = null) {3595    return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3596  }35973598  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3599    return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3600  }36013602  async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3603    const api = this.helper.getApi();3604    const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();36053606    return (props! as any).consumedSpace;3607  }36083609  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3610    return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3611  }36123613  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3614    return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3615  }36163617  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3618    return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3619  }36203621  async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3622    return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3623  }36243625  async mintToken(signer: TSigner, pieces = 1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3626    return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3627  }36283629  async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3630    return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3631  }36323633  async burnToken(signer: TSigner, tokenId: number, amount=1n) {3634    return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3635  }36363637  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId,  amount=1n) {3638    return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3639  }36403641  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3642    return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3643  }36443645  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3646    return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3647  }36483649  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3650    return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3651  }36523653  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3654    return await this.helper.rft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3655  }36563657  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3658    return await this.helper.rft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3659  }36603661  scheduleAt<T extends UniqueHelper>(3662    executionBlockNumber: number,3663    options: ISchedulerOptions = {},3664  ) {3665    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3666    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3667  }36683669  scheduleAfter<T extends UniqueHelper>(3670    blocksBeforeExecution: number,3671    options: ISchedulerOptions = {},3672  ) {3673    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3674    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3675  }36763677  getSudo<T extends UniqueHelper>() {3678    return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3679  }3680}368136823683export class UniqueFTCollection extends UniqueBaseCollection {3684  async getBalance(addressObj: ICrossAccountId) {3685    return await this.helper.ft.getBalance(this.collectionId, addressObj);3686  }36873688  async getTotalPieces() {3689    return await this.helper.ft.getTotalPieces(this.collectionId);3690  }36913692  async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3693    return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3694  }36953696  async getTop10Owners() {3697    return await this.helper.ft.getTop10Owners(this.collectionId);3698  }36993700  async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3701    return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3702  }37033704  async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3705    return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3706  }37073708  async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3709    return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3710  }37113712  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3713    return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3714  }37153716  async burnTokens(signer: TSigner, amount=1n) {3717    return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3718  }37193720  async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3721    return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3722  }37233724  async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3725    return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3726  }37273728  scheduleAt<T extends UniqueHelper>(3729    executionBlockNumber: number,3730    options: ISchedulerOptions = {},3731  ) {3732    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3733    return new UniqueFTCollection(this.collectionId, scheduledHelper);3734  }37353736  scheduleAfter<T extends UniqueHelper>(3737    blocksBeforeExecution: number,3738    options: ISchedulerOptions = {},3739  ) {3740    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3741    return new UniqueFTCollection(this.collectionId, scheduledHelper);3742  }37433744  getSudo<T extends UniqueHelper>() {3745    return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3746  }3747}374837493750export class UniqueBaseToken {3751  collection: UniqueNFTCollection | UniqueRFTCollection;3752  collectionId: number;3753  tokenId: number;37543755  constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3756    this.collection = collection;3757    this.collectionId = collection.collectionId;3758    this.tokenId = tokenId;3759  }37603761  async getNextSponsored(addressObj: ICrossAccountId) {3762    return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3763  }37643765  async getProperties(propertyKeys?: string[] | null) {3766    return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3767  }37683769  async getTokenPropertiesConsumedSpace() {3770    return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3771  }37723773  async setProperties(signer: TSigner, properties: IProperty[]) {3774    return await this.collection.setTokenProperties(signer, this.tokenId, properties);3775  }37763777  async deleteProperties(signer: TSigner, propertyKeys: string[]) {3778    return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3779  }37803781  async doesExist() {3782    return await this.collection.doesTokenExist(this.tokenId);3783  }37843785  nestingAccount() {3786    return this.collection.helper.util.getTokenAccount(this);3787  }37883789  scheduleAt<T extends UniqueHelper>(3790    executionBlockNumber: number,3791    options: ISchedulerOptions = {},3792  ) {3793    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3794    return new UniqueBaseToken(this.tokenId, scheduledCollection);3795  }37963797  scheduleAfter<T extends UniqueHelper>(3798    blocksBeforeExecution: number,3799    options: ISchedulerOptions = {},3800  ) {3801    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3802    return new UniqueBaseToken(this.tokenId, scheduledCollection);3803  }38043805  getSudo<T extends UniqueHelper>() {3806    return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3807  }3808}380938103811export class UniqueNFToken extends UniqueBaseToken {3812  collection: UniqueNFTCollection;38133814  constructor(tokenId: number, collection: UniqueNFTCollection) {3815    super(tokenId, collection);3816    this.collection = collection;3817  }38183819  async getData(blockHashAt?: string) {3820    return await this.collection.getToken(this.tokenId, blockHashAt);3821  }38223823  async getOwner(blockHashAt?: string) {3824    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3825  }38263827  async getTopmostOwner(blockHashAt?: string) {3828    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3829  }38303831  async getChildren(blockHashAt?: string) {3832    return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3833  }38343835  async nest(signer: TSigner, toTokenObj: IToken) {3836    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3837  }38383839  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3840    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3841  }38423843  async transfer(signer: TSigner, addressObj: ICrossAccountId) {3844    return await this.collection.transferToken(signer, this.tokenId, addressObj);3845  }38463847  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3848    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3849  }38503851  async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3852    return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3853  }38543855  async isApproved(toAddressObj: ICrossAccountId) {3856    return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3857  }38583859  async burn(signer: TSigner) {3860    return await this.collection.burnToken(signer, this.tokenId);3861  }38623863  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3864    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3865  }38663867  scheduleAt<T extends UniqueHelper>(3868    executionBlockNumber: number,3869    options: ISchedulerOptions = {},3870  ) {3871    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3872    return new UniqueNFToken(this.tokenId, scheduledCollection);3873  }38743875  scheduleAfter<T extends UniqueHelper>(3876    blocksBeforeExecution: number,3877    options: ISchedulerOptions = {},3878  ) {3879    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3880    return new UniqueNFToken(this.tokenId, scheduledCollection);3881  }38823883  getSudo<T extends UniqueHelper>() {3884    return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3885  }3886}38873888export class UniqueRFToken extends UniqueBaseToken {3889  collection: UniqueRFTCollection;38903891  constructor(tokenId: number, collection: UniqueRFTCollection) {3892    super(tokenId, collection);3893    this.collection = collection;3894  }38953896  async getData(blockHashAt?: string) {3897    return await this.collection.getToken(this.tokenId, blockHashAt);3898  }38993900  async getOwner(blockHashAt?: string) {3901    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3902  }39033904  async getTop10Owners() {3905    return await this.collection.getTop10TokenOwners(this.tokenId);3906  }39073908  async getTopmostOwner(blockHashAt?: string) {3909    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3910  }39113912  async nest(signer: TSigner, toTokenObj: IToken) {3913    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3914  }39153916  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3917    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3918  }39193920  async getBalance(addressObj: ICrossAccountId) {3921    return await this.collection.getTokenBalance(this.tokenId, addressObj);3922  }39233924  async getTotalPieces() {3925    return await this.collection.getTokenTotalPieces(this.tokenId);3926  }39273928  async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3929    return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3930  }39313932  async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3933    return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3934  }39353936  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3937    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3938  }39393940  async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3941    return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3942  }39433944  async repartition(signer: TSigner, amount: bigint) {3945    return await this.collection.repartitionToken(signer, this.tokenId, amount);3946  }39473948  async burn(signer: TSigner, amount=1n) {3949    return await this.collection.burnToken(signer, this.tokenId, amount);3950  }39513952  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3953    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3954  }39553956  scheduleAt<T extends UniqueHelper>(3957    executionBlockNumber: number,3958    options: ISchedulerOptions = {},3959  ) {3960    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3961    return new UniqueRFToken(this.tokenId, scheduledCollection);3962  }39633964  scheduleAfter<T extends UniqueHelper>(3965    blocksBeforeExecution: number,3966    options: ISchedulerOptions = {},3967  ) {3968    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3969    return new UniqueRFToken(this.tokenId, scheduledCollection);3970  }39713972  getSudo<T extends UniqueHelper>() {3973    return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3974  }3975}