git.delta.rocks / unique-network / refs/commits / 89fdc7343ec8

difftreelog

source

tests/src/util/playgrounds/unique.ts153.0 KiBsourcehistory
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 {SignerOptions} from '@polkadot/api/types/submittable';10import {ApiInterfaceEvents} from '@polkadot/api/types';11import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';12import {IKeyringPair} from '@polkadot/types/types';13import {hexToU8a} from '@polkadot/util/hex';14import {u8aConcat} from '@polkadot/util/u8a';15import {16  IApiListeners,17  IBlock,18  IEvent,19  IChainProperties,20  ICollectionCreationOptions,21  ICollectionLimits,22  ICollectionPermissions,23  ICrossAccountId,24  ICrossAccountIdLower,25  ILogger,26  INestingPermissions,27  IProperty,28  IStakingInfo,29  ISchedulerOptions,30  ISubstrateBalance,31  IToken,32  ITokenPropertyPermission,33  ITransactionResult,34  IUniqueHelperLog,35  TApiAllowedListeners,36  TEthereumAccount,37  TSigner,38  TSubstrateAccount,39  TNetworks,40  IForeignAssetMetadata,41  AcalaAssetMetadata,42  MoonbeamAssetInfo,43  DemocracyStandardAccountVote,44  IEthCrossAccountId,45} from './types';46import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';47import type {Vec} from '@polkadot/types-codec';48import {FrameSystemEventRecord} from '@polkadot/types/lookup';4950export class CrossAccountId implements ICrossAccountId {51  Substrate?: TSubstrateAccount;52  Ethereum?: TEthereumAccount;5354  constructor(account: ICrossAccountId) {55    if (account.Substrate) this.Substrate = account.Substrate;56    if (account.Ethereum) this.Ethereum = account.Ethereum;57  }5859  static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {60    switch (domain) {61      case 'Substrate': return new CrossAccountId({Substrate: account.address});62      case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();63    }64  }6566  static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {67    return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});68  }6970  static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {71    return encodeAddress(decodeAddress(address), ss58Format);72  }7374  static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {75    return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});76  }7778  withNormalizedSubstrate(ss58Format = 42): CrossAccountId {79    if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);80    return this;81  }8283  static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {84    return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));85  }8687  toEthereum(): CrossAccountId {88    if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});89    return this;90  }9192  static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {93    return evmToAddress(address, ss58Format);94  }9596  toSubstrate(ss58Format?: number): CrossAccountId {97    if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});98    return this;99  }100101  toLowerCase(): CrossAccountId {102    if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();103    if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();104    return this;105  }106}107108const nesting = {109  toChecksumAddress(address: string): string {110    if (typeof address === 'undefined') return '';111112    if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);113114    address = address.toLowerCase().replace(/^0x/i,'');115    const addressHash = keccakAsHex(address).replace(/^0x/i,'');116    const checksumAddress = ['0x'];117118    for (let i = 0; i < address.length; i++) {119      // If ith character is 8 to f then make it uppercase120      if (parseInt(addressHash[i], 16) > 7) {121        checksumAddress.push(address[i].toUpperCase());122      } else {123        checksumAddress.push(address[i]);124      }125    }126    return checksumAddress.join('');127  },128  tokenIdToAddress(collectionId: number, tokenId: number) {129    return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);130  },131};132133class UniqueUtil {134  static transactionStatus = {135    NOT_READY: 'NotReady',136    FAIL: 'Fail',137    SUCCESS: 'Success',138  };139140  static chainLogType = {141    EXTRINSIC: 'extrinsic',142    RPC: 'rpc',143  };144145  static getTokenAccount(token: IToken): CrossAccountId {146    return new CrossAccountId({Ethereum: this.getTokenAddress(token)});147  }148149  static getTokenAddress(token: IToken): string {150    return nesting.tokenIdToAddress(token.collectionId, token.tokenId);151  }152153  static getDefaultLogger(): ILogger {154    return {155      log(msg: any, level = 'INFO') {156        console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));157      },158      level: {159        ERROR: 'ERROR',160        WARNING: 'WARNING',161        INFO: 'INFO',162      },163    };164  }165166  static vec2str(arr: string[] | number[]) {167    return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');168  }169170  static str2vec(string: string) {171    if (typeof string !== 'string') return string;172    return Array.from(string).map(x => x.charCodeAt(0));173  }174175  static fromSeed(seed: string, ss58Format = 42) {176    const keyring = new Keyring({type: 'sr25519', ss58Format});177    return keyring.addFromUri(seed);178  }179180  static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {181    if (creationResult.status !== this.transactionStatus.SUCCESS) {182      throw Error('Unable to create collection!');183    }184185    let collectionId = null;186    creationResult.result.events.forEach(({event: {data, method, section}}) => {187      if ((section === 'common') && (method === 'CollectionCreated')) {188        collectionId = parseInt(data[0].toString(), 10);189      }190    });191192    if (collectionId === null) {193      throw Error('No CollectionCreated event was found!');194    }195196    return collectionId;197  }198199  static extractTokensFromCreationResult(creationResult: ITransactionResult): {200    success: boolean,201    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],202  } {203    if (creationResult.status !== this.transactionStatus.SUCCESS) {204      throw Error('Unable to create tokens!');205    }206    let success = false;207    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];208    creationResult.result.events.forEach(({event: {data, method, section}}) => {209      if (method === 'ExtrinsicSuccess') {210        success = true;211      } else if ((section === 'common') && (method === 'ItemCreated')) {212        tokens.push({213          collectionId: parseInt(data[0].toString(), 10),214          tokenId: parseInt(data[1].toString(), 10),215          owner: data[2].toHuman(),216          amount: data[3].toBigInt(),217        });218      }219    });220    return {success, tokens};221  }222223  static extractTokensFromBurnResult(burnResult: ITransactionResult): {224    success: boolean,225    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],226  } {227    if (burnResult.status !== this.transactionStatus.SUCCESS) {228      throw Error('Unable to burn tokens!');229    }230    let success = false;231    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];232    burnResult.result.events.forEach(({event: {data, method, section}}) => {233      if (method === 'ExtrinsicSuccess') {234        success = true;235      } else if ((section === 'common') && (method === 'ItemDestroyed')) {236        tokens.push({237          collectionId: parseInt(data[0].toString(), 10),238          tokenId: parseInt(data[1].toString(), 10),239          owner: data[2].toHuman(),240          amount: data[3].toBigInt(),241        });242      }243    });244    return {success, tokens};245  }246247  static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {248    let eventId = null;249    events.forEach(({event: {data, method, section}}) => {250      if ((section === expectedSection) && (method === expectedMethod)) {251        eventId = parseInt(data[0].toString(), 10);252      }253    });254255    if (eventId === null) {256      throw Error(`No ${expectedMethod} event was found!`);257    }258    return eventId === collectionId;259  }260261  static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {262    const normalizeAddress = (address: string | ICrossAccountId) => {263      if(typeof address === 'string') return address;264      const obj = {} as any;265      Object.keys(address).forEach(k => {266        obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];267      });268      if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);269      if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();270      return address;271    };272    let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;273    events.forEach(({event: {data, method, section}}) => {274      if ((section === 'common') && (method === 'Transfer')) {275        const hData = (data as any).toJSON();276        transfer = {277          collectionId: hData[0],278          tokenId: hData[1],279          from: normalizeAddress(hData[2]),280          to: normalizeAddress(hData[3]),281          amount: BigInt(hData[4]),282        };283      }284    });285    let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;286    isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);287    isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);288    isSuccess = isSuccess && amount === transfer.amount;289    return isSuccess;290  }291292  static bigIntToDecimals(number: bigint, decimals = 18) {293    const numberStr = number.toString();294    const dotPos = numberStr.length - decimals;295296    if (dotPos <= 0) {297      return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;298    } else {299      const intPart = numberStr.substring(0, dotPos);300      const fractPart = numberStr.substring(dotPos);301      return intPart + '.' + fractPart;302    }303  }304}305306class UniqueEventHelper {307  private static extractIndex(index: any): [number, number] | string {308    if(index.toRawType() === '[u8;2]') return [index[0], index[1]];309    return index.toJSON();310  }311312  private static extractSub(data: any, subTypes: any): {[key: string]: any} {313    let obj: any = {};314    let index = 0;315316    if (data.entries) {317      for(const [key, value] of data.entries()) {318        obj[key] = this.extractData(value, subTypes[index]);319        index++;320      }321    } else obj = data.toJSON();322323    return obj;324  }325326  private static toHuman(data: any) {327    return data && data.toHuman ? data.toHuman() : `${data}`;328  }329330  private static extractData(data: any, type: any): any {331    if(!type) return this.toHuman(data);332    if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();333    if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();334    if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);335    return this.toHuman(data);336  }337338  public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {339    const parsedEvents: IEvent[] = [];340341    events.forEach((record) => {342      const {event, phase} = record;343      const types = event.typeDef;344345      const eventData: IEvent = {346        section: event.section.toString(),347        method: event.method.toString(),348        index: this.extractIndex(event.index),349        data: [],350        phase: phase.toJSON(),351      };352353      event.data.forEach((val: any, index: number) => {354        eventData.data.push(this.extractData(val, types[index]));355      });356357      parsedEvents.push(eventData);358    });359360    return parsedEvents;361  }362}363364export class ChainHelperBase {365  helperBase: any;366367  transactionStatus = UniqueUtil.transactionStatus;368  chainLogType = UniqueUtil.chainLogType;369  util: typeof UniqueUtil;370  eventHelper: typeof UniqueEventHelper;371  logger: ILogger;372  api: ApiPromise | null;373  forcedNetwork: TNetworks | null;374  network: TNetworks | null;375  wsEndpoint: string | null;376  chainLog: IUniqueHelperLog[];377  children: ChainHelperBase[];378  address: AddressGroup;379  chain: ChainGroup;380381  constructor(logger?: ILogger, helperBase?: any) {382    this.helperBase = helperBase;383384    this.util = UniqueUtil;385    this.eventHelper = UniqueEventHelper;386    if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();387    this.logger = logger;388    this.api = null;389    this.forcedNetwork = null;390    this.network = null;391    this.wsEndpoint = null;392    this.chainLog = [];393    this.children = [];394    this.address = new AddressGroup(this);395    this.chain = new ChainGroup(this);396  }397398  clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {399    Object.setPrototypeOf(helperCls.prototype, this);400    const newHelper = new helperCls(this.logger, options);401402    newHelper.api = this.api;403    newHelper.network = this.network;404    newHelper.forceNetwork = this.forceNetwork;405406    this.children.push(newHelper);407408    return newHelper;409  }410411  getEndpoint(): string {412    if (this.wsEndpoint === null) throw Error('No connection was established');413    return this.wsEndpoint;414  }415416  getApi(): ApiPromise {417    if(this.api === null) throw Error('API not initialized');418    return this.api;419  }420421  async subscribeEvents(expectedEvents: {section: string, names: string[]}[]) {422    const collectedEvents: IEvent[] = [];423    const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {424      const ievents = this.eventHelper.extractEvents(events);425      ievents.forEach((event) => {426        expectedEvents.forEach((e => {427          if (event.section === e.section && e.names.includes(event.method)) {428            collectedEvents.push(event);429          }430        }));431      });432    });433    return {unsubscribe: unsubscribe as any, collectedEvents};434  }435436  clearChainLog(): void {437    this.chainLog = [];438  }439440  forceNetwork(value: TNetworks): void {441    this.forcedNetwork = value;442  }443444  async connect(wsEndpoint: string, listeners?: IApiListeners) {445    if (this.api !== null) throw Error('Already connected');446    const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);447    this.wsEndpoint = wsEndpoint;448    this.api = api;449    this.network = network;450  }451452  async disconnect() {453    for (const child of this.children) {454      child.clearApi();455    }456457    if (this.api === null) return;458    await this.api.disconnect();459    this.clearApi();460  }461462  clearApi() {463    this.api = null;464    this.network = null;465  }466467  static async detectNetwork(api: ApiPromise): Promise<TNetworks> {468    const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;469    const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];470471    if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;472473    if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;474    return 'opal';475  }476477  static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {478    const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});479    await api.isReady;480481    const network = await this.detectNetwork(api);482483    await api.disconnect();484485    return network;486  }487488  static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{489    api: ApiPromise;490    network: TNetworks;491  }> {492    if(typeof network === 'undefined' || network === null) network = 'opal';493    const supportedRPC = {494      opal: {495        unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,496      },497      quartz: {498        unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,499      },500      unique: {501        unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,502      },503      rococo: {},504      westend: {},505      moonbeam: {},506      moonriver: {},507      acala: {},508      karura: {},509      westmint: {},510    };511    if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);512    const rpc = supportedRPC[network];513514    // TODO: investigate how to replace rpc in runtime515    // api._rpcCore.addUserInterfaces(rpc);516517    const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});518519    await api.isReadyOrError;520521    if (typeof listeners === 'undefined') listeners = {};522    for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {523      if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;524      api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);525    }526527    return {api, network};528  }529530  getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {531    const {events, status} = data;532    if (status.isReady) {533      return this.transactionStatus.NOT_READY;534    }535    if (status.isBroadcast) {536      return this.transactionStatus.NOT_READY;537    }538    if (status.isInBlock || status.isFinalized) {539      const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');540      if (errors.length > 0) {541        return this.transactionStatus.FAIL;542      }543      if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {544        return this.transactionStatus.SUCCESS;545      }546    }547548    return this.transactionStatus.FAIL;549  }550551  signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {552    const sign = (callback: any) => {553      if(options !== null) return transaction.signAndSend(sender, options, callback);554      return transaction.signAndSend(sender, callback);555    };556    // eslint-disable-next-line no-async-promise-executor557    return new Promise(async (resolve, reject) => {558      try {559        const unsub = await sign((result: any) => {560          const status = this.getTransactionStatus(result);561562          if (status === this.transactionStatus.SUCCESS) {563            this.logger.log(`${label} successful`);564            unsub();565            resolve({result, status, blockHash: result.status.asInBlock.toHuman()});566          } else if (status === this.transactionStatus.FAIL) {567            let moduleError = null;568569            if (result.hasOwnProperty('dispatchError')) {570              const dispatchError = result['dispatchError'];571572              if (dispatchError) {573                if (dispatchError.isModule) {574                  const modErr = dispatchError.asModule;575                  const errorMeta = dispatchError.registry.findMetaError(modErr);576577                  moduleError = `${errorMeta.section}.${errorMeta.name}`;578                } else {579                  moduleError = dispatchError.toHuman();580                }581              } else {582                this.logger.log(result, this.logger.level.ERROR);583              }584            }585586            this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);587            unsub();588            reject({status, moduleError, result});589          }590        });591      } catch (e) {592        this.logger.log(e, this.logger.level.ERROR);593        reject(e);594      }595    });596  }597598  async signTransactionWithoutSending(signer: TSigner, tx: any) {599    const api = this.getApi();600    const signingInfo = await api.derive.tx.signingInfo(signer.address);601602    tx.sign(signer, {603      blockHash: api.genesisHash,604      genesisHash: api.genesisHash,605      runtimeVersion: api.runtimeVersion,606      nonce: signingInfo.nonce,607    });608609    return tx.toHex();610  }611612  async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {613    const api = this.getApi();614    const signingInfo = await api.derive.tx.signingInfo(signer.address);615616    // We need to sign the tx because617    // unsigned transactions does not have an inclusion fee618    tx.sign(signer, {619      blockHash: api.genesisHash,620      genesisHash: api.genesisHash,621      runtimeVersion: api.runtimeVersion,622      nonce: signingInfo.nonce,623    });624625    if (len === null) {626      return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;627    } else {628      return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;629    }630  }631632  constructApiCall(apiCall: string, params: any[]) {633    if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);634    let call = this.getApi() as any;635    for(const part of apiCall.slice(4).split('.')) {636      call = call[part];637      if (!call) {638        const advice = part.includes('_') ? ' Looks like it needs to be converted to camel case.' : '';639        throw Error(`Function ${part} of api call ${apiCall} not found.${advice}`);640      }641    }642    return call(...params);643  }644645  encodeApiCall(apiCall: string, params: any[]) {646    return this.constructApiCall(apiCall, params).method.toHex();647  }648649  async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {650    if(this.api === null) throw Error('API not initialized');651    if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);652653    const startTime = (new Date()).getTime();654    let result: ITransactionResult;655    let events: IEvent[] = [];656    try {657      result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;658      events = this.eventHelper.extractEvents(result.result.events);659      const errorEvent = events.find((event) => event.method == 'ExecutedFailed' || event.method == 'CreatedFailed');660      if (errorEvent)661        throw Error(errorEvent.method + ': ' + extrinsic);662    }663    catch(e) {664      if(!(e as object).hasOwnProperty('status')) throw e;665      result = e as ITransactionResult;666    }667668    const endTime = (new Date()).getTime();669670    const log = {671      executedAt: endTime,672      executionTime: endTime - startTime,673      type: this.chainLogType.EXTRINSIC,674      status: result.status,675      call: extrinsic,676      signer: this.getSignerAddress(sender),677      params,678    } as IUniqueHelperLog;679680    let errorMessage = '';681682    if(result.status !== this.transactionStatus.SUCCESS) {683      if (result.moduleError) {684        errorMessage = typeof result.moduleError === 'string'685          ? result.moduleError686          : `${Object.keys(result.moduleError)[0]}: ${Object.values(result.moduleError)[0]}`;687        log.moduleError = errorMessage;688      }689      else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;690    }691    if(events.length > 0) log.events = events;692693    this.chainLog.push(log);694695    if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {696      if (result.moduleError) throw Error(`${errorMessage}`);697      else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));698    }699    return result;700  }701702  async callRpc(rpc: string, params?: any[]) {703    if(typeof params === 'undefined') params = [];704    if(this.api === null) throw Error('API not initialized');705    if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);706707    const startTime = (new Date()).getTime();708    let result;709    let error = null;710    const log = {711      type: this.chainLogType.RPC,712      call: rpc,713      params,714    } as IUniqueHelperLog;715716    try {717      result = await this.constructApiCall(rpc, params);718    }719    catch(e) {720      error = e;721    }722723    const endTime = (new Date()).getTime();724725    log.executedAt = endTime;726    log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';727    log.executionTime = endTime - startTime;728729    this.chainLog.push(log);730731    if(error !== null) throw error;732733    return result;734  }735736  getSignerAddress(signer: IKeyringPair | string): string {737    if(typeof signer === 'string') return signer;738    return signer.address;739  }740741  fetchAllPalletNames(): string[] {742    if(this.api === null) throw Error('API not initialized');743    return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase()).sort();744  }745746  fetchMissingPalletNames(requiredPallets: string[]): string[] {747    const palletNames = this.fetchAllPalletNames();748    return requiredPallets.filter(p => !palletNames.includes(p));749  }750}751752753class HelperGroup<T extends ChainHelperBase> {754  helper: T;755756  constructor(uniqueHelper: T) {757    this.helper = uniqueHelper;758  }759}760761762class CollectionGroup extends HelperGroup<UniqueHelper> {763  /**764 * Get number of blocks when sponsored transaction is available.765 *766 * @param collectionId ID of collection767 * @param tokenId ID of token768 * @param addressObj address for which the sponsorship is checked769 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});770 * @returns number of blocks or null if sponsorship hasn't been set771 */772  async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {773    return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();774  }775776  /**777   * Get the number of created collections.778   *779   * @returns number of created collections780   */781  async getTotalCount(): Promise<number> {782    return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();783  }784785  /**786   * Get information about the collection with additional data,787   * including the number of tokens it contains, its administrators,788   * the normalized address of the collection's owner, and decoded name and description.789   *790   * @param collectionId ID of collection791   * @example await getData(2)792   * @returns collection information object793   */794  async getData(collectionId: number): Promise<{795    id: number;796    name: string;797    description: string;798    tokensCount: number;799    admins: CrossAccountId[];800    normalizedOwner: TSubstrateAccount;801    raw: any802  } | null> {803    const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);804    const humanCollection = collection.toHuman(), collectionData = {805      id: collectionId, name: null, description: null, tokensCount: 0, admins: [],806      raw: humanCollection,807    } as any, jsonCollection = collection.toJSON();808    if (humanCollection === null) return null;809    collectionData.raw.limits = jsonCollection.limits;810    collectionData.raw.permissions = jsonCollection.permissions;811    collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);812    for (const key of ['name', 'description']) {813      collectionData[key] = this.helper.util.vec2str(humanCollection[key]);814    }815816    collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))817      ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)818      : 0;819    collectionData.admins = await this.getAdmins(collectionId);820821    return collectionData;822  }823824  /**825   * Get the addresses of the collection's administrators, optionally normalized.826   *827   * @param collectionId ID of collection828   * @param normalize whether to normalize the addresses to the default ss58 format829   * @example await getAdmins(1)830   * @returns array of administrators831   */832  async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {833    const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();834835    return normalize836      ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())837      : admins;838  }839840  /**841   * Get the addresses added to the collection allow-list, optionally normalized.842   * @param collectionId ID of collection843   * @param normalize whether to normalize the addresses to the default ss58 format844   * @example await getAllowList(1)845   * @returns array of allow-listed addresses846   */847  async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {848    const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();849    return normalize850      ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())851      : allowListed;852  }853854  /**855   * Get the effective limits of the collection instead of null for default values856   *857   * @param collectionId ID of collection858   * @example await getEffectiveLimits(2)859   * @returns object of collection limits860   */861  async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {862    return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();863  }864865  /**866   * Burns the collection if the signer has sufficient permissions and collection is empty.867   *868   * @param signer keyring of signer869   * @param collectionId ID of collection870   * @example await helper.collection.burn(aliceKeyring, 3);871   * @returns ```true``` if extrinsic success, otherwise ```false```872   */873  async burn(signer: TSigner, collectionId: number): Promise<boolean> {874    const result = await this.helper.executeExtrinsic(875      signer,876      'api.tx.unique.destroyCollection', [collectionId],877      true,878    );879880    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');881  }882883  /**884   * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.885   *886   * @param signer keyring of signer887   * @param collectionId ID of collection888   * @param sponsorAddress Sponsor substrate address889   * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")890   * @returns ```true``` if extrinsic success, otherwise ```false```891   */892  async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {893    const result = await this.helper.executeExtrinsic(894      signer,895      'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],896      true,897    );898899    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');900  }901902  /**903   * Confirms consent to sponsor the collection on behalf of the signer.904   *905   * @param signer keyring of signer906   * @param collectionId ID of collection907   * @example confirmSponsorship(aliceKeyring, 10)908   * @returns ```true``` if extrinsic success, otherwise ```false```909   */910  async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {911    const result = await this.helper.executeExtrinsic(912      signer,913      'api.tx.unique.confirmSponsorship', [collectionId],914      true,915    );916917    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');918  }919920  /**921   * Removes the sponsor of a collection, regardless if it consented or not.922   *923   * @param signer keyring of signer924   * @param collectionId ID of collection925   * @example removeSponsor(aliceKeyring, 10)926   * @returns ```true``` if extrinsic success, otherwise ```false```927   */928  async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {929    const result = await this.helper.executeExtrinsic(930      signer,931      'api.tx.unique.removeCollectionSponsor', [collectionId],932      true,933    );934935    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');936  }937938  /**939   * Sets the limits of the collection. At least one limit must be specified for a correct call.940   *941   * @param signer keyring of signer942   * @param collectionId ID of collection943   * @param limits collection limits object944   * @example945   * await setLimits(946   *   aliceKeyring,947   *   10,948   *   {949   *     sponsorTransferTimeout: 0,950   *     ownerCanDestroy: false951   *   }952   * )953   * @returns ```true``` if extrinsic success, otherwise ```false```954   */955  async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {956    const result = await this.helper.executeExtrinsic(957      signer,958      'api.tx.unique.setCollectionLimits', [collectionId, limits],959      true,960    );961962    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');963  }964965  /**966   * Changes the owner of the collection to the new Substrate address.967   *968   * @param signer keyring of signer969   * @param collectionId ID of collection970   * @param ownerAddress substrate address of new owner971   * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")972   * @returns ```true``` if extrinsic success, otherwise ```false```973   */974  async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {975    const result = await this.helper.executeExtrinsic(976      signer,977      'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],978      true,979    );980981    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');982  }983984  /**985   * Adds a collection administrator.986   *987   * @param signer keyring of signer988   * @param collectionId ID of collection989   * @param adminAddressObj Administrator address (substrate or ethereum)990   * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})991   * @returns ```true``` if extrinsic success, otherwise ```false```992   */993  async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {994    const result = await this.helper.executeExtrinsic(995      signer,996      'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],997      true,998    );9991000    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');1001  }10021003  /**1004   * Removes a collection administrator.1005   *1006   * @param signer keyring of signer1007   * @param collectionId ID of collection1008   * @param adminAddressObj Administrator address (substrate or ethereum)1009   * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})1010   * @returns ```true``` if extrinsic success, otherwise ```false```1011   */1012  async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1013    const result = await this.helper.executeExtrinsic(1014      signer,1015      'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],1016      true,1017    );10181019    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');1020  }10211022  /**1023   * Check if user is in allow list.1024   *1025   * @param collectionId ID of collection1026   * @param user Account to check1027   * @example await getAdmins(1)1028   * @returns is user in allow list1029   */1030  async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {1031    return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();1032  }10331034  /**1035   * Adds an address to allow list1036   * @param signer keyring of signer1037   * @param collectionId ID of collection1038   * @param addressObj address to add to the allow list1039   * @returns ```true``` if extrinsic success, otherwise ```false```1040   */1041  async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1042    const result = await this.helper.executeExtrinsic(1043      signer,1044      'api.tx.unique.addToAllowList', [collectionId, addressObj],1045      true,1046    );10471048    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1049  }10501051  /**1052   * Removes an address from allow list1053   *1054   * @param signer keyring of signer1055   * @param collectionId ID of collection1056   * @param addressObj address to remove from the allow list1057   * @returns ```true``` if extrinsic success, otherwise ```false```1058   */1059  async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1060    const result = await this.helper.executeExtrinsic(1061      signer,1062      'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1063      true,1064    );10651066    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1067  }10681069  /**1070   * Sets onchain permissions for selected collection.1071   *1072   * @param signer keyring of signer1073   * @param collectionId ID of collection1074   * @param permissions collection permissions object1075   * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1076   * @returns ```true``` if extrinsic success, otherwise ```false```1077   */1078  async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1079    const result = await this.helper.executeExtrinsic(1080      signer,1081      'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1082      true,1083    );10841085    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1086  }10871088  /**1089   * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1090   *1091   * @param signer keyring of signer1092   * @param collectionId ID of collection1093   * @param permissions nesting permissions object1094   * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1095   * @returns ```true``` if extrinsic success, otherwise ```false```1096   */1097  async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1098    return await this.setPermissions(signer, collectionId, {nesting: permissions});1099  }11001101  /**1102   * Disables nesting for selected collection.1103   *1104   * @param signer keyring of signer1105   * @param collectionId ID of collection1106   * @example disableNesting(aliceKeyring, 10);1107   * @returns ```true``` if extrinsic success, otherwise ```false```1108   */1109  async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1110    return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1111  }11121113  /**1114   * Sets onchain properties to the collection.1115   *1116   * @param signer keyring of signer1117   * @param collectionId ID of collection1118   * @param properties array of property objects1119   * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1120   * @returns ```true``` if extrinsic success, otherwise ```false```1121   */1122  async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1123    const result = await this.helper.executeExtrinsic(1124      signer,1125      'api.tx.unique.setCollectionProperties', [collectionId, properties],1126      true,1127    );11281129    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1130  }11311132  /**1133   * Get collection properties.1134   *1135   * @param collectionId ID of collection1136   * @param propertyKeys optionally filter the returned properties to only these keys1137   * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1138   * @returns array of key-value pairs1139   */1140  async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1141    return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1142  }11431144  async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1145    const api = this.helper.getApi();1146    const props = (await api.query.common.collectionProperties(collectionId)).toJSON();11471148    return (props! as any).consumedSpace;1149  }11501151  async getCollectionOptions(collectionId: number) {1152    return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1153  }11541155  /**1156   * Deletes onchain properties from the collection.1157   *1158   * @param signer keyring of signer1159   * @param collectionId ID of collection1160   * @param propertyKeys array of property keys to delete1161   * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1162   * @returns ```true``` if extrinsic success, otherwise ```false```1163   */1164  async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1165    const result = await this.helper.executeExtrinsic(1166      signer,1167      'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1168      true,1169    );11701171    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1172  }11731174  /**1175   * Changes the owner of the token.1176   *1177   * @param signer keyring of signer1178   * @param collectionId ID of collection1179   * @param tokenId ID of token1180   * @param addressObj address of a new owner1181   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1182   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1183   * @returns true if the token success, otherwise false1184   */1185  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1186    const result = await this.helper.executeExtrinsic(1187      signer,1188      'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1189      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1190    );11911192    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1193  }11941195  /**1196   *1197   * Change ownership of a token(s) on behalf of the owner.1198   *1199   * @param signer keyring of signer1200   * @param collectionId ID of collection1201   * @param tokenId ID of token1202   * @param fromAddressObj address on behalf of which the token will be sent1203   * @param toAddressObj new token owner1204   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1205   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1206   * @returns true if the token success, otherwise false1207   */1208  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1209    const result = await this.helper.executeExtrinsic(1210      signer,1211      'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1212      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1213    );1214    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1215  }12161217  /**1218   *1219   * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1220   *1221   * @param signer keyring of signer1222   * @param collectionId ID of collection1223   * @param tokenId ID of token1224   * @param amount amount of tokens to be burned. For NFT must be set to 1n1225   * @example burnToken(aliceKeyring, 10, 5);1226   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1227   */1228  async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1229    const burnResult = await this.helper.executeExtrinsic(1230      signer,1231      'api.tx.unique.burnItem', [collectionId, tokenId, amount],1232      true, // `Unable to burn token for ${label}`,1233    );1234    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1235    if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1236    return burnedTokens.success;1237  }12381239  /**1240   * Destroys a concrete instance of NFT on behalf of the owner1241   *1242   * @param signer keyring of signer1243   * @param collectionId ID of collection1244   * @param tokenId ID of token1245   * @param fromAddressObj address on behalf of which the token will be burnt1246   * @param amount amount of tokens to be burned. For NFT must be set to 1n1247   * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1248   * @returns ```true``` if extrinsic success, otherwise ```false```1249   */1250  async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1251    const burnResult = await this.helper.executeExtrinsic(1252      signer,1253      'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1254      true, // `Unable to burn token from for ${label}`,1255    );1256    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1257    return burnedTokens.success && burnedTokens.tokens.length > 0;1258  }12591260  /**1261   * Set, change, or remove approved address to transfer the ownership of the NFT.1262   *1263   * @param signer keyring of signer1264   * @param collectionId ID of collection1265   * @param tokenId ID of token1266   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1267   * @param amount amount of token to be approved. For NFT must be set to 1n1268   * @returns ```true``` if extrinsic success, otherwise ```false```1269   */1270  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1271    const approveResult = await this.helper.executeExtrinsic(1272      signer,1273      'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1274      true, // `Unable to approve token for ${label}`,1275    );12761277    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1278  }12791280  /**1281   * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1282   *1283   * @param signer keyring of signer1284   * @param collectionId ID of collection1285   * @param tokenId ID of token1286   * @param fromAddressObj Signer's Ethereum address containing her tokens1287   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1288   * @param amount amount of token to be approved. For NFT must be set to 1n1289   * @returns ```true``` if extrinsic success, otherwise ```false```1290   */1291  async approveTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1292    const approveResult = await this.helper.executeExtrinsic(1293      signer,1294      'api.tx.unique.approveFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1295      true, // `Unable to approve token for ${label}`,1296    );12971298    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1299  }13001301  /**1302   * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1303   *1304   * @param signer keyring of signer1305   * @param collectionId ID of collection1306   * @param tokenId ID of token1307   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1308   * @param amount amount of token to be approved. For NFT must be set to 1n1309   * @returns ```true``` if extrinsic success, otherwise ```false```1310   */1311  async approveTokenFromEth(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1312    const ethMirror = CrossAccountId.fromKeyring(signer).toEthereum();1313    return await this.approveTokenFrom(signer, collectionId, tokenId, ethMirror, toAddressObj, amount);1314  }13151316  /**1317   * Get the amount of token pieces approved to transfer or burn. Normally 0.1318   *1319   * @param collectionId ID of collection1320   * @param tokenId ID of token1321   * @param toAccountObj address which is approved to use token pieces1322   * @param fromAccountObj address which may have allowed the use of its owned tokens1323   * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1324   * @returns number of approved to transfer pieces1325   */1326  async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1327    return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1328  }13291330  /**1331   * Get the last created token ID in a collection1332   *1333   * @param collectionId ID of collection1334   * @example getLastTokenId(10);1335   * @returns id of the last created token1336   */1337  async getLastTokenId(collectionId: number): Promise<number> {1338    return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1339  }13401341  /**1342   * Check if token exists1343   *1344   * @param collectionId ID of collection1345   * @param tokenId ID of token1346   * @example doesTokenExist(10, 20);1347   * @returns true if the token exists, otherwise false1348   */1349  async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1350    return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1351  }1352}13531354class NFTnRFT extends CollectionGroup {1355  /**1356   * Get tokens owned by account1357   *1358   * @param collectionId ID of collection1359   * @param addressObj tokens owner1360   * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1361   * @returns array of token ids owned by account1362   */1363  async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1364    return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1365  }13661367  /**1368   * Get token data1369   *1370   * @param collectionId ID of collection1371   * @param tokenId ID of token1372   * @param propertyKeys optionally filter the token properties to only these keys1373   * @param blockHashAt optionally query the data at some block with this hash1374   * @example getToken(10, 5);1375   * @returns human readable token data1376   */1377  async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1378    properties: IProperty[];1379    owner: CrossAccountId;1380    normalizedOwner: CrossAccountId;1381  }| null> {1382    let tokenData;1383    if(typeof blockHashAt === 'undefined') {1384      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1385    }1386    else {1387      if(propertyKeys.length == 0) {1388        const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1389        if(!collection) return null;1390        propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1391      }1392      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1393    }1394    tokenData = tokenData.toHuman();1395    if (tokenData === null || tokenData.owner === null) return null;1396    const owner = {} as any;1397    for (const key of Object.keys(tokenData.owner)) {1398      owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1399        ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1400        : tokenData.owner[key];1401    }1402    tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1403    return tokenData;1404  }14051406  /**1407   * Get token's owner1408   * @param collectionId ID of collection1409   * @param tokenId ID of token1410   * @param blockHashAt optionally query the data at the block with this hash1411   * @example getTokenOwner(10, 5);1412   * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1413   */1414  async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1415    let owner;1416    if (typeof blockHashAt === 'undefined') {1417      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1418    } else {1419      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1420    }1421    return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1422  }14231424  /**1425   * Recursively find the address that owns the token1426   * @param collectionId ID of collection1427   * @param tokenId ID of token1428   * @param blockHashAt1429   * @example getTokenTopmostOwner(10, 5);1430   * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1431   */1432  async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1433    let owner;1434    if (typeof blockHashAt === 'undefined') {1435      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1436    } else {1437      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1438    }14391440    if (owner === null) return null;14411442    return owner.toHuman();1443  }14441445  /**1446   * Nest one token into another1447   * @param signer keyring of signer1448   * @param tokenObj token to be nested1449   * @param rootTokenObj token to be parent1450   * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1451   * @returns ```true``` if extrinsic success, otherwise ```false```1452   */1453  async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1454    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1455    const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1456    if(!result) {1457      throw Error('Unable to nest token!');1458    }1459    return result;1460  }14611462  /**1463     * Remove token from nested state1464     * @param signer keyring of signer1465     * @param tokenObj token to unnest1466     * @param rootTokenObj parent of a token1467     * @param toAddressObj address of a new token owner1468     * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1469     * @returns ```true``` if extrinsic success, otherwise ```false```1470     */1471  async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1472    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1473    const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1474    if(!result) {1475      throw Error('Unable to unnest token!');1476    }1477    return result;1478  }14791480  /**1481   * Set permissions to change token properties1482   *1483   * @param signer keyring of signer1484   * @param collectionId ID of collection1485   * @param permissions permissions to change a property by the collection admin or token owner1486   * @example setTokenPropertyPermissions(1487   *   aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1488   * )1489   * @returns true if extrinsic success otherwise false1490   */1491  async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1492    const result = await this.helper.executeExtrinsic(1493      signer,1494      'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1495      true,1496    );14971498    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1499  }15001501  /**1502   * Get token property permissions.1503   *1504   * @param collectionId ID of collection1505   * @param propertyKeys optionally filter the returned property permissions to only these keys1506   * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1507   * @returns array of key-permission pairs1508   */1509  async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1510    return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1511  }15121513  /**1514   * Set token properties1515   *1516   * @param signer keyring of signer1517   * @param collectionId ID of collection1518   * @param tokenId ID of token1519   * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1520   * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1521   * @returns ```true``` if extrinsic success, otherwise ```false```1522   */1523  async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1524    const result = await this.helper.executeExtrinsic(1525      signer,1526      'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1527      true,1528    );15291530    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1531  }15321533  /**1534   * Get properties, metadata assigned to a token.1535   *1536   * @param collectionId ID of collection1537   * @param tokenId ID of token1538   * @param propertyKeys optionally filter the returned properties to only these keys1539   * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1540   * @returns array of key-value pairs1541   */1542  async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1543    return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1544  }15451546  /**1547   * Delete the provided properties of a token1548   * @param signer keyring of signer1549   * @param collectionId ID of collection1550   * @param tokenId ID of token1551   * @param propertyKeys property keys to be deleted1552   * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1553   * @returns ```true``` if extrinsic success, otherwise ```false```1554   */1555  async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1556    const result = await this.helper.executeExtrinsic(1557      signer,1558      'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1559      true,1560    );15611562    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1563  }15641565  /**1566   * Mint new collection1567   *1568   * @param signer keyring of signer1569   * @param collectionOptions basic collection options and properties1570   * @param mode NFT or RFT type of a collection1571   * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1572   * @returns object of the created collection1573   */1574  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1575    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1576    collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1577    for (const key of ['name', 'description', 'tokenPrefix']) {1578      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);1579    }1580    const creationResult = await this.helper.executeExtrinsic(1581      signer,1582      'api.tx.unique.createCollectionEx', [collectionOptions],1583      true, // errorLabel,1584    );1585    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1586  }15871588  getCollectionObject(_collectionId: number): any {1589    return null;1590  }15911592  getTokenObject(_collectionId: number, _tokenId: number): any {1593    return null;1594  }15951596  /**1597   * Tells whether the given `owner` approves the `operator`.1598   * @param collectionId ID of collection1599   * @param owner owner address1600   * @param operator operator addrees1601   * @returns true if operator is enabled1602   */1603  async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1604    return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1605  }16061607  /** Sets or unsets the approval of a given operator.1608   *  The `operator` is allowed to transfer all tokens of the `caller` on their behalf.1609   *  @param operator Operator1610   *  @param approved Should operator status be granted or revoked?1611   *  @returns ```true``` if extrinsic success, otherwise ```false```1612   */1613  async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1614    const result = await this.helper.executeExtrinsic(1615      signer,1616      'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1617      true,1618    );1619    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1620  }1621}162216231624class NFTGroup extends NFTnRFT {1625  /**1626   * Get collection object1627   * @param collectionId ID of collection1628   * @example getCollectionObject(2);1629   * @returns instance of UniqueNFTCollection1630   */1631  getCollectionObject(collectionId: number): UniqueNFTCollection {1632    return new UniqueNFTCollection(collectionId, this.helper);1633  }16341635  /**1636   * Get token object1637   * @param collectionId ID of collection1638   * @param tokenId ID of token1639   * @example getTokenObject(10, 5);1640   * @returns instance of UniqueNFTToken1641   */1642  getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1643    return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1644  }16451646  /**1647   * Is token approved to transfer1648   * @param collectionId ID of collection1649   * @param tokenId ID of token1650   * @param toAccountObj address to be approved1651   * @returns ```true``` if extrinsic success, otherwise ```false```1652   */1653  async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1654    return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1655  }16561657  /**1658   * Changes the owner of the token.1659   *1660   * @param signer keyring of signer1661   * @param collectionId ID of collection1662   * @param tokenId ID of token1663   * @param addressObj address of a new owner1664   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1665   * @returns ```true``` if extrinsic success, otherwise ```false```1666   */1667  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1668    return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1669  }16701671  /**1672   *1673   * Change ownership of a NFT on behalf of the owner.1674   *1675   * @param signer keyring of signer1676   * @param collectionId ID of collection1677   * @param tokenId ID of token1678   * @param fromAddressObj address on behalf of which the token will be sent1679   * @param toAddressObj new token owner1680   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1681   * @returns ```true``` if extrinsic success, otherwise ```false```1682   */1683  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1684    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1685  }16861687  /**1688   * Get tokens nested in the provided token1689   * @param collectionId ID of collection1690   * @param tokenId ID of token1691   * @param blockHashAt optionally query the data at the block with this hash1692   * @example getTokenChildren(10, 5);1693   * @returns tokens whose depth of nesting is <= 51694   */1695  async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1696    let children;1697    if(typeof blockHashAt === 'undefined') {1698      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1699    } else {1700      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1701    }17021703    return children.toJSON().map((x: any) => {1704      return {collectionId: x.collection, tokenId: x.token};1705    });1706  }17071708  /**1709   * Mint new collection1710   * @param signer keyring of signer1711   * @param collectionOptions Collection options1712   * @example1713   * mintCollection(aliceKeyring, {1714   *   name: 'New',1715   *   description: 'New collection',1716   *   tokenPrefix: 'NEW',1717   * })1718   * @returns object of the created collection1719   */1720  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1721    return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1722  }17231724  /**1725   * Mint new token1726   * @param signer keyring of signer1727   * @param data token data1728   * @returns created token object1729   */1730  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1731    const creationResult = await this.helper.executeExtrinsic(1732      signer,1733      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1734        nft: {1735          properties: data.properties,1736        },1737      }],1738      true,1739    );1740    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1741    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1742    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1743    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1744  }17451746  /**1747   * Mint multiple NFT tokens1748   * @param signer keyring of signer1749   * @param collectionId ID of collection1750   * @param tokens array of tokens with owner and properties1751   * @example1752   * mintMultipleTokens(aliceKeyring, 10, [{1753   *     owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1754   *     properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1755   *   },{1756   *     owner: {Ethereum: "0x9F0583DbB855d..."},1757   *     properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1758   * }]);1759   * @returns ```true``` if extrinsic success, otherwise ```false```1760   */1761  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1762    const creationResult = await this.helper.executeExtrinsic(1763      signer,1764      'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1765      true,1766    );1767    const collection = this.getCollectionObject(collectionId);1768    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1769  }17701771  /**1772   * Mint multiple NFT tokens with one owner1773   * @param signer keyring of signer1774   * @param collectionId ID of collection1775   * @param owner tokens owner1776   * @param tokens array of tokens with owner and properties1777   * @example1778   * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1779   *   properties: [{1780   *   key: "gender",1781   *   value: "female",1782   *  },{1783   *   key: "age",1784   *   value: "33",1785   *  }],1786   * }]);1787   * @returns array of newly created tokens1788   */1789  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1790    const rawTokens = [];1791    for (const token of tokens) {1792      const raw = {NFT: {properties: token.properties}};1793      rawTokens.push(raw);1794    }1795    const creationResult = await this.helper.executeExtrinsic(1796      signer,1797      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1798      true,1799    );1800    const collection = this.getCollectionObject(collectionId);1801    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1802  }18031804  /**1805   * Set, change, or remove approved address to transfer the ownership of the NFT.1806   *1807   * @param signer keyring of signer1808   * @param collectionId ID of collection1809   * @param tokenId ID of token1810   * @param toAddressObj address to approve1811   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1812   * @returns ```true``` if extrinsic success, otherwise ```false```1813   */1814  approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1815    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1816  }1817}181818191820class RFTGroup extends NFTnRFT {1821  /**1822   * Get collection object1823   * @param collectionId ID of collection1824   * @example getCollectionObject(2);1825   * @returns instance of UniqueRFTCollection1826   */1827  getCollectionObject(collectionId: number): UniqueRFTCollection {1828    return new UniqueRFTCollection(collectionId, this.helper);1829  }18301831  /**1832   * Get token object1833   * @param collectionId ID of collection1834   * @param tokenId ID of token1835   * @example getTokenObject(10, 5);1836   * @returns instance of UniqueNFTToken1837   */1838  getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1839    return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1840  }18411842  /**1843   * Get top 10 token owners with the largest number of pieces1844   * @param collectionId ID of collection1845   * @param tokenId ID of token1846   * @example getTokenTop10Owners(10, 5);1847   * @returns array of top 10 owners1848   */1849  async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1850    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1851  }18521853  /**1854   * Get number of pieces owned by address1855   * @param collectionId ID of collection1856   * @param tokenId ID of token1857   * @param addressObj address token owner1858   * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1859   * @returns number of pieces ownerd by address1860   */1861  async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1862    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1863  }18641865  /**1866   * Transfer pieces of token to another address1867   * @param signer keyring of signer1868   * @param collectionId ID of collection1869   * @param tokenId ID of token1870   * @param addressObj address of a new owner1871   * @param amount number of pieces to be transfered1872   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1873   * @returns ```true``` if extrinsic success, otherwise ```false```1874   */1875  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1876    return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1877  }18781879  /**1880   * Change ownership of some pieces of RFT on behalf of the owner.1881   * @param signer keyring of signer1882   * @param collectionId ID of collection1883   * @param tokenId ID of token1884   * @param fromAddressObj address on behalf of which the token will be sent1885   * @param toAddressObj new token owner1886   * @param amount number of pieces to be transfered1887   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1888   * @returns ```true``` if extrinsic success, otherwise ```false```1889   */1890  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1891    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1892  }18931894  /**1895   * Mint new collection1896   * @param signer keyring of signer1897   * @param collectionOptions Collection options1898   * @example1899   * mintCollection(aliceKeyring, {1900   *   name: 'New',1901   *   description: 'New collection',1902   *   tokenPrefix: 'NEW',1903   * })1904   * @returns object of the created collection1905   */1906  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1907    return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1908  }19091910  /**1911   * Mint new token1912   * @param signer keyring of signer1913   * @param data token data1914   * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1915   * @returns created token object1916   */1917  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1918    const creationResult = await this.helper.executeExtrinsic(1919      signer,1920      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1921        refungible: {1922          pieces: data.pieces,1923          properties: data.properties,1924        },1925      }],1926      true,1927    );1928    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1929    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1930    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1931    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1932  }19331934  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1935    throw Error('Not implemented');1936    const creationResult = await this.helper.executeExtrinsic(1937      signer,1938      'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1939      true, // `Unable to mint RFT tokens for ${label}`,1940    );1941    const collection = this.getCollectionObject(collectionId);1942    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1943  }19441945  /**1946   * Mint multiple RFT tokens with one owner1947   * @param signer keyring of signer1948   * @param collectionId ID of collection1949   * @param owner tokens owner1950   * @param tokens array of tokens with properties and pieces1951   * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1952   * @returns array of newly created RFT tokens1953   */1954  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1955    const rawTokens = [];1956    for (const token of tokens) {1957      const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1958      rawTokens.push(raw);1959    }1960    const creationResult = await this.helper.executeExtrinsic(1961      signer,1962      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1963      true,1964    );1965    const collection = this.getCollectionObject(collectionId);1966    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1967  }19681969  /**1970   * Destroys a concrete instance of RFT.1971   * @param signer keyring of signer1972   * @param collectionId ID of collection1973   * @param tokenId ID of token1974   * @param amount number of pieces to be burnt1975   * @example burnToken(aliceKeyring, 10, 5);1976   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1977   */1978  async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1979    return await super.burnToken(signer, collectionId, tokenId, amount);1980  }19811982  /**1983   * Destroys a concrete instance of RFT on behalf of the owner.1984   * @param signer keyring of signer1985   * @param collectionId ID of collection1986   * @param tokenId ID of token1987   * @param fromAddressObj address on behalf of which the token will be burnt1988   * @param amount number of pieces to be burnt1989   * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1990   * @returns ```true``` if extrinsic success, otherwise ```false```1991   */1992  async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1993    return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1994  }19951996  /**1997   * Set, change, or remove approved address to transfer the ownership of the RFT.1998   *1999   * @param signer keyring of signer2000   * @param collectionId ID of collection2001   * @param tokenId ID of token2002   * @param toAddressObj address to approve2003   * @param amount number of pieces to be approved2004   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);2005   * @returns true if the token success, otherwise false2006   */2007  approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2008    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);2009  }20102011  /**2012   * Get total number of pieces2013   * @param collectionId ID of collection2014   * @param tokenId ID of token2015   * @example getTokenTotalPieces(10, 5);2016   * @returns number of pieces2017   */2018  async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {2019    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();2020  }20212022  /**2023   * Change number of token pieces. Signer must be the owner of all token pieces.2024   * @param signer keyring of signer2025   * @param collectionId ID of collection2026   * @param tokenId ID of token2027   * @param amount new number of pieces2028   * @example repartitionToken(aliceKeyring, 10, 5, 12345n);2029   * @returns true if the repartion was success, otherwise false2030   */2031  async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {2032    const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);2033    const repartitionResult = await this.helper.executeExtrinsic(2034      signer,2035      'api.tx.unique.repartition', [collectionId, tokenId, amount],2036      true,2037    );2038    if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');2039    return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');2040  }2041}204220432044class FTGroup extends CollectionGroup {2045  /**2046   * Get collection object2047   * @param collectionId ID of collection2048   * @example getCollectionObject(2);2049   * @returns instance of UniqueFTCollection2050   */2051  getCollectionObject(collectionId: number): UniqueFTCollection {2052    return new UniqueFTCollection(collectionId, this.helper);2053  }20542055  /**2056   * Mint new fungible collection2057   * @param signer keyring of signer2058   * @param collectionOptions Collection options2059   * @param decimalPoints number of token decimals2060   * @example2061   * mintCollection(aliceKeyring, {2062   *   name: 'New',2063   *   description: 'New collection',2064   *   tokenPrefix: 'NEW',2065   * }, 18)2066   * @returns newly created fungible collection2067   */2068  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {2069    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object2070    if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');2071    collectionOptions.mode = {fungible: decimalPoints};2072    for (const key of ['name', 'description', 'tokenPrefix']) {2073      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);2074    }2075    const creationResult = await this.helper.executeExtrinsic(2076      signer,2077      'api.tx.unique.createCollectionEx', [collectionOptions],2078      true,2079    );2080    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2081  }20822083  /**2084   * Mint tokens2085   * @param signer keyring of signer2086   * @param collectionId ID of collection2087   * @param owner address owner of new tokens2088   * @param amount amount of tokens to be meanted2089   * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);2090   * @returns ```true``` if extrinsic success, otherwise ```false```2091   */2092  async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2093    const creationResult = await this.helper.executeExtrinsic(2094      signer,2095      'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2096        fungible: {2097          value: amount,2098        },2099      }],2100      true, // `Unable to mint fungible tokens for ${label}`,2101    );2102    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2103  }21042105  /**2106   * Mint multiple Fungible tokens with one owner2107   * @param signer keyring of signer2108   * @param collectionId ID of collection2109   * @param owner tokens owner2110   * @param tokens array of tokens with properties and pieces2111   * @returns ```true``` if extrinsic success, otherwise ```false```2112   */2113  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {2114    const rawTokens = [];2115    for (const token of tokens) {2116      const raw = {Fungible: {Value: token.value}};2117      rawTokens.push(raw);2118    }2119    const creationResult = await this.helper.executeExtrinsic(2120      signer,2121      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2122      true,2123    );2124    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2125  }21262127  /**2128   * Get the top 10 owners with the largest balance for the Fungible collection2129   * @param collectionId ID of collection2130   * @example getTop10Owners(10);2131   * @returns array of ```ICrossAccountId```2132   */2133  async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2134    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2135  }21362137  /**2138   * Get account balance2139   * @param collectionId ID of collection2140   * @param addressObj address of owner2141   * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2142   * @returns amount of fungible tokens owned by address2143   */2144  async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2145    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2146  }21472148  /**2149   * Transfer tokens to address2150   * @param signer keyring of signer2151   * @param collectionId ID of collection2152   * @param toAddressObj address recipient2153   * @param amount amount of tokens to be sent2154   * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2155   * @returns ```true``` if extrinsic success, otherwise ```false```2156   */2157  async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2158    return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2159  }21602161  /**2162   * Transfer some tokens on behalf of the owner.2163   * @param signer keyring of signer2164   * @param collectionId ID of collection2165   * @param fromAddressObj address on behalf of which tokens will be sent2166   * @param toAddressObj address where token to be sent2167   * @param amount number of tokens to be sent2168   * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2169   * @returns ```true``` if extrinsic success, otherwise ```false```2170   */2171  async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2172    return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2173  }21742175  /**2176   * Destroy some amount of tokens2177   * @param signer keyring of signer2178   * @param collectionId ID of collection2179   * @param amount amount of tokens to be destroyed2180   * @example burnTokens(aliceKeyring, 10, 1000n);2181   * @returns ```true``` if extrinsic success, otherwise ```false```2182   */2183  async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2184    return await super.burnToken(signer, collectionId, 0, amount);2185  }21862187  /**2188   * Burn some tokens on behalf of the owner.2189   * @param signer keyring of signer2190   * @param collectionId ID of collection2191   * @param fromAddressObj address on behalf of which tokens will be burnt2192   * @param amount amount of tokens to be burnt2193   * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2194   * @returns ```true``` if extrinsic success, otherwise ```false```2195   */2196  async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2197    return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2198  }21992200  /**2201   * Get total collection supply2202   * @param collectionId2203   * @returns2204   */2205  async getTotalPieces(collectionId: number): Promise<bigint> {2206    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2207  }22082209  /**2210   * Set, change, or remove approved address to transfer tokens.2211   *2212   * @param signer keyring of signer2213   * @param collectionId ID of collection2214   * @param toAddressObj address to be approved2215   * @param amount amount of tokens to be approved2216   * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2217   * @returns ```true``` if extrinsic success, otherwise ```false```2218   */2219  approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2220    return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2221  }22222223  /**2224   * Get amount of fungible tokens approved to transfer2225   * @param collectionId ID of collection2226   * @param fromAddressObj owner of tokens2227   * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2228   * @returns number of tokens approved for the transfer2229   */2230  getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2231    return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2232  }2233}223422352236class ChainGroup extends HelperGroup<ChainHelperBase> {2237  /**2238   * Get system properties of a chain2239   * @example getChainProperties();2240   * @returns ss58Format, token decimals, and token symbol2241   */2242  getChainProperties(): IChainProperties {2243    const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2244    return {2245      ss58Format: properties.ss58Format.toJSON(),2246      tokenDecimals: properties.tokenDecimals.toJSON(),2247      tokenSymbol: properties.tokenSymbol.toJSON(),2248    };2249  }22502251  /**2252   * Get chain header2253   * @example getLatestBlockNumber();2254   * @returns the number of the last block2255   */2256  async getLatestBlockNumber(): Promise<number> {2257    return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2258  }22592260  /**2261   * Get block hash by block number2262   * @param blockNumber number of block2263   * @example getBlockHashByNumber(12345);2264   * @returns hash of a block2265   */2266  async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2267    const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2268    if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2269    return blockHash;2270  }22712272  // TODO add docs2273  async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2274    const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2275    if (!blockHash) return null;2276    return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2277  }22782279  /**2280   * Get latest relay block2281   * @returns {number} relay block2282   */2283  async getRelayBlockNumber(): Promise<bigint> {2284    const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2285    return BigInt(blockNumber);2286  }22872288  /**2289   * Get account nonce2290   * @param address substrate address2291   * @example getNonce("5GrwvaEF5zXb26Fz...");2292   * @returns number, account's nonce2293   */2294  async getNonce(address: TSubstrateAccount): Promise<number> {2295    return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2296  }2297}22982299class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2300  /**2301 * Get substrate address balance2302 * @param address substrate address2303 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2304 * @returns amount of tokens on address2305 */2306  async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2307    return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2308  }23092310  /**2311   * Transfer tokens to substrate address2312   * @param signer keyring of signer2313   * @param address substrate address of a recipient2314   * @param amount amount of tokens to be transfered2315   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2316   * @returns ```true``` if extrinsic success, otherwise ```false```2317   */2318  async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2319    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}`*/);23202321    let transfer = {from: null, to: null, amount: 0n} as any;2322    result.result.events.forEach(({event: {data, method, section}}) => {2323      if ((section === 'balances') && (method === 'Transfer')) {2324        transfer = {2325          from: this.helper.address.normalizeSubstrate(data[0]),2326          to: this.helper.address.normalizeSubstrate(data[1]),2327          amount: BigInt(data[2]),2328        };2329      }2330    });2331    const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2332      && this.helper.address.normalizeSubstrate(address) === transfer.to2333      && BigInt(amount) === transfer.amount;2334    return isSuccess;2335  }23362337  /**2338   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2339   * @param address substrate address2340   * @returns2341   */2342  async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2343    const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2344    return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2345  }23462347  async getLocked(address: TSubstrateAccount): Promise<[{id: string, amount: bigint, reason: string}]> {2348    const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2349    return locks.map((lock: any) => {return {id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons};});2350  }2351}23522353class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2354  /**2355   * Get ethereum address balance2356   * @param address ethereum address2357   * @example getEthereum("0x9F0583DbB855d...")2358   * @returns amount of tokens on address2359   */2360  async getEthereum(address: TEthereumAccount): Promise<bigint> {2361    return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2362  }23632364  /**2365   * Transfer tokens to address2366   * @param signer keyring of signer2367   * @param address Ethereum address of a recipient2368   * @param amount amount of tokens to be transfered2369   * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2370   * @returns ```true``` if extrinsic success, otherwise ```false```2371   */2372  async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2373    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);23742375    let transfer = {from: null, to: null, amount: 0n} as any;2376    result.result.events.forEach(({event: {data, method, section}}) => {2377      if ((section === 'balances') && (method === 'Transfer')) {2378        transfer = {2379          from: data[0].toString(),2380          to: data[1].toString(),2381          amount: BigInt(data[2]),2382        };2383      }2384    });2385    const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2386      && address === transfer.to2387      && BigInt(amount) === transfer.amount;2388    return isSuccess;2389  }2390}23912392class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2393  subBalanceGroup: SubstrateBalanceGroup<T>;2394  ethBalanceGroup: EthereumBalanceGroup<T>;23952396  constructor(helper: T) {2397    super(helper);2398    this.subBalanceGroup = new SubstrateBalanceGroup(helper);2399    this.ethBalanceGroup = new EthereumBalanceGroup(helper);2400  }24012402  getCollectionCreationPrice(): bigint {2403    return 2n * this.getOneTokenNominal();2404  }2405  /**2406   * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2407   * @example getOneTokenNominal()2408   * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2409   */2410  getOneTokenNominal(): bigint {2411    const chainProperties = this.helper.chain.getChainProperties();2412    return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2413  }24142415  /**2416   * Get substrate address balance2417   * @param address substrate address2418   * @example getSubstrate("5GrwvaEF5zXb26Fz...")2419   * @returns amount of tokens on address2420   */2421  getSubstrate(address: TSubstrateAccount): Promise<bigint> {2422    return this.subBalanceGroup.getSubstrate(address);2423  }24242425  /**2426   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2427   * @param address substrate address2428   * @returns2429   */2430  getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2431    return this.subBalanceGroup.getSubstrateFull(address);2432  }24332434  /**2435   * Get locked balances2436   * @param address substrate address2437   * @returns locked balances with reason via api.query.balances.locks2438   */2439  getLocked(address: TSubstrateAccount) {2440    return this.subBalanceGroup.getLocked(address);2441  }24422443  /**2444   * Get ethereum address balance2445   * @param address ethereum address2446   * @example getEthereum("0x9F0583DbB855d...")2447   * @returns amount of tokens on address2448   */2449  getEthereum(address: TEthereumAccount): Promise<bigint> {2450    return this.ethBalanceGroup.getEthereum(address);2451  }24522453  async setBalanceSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint, reservedAmount = 0n) {2454    await this.helper.executeExtrinsic(signer, 'api.tx.balances.setBalance', [address, amount, reservedAmount], true);2455  }24562457  /**2458   * Transfer tokens to substrate address2459   * @param signer keyring of signer2460   * @param address substrate address of a recipient2461   * @param amount amount of tokens to be transfered2462   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2463   * @returns ```true``` if extrinsic success, otherwise ```false```2464   */2465  transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2466    return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2467  }24682469  async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2470    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);24712472    let transfer = {from: null, to: null, amount: 0n} as any;2473    result.result.events.forEach(({event: {data, method, section}}) => {2474      if ((section === 'balances') && (method === 'Transfer')) {2475        transfer = {2476          from: this.helper.address.normalizeSubstrate(data[0]),2477          to: this.helper.address.normalizeSubstrate(data[1]),2478          amount: BigInt(data[2]),2479        };2480      }2481    });2482    let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2483    isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2484    isSuccess = isSuccess && BigInt(amount) === transfer.amount;2485    return isSuccess;2486  }24872488  /**2489   * Transfer tokens with the unlock period2490   * @param signer signers Keyring2491   * @param address Substrate address of recipient2492   * @param schedule Schedule params2493   * @example vestedTransfer(signer, recepient.address, 20000, 100, 10, 50 * nominal); // total amount of vested tokens will be 100 * 50 = 50002494   */2495  async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: {start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}): Promise<void> {2496    const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2497    const event = result.result.events2498      .find(e => e.event.section === 'vesting' &&2499            e.event.method === 'VestingScheduleAdded' &&2500            e.event.data[0].toHuman() === signer.address);2501    if (!event) throw Error('Cannot find transfer in events');2502  }25032504  /**2505   * Get schedule for recepient of vested transfer2506   * @param address Substrate address of recipient2507   * @returns2508   */2509  async getVestingSchedules(address: TSubstrateAccount): Promise<{start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}[]> {2510    const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2511    return schedule.map((schedule: any) => {2512      return {2513        start: BigInt(schedule.start),2514        period: BigInt(schedule.period),2515        periodCount: BigInt(schedule.periodCount),2516        perPeriod: BigInt(schedule.perPeriod),2517      };2518    });2519  }25202521  /**2522   * Claim vested tokens2523   * @param signer signers Keyring2524   */2525  async claim(signer: TSigner) {2526    const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2527    const event = result.result.events2528      .find(e => e.event.section === 'vesting' &&2529            e.event.method === 'Claimed' &&2530            e.event.data[0].toHuman() === signer.address);2531    if (!event) throw Error('Cannot find claim in events');2532  }2533}25342535class AddressGroup extends HelperGroup<ChainHelperBase> {2536  /**2537   * Normalizes the address to the specified ss58 format, by default ```42```.2538   * @param address substrate address2539   * @param ss58Format format for address conversion, by default ```42```2540   * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2541   * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2542   */2543  normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2544    return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2545  }25462547  /**2548   * Get address in the connected chain format2549   * @param address substrate address2550   * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2551   * @returns address in chain format2552   */2553  normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2554    return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2555  }25562557  /**2558   * Get substrate mirror of an ethereum address2559   * @param ethAddress ethereum address2560   * @param toChainFormat false for normalized account2561   * @example ethToSubstrate('0x9F0583DbB855d...')2562   * @returns substrate mirror of a provided ethereum address2563   */2564  ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2565    return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2566  }25672568  /**2569   * Get ethereum mirror of a substrate address2570   * @param subAddress substrate account2571   * @example substrateToEth("5DnSF6RRjwteE3BrC...")2572   * @returns ethereum mirror of a provided substrate address2573   */2574  substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2575    return CrossAccountId.translateSubToEth(subAddress);2576  }25772578  /**2579   * Encode key to substrate address2580   * @param key key for encoding address2581   * @param ss58Format prefix for encoding to the address of the corresponding network2582   * @returns encoded substrate address2583   */2584  encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2585    const u8a :Uint8Array = typeof key === 'string'2586      ? hexToU8a(key)2587      : typeof key === 'bigint'2588        ? hexToU8a(key.toString(16))2589        : key;25902591    if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2592      throw new Error(`ss58Format is not valid, received ${typeof ss58Format} "${ss58Format}"`);2593    }25942595    const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2596    if (!allowedDecodedLengths.includes(u8a.length)) {2597      throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2598    }25992600    const u8aPrefix = ss58Format < 642601      ? new Uint8Array([ss58Format])2602      : new Uint8Array([2603        ((ss58Format & 0xfc) >> 2) | 0x40,2604        (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2605      ]);26062607    const input = u8aConcat(u8aPrefix, u8a);26082609    return base58Encode(u8aConcat(2610      input,2611      blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2612    ));2613  }26142615  /**2616   * Restore substrate address from bigint representation2617   * @param number decimal representation of substrate address2618   * @returns substrate address2619   */2620  restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2621    if (this.helper.api === null) {2622      throw 'Not connected';2623    }2624    const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2625    if (res === undefined || res === null) {2626      throw 'Restore address error';2627    }2628    return res.toString();2629  }26302631  /**2632   * Convert etherium cross account id to substrate cross account id2633   * @param ethCrossAccount etherium cross account2634   * @returns substrate cross account id2635   */2636  convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2637    if (ethCrossAccount.sub === '0') {2638      return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2639    }26402641    const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2642    return {Substrate: ss58};2643  }26442645  paraSiblingSovereignAccount(paraid: number) {2646    // We are getting a *sibling* parachain sovereign account,2647    // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2648    const siblingPrefix = '0x7369626c';26492650    const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2651    const suffix = '000000000000000000000000000000000000000000000000';26522653    return siblingPrefix + encodedParaId + suffix;2654  }2655}26562657class StakingGroup extends HelperGroup<UniqueHelper> {2658  /**2659   * Stake tokens for App Promotion2660   * @param signer keyring of signer2661   * @param amountToStake amount of tokens to stake2662   * @param label extra label for log2663   * @returns2664   */2665  async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2666    if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2667    const _stakeResult = await this.helper.executeExtrinsic(2668      signer, 'api.tx.appPromotion.stake',2669      [amountToStake], true,2670    );2671    // TODO extract info from stakeResult2672    return true;2673  }26742675  /**2676   * Unstake all staked tokens2677   * @param signer keyring of signer2678   * @param amountToUnstake amount of tokens to unstake2679   * @param label extra label for log2680   * @returns block hash where unstake happened2681   */2682  async unstakeAll(signer: TSigner, label?: string): Promise<string> {2683    if(typeof label === 'undefined') label = `${signer.address}`;2684    const unstakeResult = await this.helper.executeExtrinsic(2685      signer, 'api.tx.appPromotion.unstakeAll',2686      [], true,2687    );2688    return unstakeResult.blockHash;2689  }26902691  /**2692   * Unstake the part of a staked tokens2693   * @param signer keyring of signer2694   * @param amount amount of tokens to unstake2695   * @param label extra label for log2696   * @returns block hash where unstake happened2697   */2698  async unstakePartial(signer: TSigner, amount: bigint, label?: string): Promise<string> {2699    if(typeof label === 'undefined') label = `${signer.address}`;2700    const unstakeResult = await this.helper.executeExtrinsic(2701      signer, 'api.tx.appPromotion.unstakePartial',2702      [amount], true,2703    );2704    return unstakeResult.blockHash;2705  }27062707  /**2708   * Get total number of active stakes2709   * @param address substrate address2710   * @returns {number}2711   */2712  async getStakesNumber(address: ICrossAccountId): Promise<number> {2713    if (address.Ethereum) throw Error('only substrate address');2714    return (await this.helper.callRpc('api.query.appPromotion.stakesPerAccount', [address.Substrate])).toNumber();2715  }27162717  /**2718   * Get total staked amount for address2719   * @param address substrate or ethereum address2720   * @returns total staked amount2721   */2722  async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2723    if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2724    return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2725  }27262727  /**2728   * Get total staked per block2729   * @param address substrate or ethereum address2730   * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2731   */2732  async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2733    const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2734    return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2735      return {2736        block: block.toBigInt(),2737        amount: amount.toBigInt(),2738      };2739    });2740  }27412742  /**2743   * Get total pending unstake amount for address2744   * @param address substrate or ethereum address2745   * @returns total pending unstake amount2746   */2747  async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2748    return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2749  }27502751  /**2752   * Get pending unstake amount per block for address2753   * @param address substrate or ethereum address2754   * @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 block2755   */2756  async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2757    const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2758    const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2759      return {2760        block: block.toBigInt(),2761        amount: amount.toBigInt(),2762      };2763    });2764    return result;2765  }2766}27672768class SchedulerGroup extends HelperGroup<UniqueHelper> {2769  constructor(helper: UniqueHelper) {2770    super(helper);2771  }27722773  cancelScheduled(signer: TSigner, scheduledId: string) {2774    return this.helper.executeExtrinsic(2775      signer,2776      'api.tx.scheduler.cancelNamed',2777      [scheduledId],2778      true,2779    );2780  }27812782  changePriority(signer: TSigner, scheduledId: string, priority: number) {2783    return this.helper.executeExtrinsic(2784      signer,2785      'api.tx.scheduler.changeNamedPriority',2786      [scheduledId, priority],2787      true,2788    );2789  }27902791  scheduleAt<T extends UniqueHelper>(2792    executionBlockNumber: number,2793    options: ISchedulerOptions = {},2794  ) {2795    return this.schedule<T>('schedule', executionBlockNumber, options);2796  }27972798  scheduleAfter<T extends UniqueHelper>(2799    blocksBeforeExecution: number,2800    options: ISchedulerOptions = {},2801  ) {2802    return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2803  }28042805  schedule<T extends UniqueHelper>(2806    scheduleFn: 'schedule' | 'scheduleAfter',2807    blocksNum: number,2808    options: ISchedulerOptions = {},2809  ) {2810    // eslint-disable-next-line @typescript-eslint/naming-convention2811    const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2812    return this.helper.clone(ScheduledHelperType, {2813      scheduleFn,2814      blocksNum,2815      options,2816    }) as T;2817  }2818}28192820class CollatorSelectionGroup extends HelperGroup<UniqueHelper> {2821  //todo:collator documentation2822  addInvulnerable(signer: TSigner, address: string) {2823    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.addInvulnerable', [address]);2824  }28252826  removeInvulnerable(signer: TSigner, address: string) {2827    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.removeInvulnerable', [address]);2828  }28292830  async getInvulnerables(): Promise<string[]> {2831    return (await this.helper.callRpc('api.query.collatorSelection.invulnerables')).map((x: any) => x.toHuman());2832  }28332834  /** and also total max invulnerables */2835  maxCollators(): number {2836    return (this.helper.getApi().consts.configuration.defaultCollatorSelectionMaxCollators.toJSON() as number);2837  }28382839  async getDesiredCollators(): Promise<number> {2840    return (await this.helper.callRpc('api.query.configuration.collatorSelectionDesiredCollatorsOverride')).toNumber();2841  }28422843  setLicenseBond(signer: TSigner, amount: bigint) {2844    return this.helper.executeExtrinsic(signer, 'api.tx.configuration.setCollatorSelectionLicenseBond', [amount]);2845  }28462847  async getLicenseBond(): Promise<bigint> {2848    return (await this.helper.callRpc('api.query.configuration.collatorSelectionLicenseBondOverride')).toBigInt();2849  }28502851  obtainLicense(signer: TSigner) {2852    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.getLicense', []);2853  }28542855  releaseLicense(signer: TSigner) {2856    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.releaseLicense', []);2857  }28582859  forceReleaseLicense(signer: TSigner, released: string) {2860    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.forceReleaseLicense', [released]);2861  }28622863  async hasLicense(address: string): Promise<bigint> {2864    return (await this.helper.callRpc('api.query.collatorSelection.licenseDepositOf', [address])).toBigInt();2865  }28662867  onboard(signer: TSigner) {2868    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.onboard', []);2869  }28702871  offboard(signer: TSigner) {2872    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.offboard', []);2873  }28742875  async getCandidates(): Promise<string[]> {2876    return (await this.helper.callRpc('api.query.collatorSelection.candidates')).map((x: any) => x.toHuman());2877  }2878}28792880class PreimageGroup extends HelperGroup<UniqueHelper> {2881  async getPreimageInfo(h256: string) {2882    return (await this.helper.callRpc('api.query.preimage.statusFor', [h256])).toJSON();2883  }28842885  /**2886   * Create a preimage with a hex or a byte array.2887   * @param signer keyring of the signer.2888   * @param bytes preimage encoded in hex or a byte array, e.g. an extrinsic call.2889   * @example await notePreimage(preimageMaker,2890   *   helper.constructApiCall('api.tx.identity.forceInsertIdentities', [identitiesToAdd]).method.toHex()2891   * );2892   * @returns promise of extrinsic execution.2893   */2894  notePreimage(signer: TSigner, bytes: string | Uint8Array) {2895    return this.helper.executeExtrinsic(signer, 'api.tx.preimage.notePreimage', [bytes]);2896  }28972898  /**2899   * Delete an existing preimage and return the deposit.2900   * @param signer keyring of the signer - either the owner or the preimage manager (sudo).2901   * @param h256 hash of the preimage.2902   * @returns promise of extrinsic execution.2903   */2904  unnotePreimage(signer: TSigner, h256: string) {2905    return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unnotePreimage', [h256]);2906  }29072908  /**2909   * Request a preimage be uploaded to the chain without paying any fees or deposits.2910   * @param signer keyring of the signer - either the owner or the preimage manager (sudo).2911   * @param h256 hash of the preimage.2912   * @returns promise of extrinsic execution.2913   */2914  requestPreimage(signer: TSigner, h256: string) {2915    return this.helper.executeExtrinsic(signer, 'api.tx.preimage.requestPreimage', [h256]);2916  }29172918  /**2919   * Clear a previously made request for a preimage.2920   * @param signer keyring of the signer - either the owner or the preimage manager (sudo).2921   * @param h256 hash of the preimage.2922   * @returns promise of extrinsic execution.2923   */2924  unrequestPreimage(signer: TSigner, h256: string) {2925    return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unrequestPreimage', [h256]);2926  }2927}29282929class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2930  async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2931    await this.helper.executeExtrinsic(2932      signer,2933      'api.tx.foreignAssets.registerForeignAsset',2934      [ownerAddress, location, metadata],2935      true,2936    );2937  }29382939  async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2940    await this.helper.executeExtrinsic(2941      signer,2942      'api.tx.foreignAssets.updateForeignAsset',2943      [foreignAssetId, location, metadata],2944      true,2945    );2946  }2947}29482949class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2950  palletName: string;29512952  constructor(helper: T, palletName: string) {2953    super(helper);29542955    this.palletName = palletName;2956  }29572958  async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {2959    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);2960  }29612962  async setSafeXcmVersion(signer: TSigner, version: number) {2963    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.forceDefaultXcmVersion`, [version], true);2964  }29652966  async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {2967    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);2968  }29692970  async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint, xcmVersion = 3) {2971    const destinationContent = {2972      parents: 0,2973      interior: {2974        X1: {2975          Parachain: destinationParaId,2976        },2977      },2978    };29792980    const beneficiaryContent = {2981      parents: 0,2982      interior: {2983        X1: {2984          AccountId32: {2985            network: 'Any',2986            id: targetAccount,2987          },2988        },2989      },2990    };29912992    const assetsContent = [2993      {2994        id: {2995          Concrete: {2996            parents: 0,2997            interior: 'Here',2998          },2999        },3000        fun: {3001          Fungible: amount,3002        },3003      },3004    ];30053006    let destination;3007    let beneficiary;3008    let assets;30093010    if (xcmVersion == 2) {3011      destination = {V1: destinationContent};3012      beneficiary = {V1: beneficiaryContent};3013      assets = {V1: assetsContent};30143015    } else if (xcmVersion == 3) {3016      destination = {V2: destinationContent};3017      beneficiary = {V2: beneficiaryContent};3018      assets = {V2: assetsContent};30193020    } else {3021      throw Error('Unknown XCM version: ' + xcmVersion);3022    }30233024    const feeAssetItem = 0;30253026    await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);3027  }30283029  async send(signer: IKeyringPair, destination: any, message: any) {3030    await this.helper.executeExtrinsic(3031      signer,3032      `api.tx.${this.palletName}.send`,3033      [3034        destination,3035        message,3036      ],3037      true,3038    );3039  }3040}30413042class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {3043  async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {3044    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);3045  }30463047  async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {3048    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);3049  }30503051  async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {3052    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);3053  }3054}30553056class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {3057  async accounts(address: string, currencyId: any) {3058    const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;3059    return BigInt(free);3060  }3061}30623063class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {3064  async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {3065    await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);3066  }30673068  async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {3069    await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);3070  }30713072  async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {3073    await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);3074  }30753076  async account(assetId: string | number, address: string) {3077    const accountAsset = (3078      await this.helper.callRpc('api.query.assets.account', [assetId, address])3079    ).toJSON()! as any;30803081    if (accountAsset !== null) {3082      return BigInt(accountAsset['balance']);3083    } else {3084      return null;3085    }3086  }3087}30883089class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {3090  async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {3091    await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);3092  }3093}30943095class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {3096  makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {3097    const apiPrefix = 'api.tx.assetManager.';30983099    const registerTx = this.helper.constructApiCall(3100      apiPrefix + 'registerForeignAsset',3101      [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],3102    );31033104    const setUnitsTx = this.helper.constructApiCall(3105      apiPrefix + 'setAssetUnitsPerSecond',3106      [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],3107    );31083109    const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);3110    const encodedProposal = batchCall?.method.toHex() || '';3111    return encodedProposal;3112  }31133114  async assetTypeId(location: any) {3115    return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);3116  }3117}31183119class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {3120  notePreimagePallet: string;31213122  constructor(helper: MoonbeamHelper, options: {[key: string]: any} = {}) {3123    super(helper);3124    this.notePreimagePallet = options.notePreimagePallet;3125  }31263127  async notePreimage(signer: TSigner, encodedProposal: string) {3128    await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);3129  }31303131  externalProposeMajority(proposal: any) {3132    return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);3133  }31343135  fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {3136    return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);3137  }31383139  async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {3140    await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);3141  }3142}31433144class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {3145  collective: string;31463147  constructor(helper: MoonbeamHelper, collective: string) {3148    super(helper);31493150    this.collective = collective;3151  }31523153  async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {3154    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);3155  }31563157  async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {3158    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);3159  }31603161  async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {3162    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);3163  }31643165  async proposalCount() {3166    return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));3167  }3168}31693170export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;3171export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;31723173export class UniqueHelper extends ChainHelperBase {3174  balance: BalanceGroup<UniqueHelper>;3175  collection: CollectionGroup;3176  nft: NFTGroup;3177  rft: RFTGroup;3178  ft: FTGroup;3179  staking: StakingGroup;3180  scheduler: SchedulerGroup;3181  collatorSelection: CollatorSelectionGroup;3182  preimage: PreimageGroup;3183  foreignAssets: ForeignAssetsGroup;3184  xcm: XcmGroup<UniqueHelper>;3185  xTokens: XTokensGroup<UniqueHelper>;3186  tokens: TokensGroup<UniqueHelper>;31873188  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3189    super(logger, options.helperBase ?? UniqueHelper);31903191    this.balance = new BalanceGroup(this);3192    this.collection = new CollectionGroup(this);3193    this.nft = new NFTGroup(this);3194    this.rft = new RFTGroup(this);3195    this.ft = new FTGroup(this);3196    this.staking = new StakingGroup(this);3197    this.scheduler = new SchedulerGroup(this);3198    this.collatorSelection = new CollatorSelectionGroup(this);3199    this.preimage = new PreimageGroup(this);3200    this.foreignAssets = new ForeignAssetsGroup(this);3201    this.xcm = new XcmGroup(this, 'polkadotXcm');3202    this.xTokens = new XTokensGroup(this);3203    this.tokens = new TokensGroup(this);3204  }32053206  getSudo<T extends UniqueHelper>() {3207    // eslint-disable-next-line @typescript-eslint/naming-convention3208    const SudoHelperType = SudoHelper(this.helperBase);3209    return this.clone(SudoHelperType) as T;3210  }3211}32123213export class XcmChainHelper extends ChainHelperBase {3214  async connect(wsEndpoint: string, _listeners?: any): Promise<void> {3215    const wsProvider = new WsProvider(wsEndpoint);3216    this.api = new ApiPromise({3217      provider: wsProvider,3218    });3219    await this.api.isReadyOrError;3220    this.network = await UniqueHelper.detectNetwork(this.api);3221  }3222}32233224export class RelayHelper extends XcmChainHelper {3225  balance: SubstrateBalanceGroup<RelayHelper>;3226  xcm: XcmGroup<RelayHelper>;32273228  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3229    super(logger, options.helperBase ?? RelayHelper);32303231    this.balance = new SubstrateBalanceGroup(this);3232    this.xcm = new XcmGroup(this, 'xcmPallet');3233  }3234}32353236export class WestmintHelper extends XcmChainHelper {3237  balance: SubstrateBalanceGroup<WestmintHelper>;3238  xcm: XcmGroup<WestmintHelper>;3239  assets: AssetsGroup<WestmintHelper>;3240  xTokens: XTokensGroup<WestmintHelper>;32413242  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3243    super(logger, options.helperBase ?? WestmintHelper);32443245    this.balance = new SubstrateBalanceGroup(this);3246    this.xcm = new XcmGroup(this, 'polkadotXcm');3247    this.assets = new AssetsGroup(this);3248    this.xTokens = new XTokensGroup(this);3249  }3250}32513252export class MoonbeamHelper extends XcmChainHelper {3253  balance: EthereumBalanceGroup<MoonbeamHelper>;3254  assetManager: MoonbeamAssetManagerGroup;3255  assets: AssetsGroup<MoonbeamHelper>;3256  xTokens: XTokensGroup<MoonbeamHelper>;3257  democracy: MoonbeamDemocracyGroup;3258  collective: {3259    council: MoonbeamCollectiveGroup,3260    techCommittee: MoonbeamCollectiveGroup,3261  };32623263  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3264    super(logger, options.helperBase ?? MoonbeamHelper);32653266    this.balance = new EthereumBalanceGroup(this);3267    this.assetManager = new MoonbeamAssetManagerGroup(this);3268    this.assets = new AssetsGroup(this);3269    this.xTokens = new XTokensGroup(this);3270    this.democracy = new MoonbeamDemocracyGroup(this, options);3271    this.collective = {3272      council: new MoonbeamCollectiveGroup(this, 'councilCollective'),3273      techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),3274    };3275  }3276}32773278export class AstarHelper extends XcmChainHelper {3279  balance: SubstrateBalanceGroup<AstarHelper>;3280  assets: AssetsGroup<AstarHelper>;3281  xcm: XcmGroup<AstarHelper>;32823283  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3284    super(logger, options.helperBase ?? AstarHelper);32853286    this.balance = new SubstrateBalanceGroup(this);3287    this.assets = new AssetsGroup(this);3288    this.xcm = new XcmGroup(this, 'polkadotXcm');3289  }32903291  getSudo<T extends UniqueHelper>() {3292    // eslint-disable-next-line @typescript-eslint/naming-convention3293    const SudoHelperType = SudoHelper(this.helperBase);3294    return this.clone(SudoHelperType) as T;3295  }3296}32973298export class AcalaHelper extends XcmChainHelper {3299  balance: SubstrateBalanceGroup<AcalaHelper>;3300  assetRegistry: AcalaAssetRegistryGroup;3301  xTokens: XTokensGroup<AcalaHelper>;3302  tokens: TokensGroup<AcalaHelper>;3303  xcm: XcmGroup<AcalaHelper>;33043305  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3306    super(logger, options.helperBase ?? AcalaHelper);33073308    this.balance = new SubstrateBalanceGroup(this);3309    this.assetRegistry = new AcalaAssetRegistryGroup(this);3310    this.xTokens = new XTokensGroup(this);3311    this.tokens = new TokensGroup(this);3312    this.xcm = new XcmGroup(this, 'polkadotXcm');3313  }33143315  getSudo<T extends AcalaHelper>() {3316    // eslint-disable-next-line @typescript-eslint/naming-convention3317    const SudoHelperType = SudoHelper(this.helperBase);3318    return this.clone(SudoHelperType) as T;3319  }3320}33213322// eslint-disable-next-line @typescript-eslint/naming-convention3323function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3324  return class extends Base {3325    scheduleFn: 'schedule' | 'scheduleAfter';3326    blocksNum: number;3327    options: ISchedulerOptions;33283329    constructor(...args: any[]) {3330      const logger = args[0] as ILogger;3331      const options = args[1] as {3332        scheduleFn: 'schedule' | 'scheduleAfter',3333        blocksNum: number,3334        options: ISchedulerOptions3335      };33363337      super(logger);33383339      this.scheduleFn = options.scheduleFn;3340      this.blocksNum = options.blocksNum;3341      this.options = options.options;3342    }33433344    executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3345      const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);33463347      const mandatorySchedArgs = [3348        this.blocksNum,3349        this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3350        this.options.priority ?? null,3351        scheduledTx,3352      ];33533354      let schedArgs;3355      let scheduleFn;33563357      if (this.options.scheduledId) {3358        schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];33593360        if (this.scheduleFn == 'schedule') {3361          scheduleFn = 'scheduleNamed';3362        } else if (this.scheduleFn == 'scheduleAfter') {3363          scheduleFn = 'scheduleNamedAfter';3364        }3365      } else {3366        schedArgs = mandatorySchedArgs;3367        scheduleFn = this.scheduleFn;3368      }33693370      const extrinsic = 'api.tx.scheduler.' +  scheduleFn;33713372      return super.executeExtrinsic(3373        sender,3374        extrinsic,3375        schedArgs,3376        expectSuccess,3377      );3378    }3379  };3380}33813382// eslint-disable-next-line @typescript-eslint/naming-convention3383function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3384  return class extends Base {3385    constructor(...args: any[]) {3386      super(...args);3387    }33883389    async executeExtrinsic(3390      sender: IKeyringPair,3391      extrinsic: string,3392      params: any[],3393      expectSuccess?: boolean,3394      options: Partial<SignerOptions>|null = null,3395    ): Promise<ITransactionResult> {3396      const call = this.constructApiCall(extrinsic, params);3397      const result = await super.executeExtrinsic(3398        sender,3399        'api.tx.sudo.sudo',3400        [call],3401        expectSuccess,3402        options,3403      );34043405      if (result.status === 'Fail') return result;34063407      const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;3408      if (data.isErr) {3409        if (data.asErr.isModule) {3410          const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;3411          const metaError = super.getApi()?.registry.findMetaError(error);3412          throw new Error(`${metaError.section}.${metaError.name}`);3413        } else {3414          throw new Error(data.asErr.toHuman());3415        }3416      }3417      return result;3418    }3419  };3420}34213422export class UniqueBaseCollection {3423  helper: UniqueHelper;3424  collectionId: number;34253426  constructor(collectionId: number, uniqueHelper: UniqueHelper) {3427    this.collectionId = collectionId;3428    this.helper = uniqueHelper;3429  }34303431  async getData() {3432    return await this.helper.collection.getData(this.collectionId);3433  }34343435  async getLastTokenId() {3436    return await this.helper.collection.getLastTokenId(this.collectionId);3437  }34383439  async doesTokenExist(tokenId: number) {3440    return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3441  }34423443  async getAdmins() {3444    return await this.helper.collection.getAdmins(this.collectionId);3445  }34463447  async getAllowList() {3448    return await this.helper.collection.getAllowList(this.collectionId);3449  }34503451  async getEffectiveLimits() {3452    return await this.helper.collection.getEffectiveLimits(this.collectionId);3453  }34543455  async getProperties(propertyKeys?: string[] | null) {3456    return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3457  }34583459  async getPropertiesConsumedSpace() {3460    return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3461  }34623463  async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3464    return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3465  }34663467  async getOptions() {3468    return await this.helper.collection.getCollectionOptions(this.collectionId);3469  }34703471  async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3472    return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3473  }34743475  async confirmSponsorship(signer: TSigner) {3476    return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3477  }34783479  async removeSponsor(signer: TSigner) {3480    return await this.helper.collection.removeSponsor(signer, this.collectionId);3481  }34823483  async setLimits(signer: TSigner, limits: ICollectionLimits) {3484    return await this.helper.collection.setLimits(signer, this.collectionId, limits);3485  }34863487  async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3488    return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3489  }34903491  async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3492    return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3493  }34943495  async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3496    return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3497  }34983499  async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3500    return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3501  }35023503  async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3504    return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3505  }35063507  async setProperties(signer: TSigner, properties: IProperty[]) {3508    return await this.helper.collection.setProperties(signer, this.collectionId, properties);3509  }35103511  async deleteProperties(signer: TSigner, propertyKeys: string[]) {3512    return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3513  }35143515  async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3516    return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3517  }35183519  async enableNesting(signer: TSigner, permissions: INestingPermissions) {3520    return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3521  }35223523  async disableNesting(signer: TSigner) {3524    return await this.helper.collection.disableNesting(signer, this.collectionId);3525  }35263527  async burn(signer: TSigner) {3528    return await this.helper.collection.burn(signer, this.collectionId);3529  }35303531  scheduleAt<T extends UniqueHelper>(3532    executionBlockNumber: number,3533    options: ISchedulerOptions = {},3534  ) {3535    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3536    return new UniqueBaseCollection(this.collectionId, scheduledHelper);3537  }35383539  scheduleAfter<T extends UniqueHelper>(3540    blocksBeforeExecution: number,3541    options: ISchedulerOptions = {},3542  ) {3543    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3544    return new UniqueBaseCollection(this.collectionId, scheduledHelper);3545  }35463547  getSudo<T extends UniqueHelper>() {3548    return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3549  }3550}355135523553export class UniqueNFTCollection extends UniqueBaseCollection {3554  getTokenObject(tokenId: number) {3555    return new UniqueNFToken(tokenId, this);3556  }35573558  async getTokensByAddress(addressObj: ICrossAccountId) {3559    return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3560  }35613562  async getToken(tokenId: number, blockHashAt?: string) {3563    return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3564  }35653566  async getTokenOwner(tokenId: number, blockHashAt?: string) {3567    return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3568  }35693570  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3571    return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3572  }35733574  async getTokenChildren(tokenId: number, blockHashAt?: string) {3575    return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3576  }35773578  async getPropertyPermissions(propertyKeys: string[] | null = null) {3579    return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3580  }35813582  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3583    return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3584  }35853586  async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3587    const api = this.helper.getApi();3588    const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();35893590    return (props! as any).consumedSpace;3591  }35923593  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3594    return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3595  }35963597  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3598    return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3599  }36003601  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3602    return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3603  }36043605  async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3606    return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3607  }36083609  async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3610    return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3611  }36123613  async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3614    return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3615  }36163617  async burnToken(signer: TSigner, tokenId: number) {3618    return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3619  }36203621  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3622    return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3623  }36243625  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3626    return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3627  }36283629  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3630    return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3631  }36323633  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3634    return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3635  }36363637  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3638    return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3639  }36403641  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3642    return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3643  }36443645  scheduleAt<T extends UniqueHelper>(3646    executionBlockNumber: number,3647    options: ISchedulerOptions = {},3648  ) {3649    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3650    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3651  }36523653  scheduleAfter<T extends UniqueHelper>(3654    blocksBeforeExecution: number,3655    options: ISchedulerOptions = {},3656  ) {3657    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3658    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3659  }36603661  getSudo<T extends UniqueHelper>() {3662    return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3663  }3664}366536663667export class UniqueRFTCollection extends UniqueBaseCollection {3668  getTokenObject(tokenId: number) {3669    return new UniqueRFToken(tokenId, this);3670  }36713672  async getToken(tokenId: number, blockHashAt?: string) {3673    return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3674  }36753676  async getTokenOwner(tokenId: number, blockHashAt?: string) {3677    return await this.helper.rft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3678  }36793680  async getTokensByAddress(addressObj: ICrossAccountId) {3681    return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3682  }36833684  async getTop10TokenOwners(tokenId: number) {3685    return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3686  }36873688  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3689    return await this.helper.rft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3690  }36913692  async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3693    return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3694  }36953696  async getTokenTotalPieces(tokenId: number) {3697    return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3698  }36993700  async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3701    return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3702  }37033704  async getPropertyPermissions(propertyKeys: string[] | null = null) {3705    return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3706  }37073708  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3709    return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3710  }37113712  async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3713    const api = this.helper.getApi();3714    const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();37153716    return (props! as any).consumedSpace;3717  }37183719  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3720    return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3721  }37223723  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3724    return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3725  }37263727  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3728    return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3729  }37303731  async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3732    return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3733  }37343735  async mintToken(signer: TSigner, pieces = 1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3736    return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3737  }37383739  async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3740    return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3741  }37423743  async burnToken(signer: TSigner, tokenId: number, amount=1n) {3744    return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3745  }37463747  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId,  amount=1n) {3748    return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3749  }37503751  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3752    return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3753  }37543755  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3756    return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3757  }37583759  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3760    return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3761  }37623763  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3764    return await this.helper.rft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3765  }37663767  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3768    return await this.helper.rft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3769  }37703771  scheduleAt<T extends UniqueHelper>(3772    executionBlockNumber: number,3773    options: ISchedulerOptions = {},3774  ) {3775    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3776    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3777  }37783779  scheduleAfter<T extends UniqueHelper>(3780    blocksBeforeExecution: number,3781    options: ISchedulerOptions = {},3782  ) {3783    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3784    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3785  }37863787  getSudo<T extends UniqueHelper>() {3788    return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3789  }3790}379137923793export class UniqueFTCollection extends UniqueBaseCollection {3794  async getBalance(addressObj: ICrossAccountId) {3795    return await this.helper.ft.getBalance(this.collectionId, addressObj);3796  }37973798  async getTotalPieces() {3799    return await this.helper.ft.getTotalPieces(this.collectionId);3800  }38013802  async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3803    return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3804  }38053806  async getTop10Owners() {3807    return await this.helper.ft.getTop10Owners(this.collectionId);3808  }38093810  async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3811    return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3812  }38133814  async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3815    return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3816  }38173818  async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3819    return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3820  }38213822  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3823    return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3824  }38253826  async burnTokens(signer: TSigner, amount=1n) {3827    return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3828  }38293830  async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3831    return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3832  }38333834  async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3835    return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3836  }38373838  scheduleAt<T extends UniqueHelper>(3839    executionBlockNumber: number,3840    options: ISchedulerOptions = {},3841  ) {3842    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3843    return new UniqueFTCollection(this.collectionId, scheduledHelper);3844  }38453846  scheduleAfter<T extends UniqueHelper>(3847    blocksBeforeExecution: number,3848    options: ISchedulerOptions = {},3849  ) {3850    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3851    return new UniqueFTCollection(this.collectionId, scheduledHelper);3852  }38533854  getSudo<T extends UniqueHelper>() {3855    return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3856  }3857}385838593860export class UniqueBaseToken {3861  collection: UniqueNFTCollection | UniqueRFTCollection;3862  collectionId: number;3863  tokenId: number;38643865  constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3866    this.collection = collection;3867    this.collectionId = collection.collectionId;3868    this.tokenId = tokenId;3869  }38703871  async getNextSponsored(addressObj: ICrossAccountId) {3872    return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3873  }38743875  async getProperties(propertyKeys?: string[] | null) {3876    return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3877  }38783879  async getTokenPropertiesConsumedSpace() {3880    return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3881  }38823883  async setProperties(signer: TSigner, properties: IProperty[]) {3884    return await this.collection.setTokenProperties(signer, this.tokenId, properties);3885  }38863887  async deleteProperties(signer: TSigner, propertyKeys: string[]) {3888    return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3889  }38903891  async doesExist() {3892    return await this.collection.doesTokenExist(this.tokenId);3893  }38943895  nestingAccount() {3896    return this.collection.helper.util.getTokenAccount(this);3897  }38983899  scheduleAt<T extends UniqueHelper>(3900    executionBlockNumber: number,3901    options: ISchedulerOptions = {},3902  ) {3903    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3904    return new UniqueBaseToken(this.tokenId, scheduledCollection);3905  }39063907  scheduleAfter<T extends UniqueHelper>(3908    blocksBeforeExecution: number,3909    options: ISchedulerOptions = {},3910  ) {3911    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3912    return new UniqueBaseToken(this.tokenId, scheduledCollection);3913  }39143915  getSudo<T extends UniqueHelper>() {3916    return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3917  }3918}391939203921export class UniqueNFToken extends UniqueBaseToken {3922  collection: UniqueNFTCollection;39233924  constructor(tokenId: number, collection: UniqueNFTCollection) {3925    super(tokenId, collection);3926    this.collection = collection;3927  }39283929  async getData(blockHashAt?: string) {3930    return await this.collection.getToken(this.tokenId, blockHashAt);3931  }39323933  async getOwner(blockHashAt?: string) {3934    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3935  }39363937  async getTopmostOwner(blockHashAt?: string) {3938    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3939  }39403941  async getChildren(blockHashAt?: string) {3942    return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3943  }39443945  async nest(signer: TSigner, toTokenObj: IToken) {3946    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3947  }39483949  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3950    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3951  }39523953  async transfer(signer: TSigner, addressObj: ICrossAccountId) {3954    return await this.collection.transferToken(signer, this.tokenId, addressObj);3955  }39563957  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3958    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3959  }39603961  async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3962    return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3963  }39643965  async isApproved(toAddressObj: ICrossAccountId) {3966    return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3967  }39683969  async burn(signer: TSigner) {3970    return await this.collection.burnToken(signer, this.tokenId);3971  }39723973  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3974    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3975  }39763977  scheduleAt<T extends UniqueHelper>(3978    executionBlockNumber: number,3979    options: ISchedulerOptions = {},3980  ) {3981    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3982    return new UniqueNFToken(this.tokenId, scheduledCollection);3983  }39843985  scheduleAfter<T extends UniqueHelper>(3986    blocksBeforeExecution: number,3987    options: ISchedulerOptions = {},3988  ) {3989    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3990    return new UniqueNFToken(this.tokenId, scheduledCollection);3991  }39923993  getSudo<T extends UniqueHelper>() {3994    return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3995  }3996}39973998export class UniqueRFToken extends UniqueBaseToken {3999  collection: UniqueRFTCollection;40004001  constructor(tokenId: number, collection: UniqueRFTCollection) {4002    super(tokenId, collection);4003    this.collection = collection;4004  }40054006  async getData(blockHashAt?: string) {4007    return await this.collection.getToken(this.tokenId, blockHashAt);4008  }40094010  async getOwner(blockHashAt?: string) {4011    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);4012  }40134014  async getTop10Owners() {4015    return await this.collection.getTop10TokenOwners(this.tokenId);4016  }40174018  async getTopmostOwner(blockHashAt?: string) {4019    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);4020  }40214022  async nest(signer: TSigner, toTokenObj: IToken) {4023    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);4024  }40254026  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {4027    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);4028  }40294030  async getBalance(addressObj: ICrossAccountId) {4031    return await this.collection.getTokenBalance(this.tokenId, addressObj);4032  }40334034  async getTotalPieces() {4035    return await this.collection.getTokenTotalPieces(this.tokenId);4036  }40374038  async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {4039    return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);4040  }40414042  async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {4043    return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);4044  }40454046  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {4047    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);4048  }40494050  async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {4051    return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);4052  }40534054  async repartition(signer: TSigner, amount: bigint) {4055    return await this.collection.repartitionToken(signer, this.tokenId, amount);4056  }40574058  async burn(signer: TSigner, amount=1n) {4059    return await this.collection.burnToken(signer, this.tokenId, amount);4060  }40614062  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {4063    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);4064  }40654066  scheduleAt<T extends UniqueHelper>(4067    executionBlockNumber: number,4068    options: ISchedulerOptions = {},4069  ) {4070    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);4071    return new UniqueRFToken(this.tokenId, scheduledCollection);4072  }40734074  scheduleAfter<T extends UniqueHelper>(4075    blocksBeforeExecution: number,4076    options: ISchedulerOptions = {},4077  ) {4078    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);4079    return new UniqueRFToken(this.tokenId, scheduledCollection);4080  }40814082  getSudo<T extends UniqueHelper>() {4083    return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());4084  }4085}