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

difftreelog

source

tests/src/util/playgrounds/unique.ts132.4 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 {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISchedulerOptions, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, IForeignAssetMetadata, TNetworks, MoonbeamAssetInfo, DemocracyStandardAccountVote, AcalaAssetMetadata} from './types';13import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';1415export class CrossAccountId implements ICrossAccountId {16  Substrate?: TSubstrateAccount;17  Ethereum?: TEthereumAccount;1819  constructor(account: ICrossAccountId) {20    if (account.Substrate) this.Substrate = account.Substrate;21    if (account.Ethereum) this.Ethereum = account.Ethereum;22  }2324  static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {25    switch (domain) {26      case 'Substrate': return new CrossAccountId({Substrate: account.address});27      case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();28    }29  }3031  static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {32    return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});33  }3435  static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {36    return encodeAddress(decodeAddress(address), ss58Format);37  }3839  static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {40    return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});41  }42  43  withNormalizedSubstrate(ss58Format = 42): CrossAccountId {44    if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);45    return this;46  }4748  static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {49    return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));50  }5152  toEthereum(): CrossAccountId {53    if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});54    return this;55  }5657  static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {58    return evmToAddress(address, ss58Format);59  }6061  toSubstrate(ss58Format?: number): CrossAccountId {62    if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});63    return this;64  }65  66  toLowerCase(): CrossAccountId {67    if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();68    if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();69    return this;70  }71}7273const nesting = {74  toChecksumAddress(address: string): string {75    if (typeof address === 'undefined') return '';7677    if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);7879    address = address.toLowerCase().replace(/^0x/i,'');80    const addressHash = keccakAsHex(address).replace(/^0x/i,'');81    const checksumAddress = ['0x'];8283    for (let i = 0; i < address.length; i++) {84      // If ith character is 8 to f then make it uppercase85      if (parseInt(addressHash[i], 16) > 7) {86        checksumAddress.push(address[i].toUpperCase());87      } else {88        checksumAddress.push(address[i]);89      }90    }91    return checksumAddress.join('');92  },93  tokenIdToAddress(collectionId: number, tokenId: number) {94    return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);95  },96};9798class UniqueUtil {99  static transactionStatus = {100    NOT_READY: 'NotReady',101    FAIL: 'Fail',102    SUCCESS: 'Success',103  };104105  static chainLogType = {106    EXTRINSIC: 'extrinsic',107    RPC: 'rpc',108  };109110  static getTokenAccount(token: IToken): CrossAccountId {111    return new CrossAccountId({Ethereum: this.getTokenAddress(token)});112  }113114  static getTokenAddress(token: IToken): string {115    return nesting.tokenIdToAddress(token.collectionId, token.tokenId);116  }117118  static getDefaultLogger(): ILogger {119    return {120      log(msg: any, level = 'INFO') {121        console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));122      },123      level: {124        ERROR: 'ERROR',125        WARNING: 'WARNING',126        INFO: 'INFO',127      },128    };129  }130131  static vec2str(arr: string[] | number[]) {132    return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');133  }134135  static str2vec(string: string) {136    if (typeof string !== 'string') return string;137    return Array.from(string).map(x => x.charCodeAt(0));138  }139140  static fromSeed(seed: string, ss58Format = 42) {141    const keyring = new Keyring({type: 'sr25519', ss58Format});142    return keyring.addFromUri(seed);143  }144145  static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {146    if (creationResult.status !== this.transactionStatus.SUCCESS) {147      throw Error('Unable to create collection!');148    }149150    let collectionId = null;151    creationResult.result.events.forEach(({event: {data, method, section}}) => {152      if ((section === 'common') && (method === 'CollectionCreated')) {153        collectionId = parseInt(data[0].toString(), 10);154      }155    });156157    if (collectionId === null) {158      throw Error('No CollectionCreated event was found!');159    }160161    return collectionId;162  }163164  static extractTokensFromCreationResult(creationResult: ITransactionResult): {165    success: boolean, 166    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],167  } {168    if (creationResult.status !== this.transactionStatus.SUCCESS) {169      throw Error('Unable to create tokens!');170    }171    let success = false;172    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];173    creationResult.result.events.forEach(({event: {data, method, section}}) => {174      if (method === 'ExtrinsicSuccess') {175        success = true;176      } else if ((section === 'common') && (method === 'ItemCreated')) {177        tokens.push({178          collectionId: parseInt(data[0].toString(), 10),179          tokenId: parseInt(data[1].toString(), 10),180          owner: data[2].toHuman(),181          amount: data[3].toBigInt(),182        });183      }184    });185    return {success, tokens};186  }187188  static extractTokensFromBurnResult(burnResult: ITransactionResult): {189    success: boolean, 190    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],191  } {192    if (burnResult.status !== this.transactionStatus.SUCCESS) {193      throw Error('Unable to burn tokens!');194    }195    let success = false;196    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];197    burnResult.result.events.forEach(({event: {data, method, section}}) => {198      if (method === 'ExtrinsicSuccess') {199        success = true;200      } else if ((section === 'common') && (method === 'ItemDestroyed')) {201        tokens.push({202          collectionId: parseInt(data[0].toString(), 10),203          tokenId: parseInt(data[1].toString(), 10),204          owner: data[2].toHuman(),205          amount: data[3].toBigInt(),206        });207      }208    });209    return {success, tokens};210  }211212  static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {213    let eventId = null;214    events.forEach(({event: {data, method, section}}) => {215      if ((section === expectedSection) && (method === expectedMethod)) {216        eventId = parseInt(data[0].toString(), 10);217      }218    });219220    if (eventId === null) {221      throw Error(`No ${expectedMethod} event was found!`);222    }223    return eventId === collectionId;224  }225226  static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {227    const normalizeAddress = (address: string | ICrossAccountId) => {228      if(typeof address === 'string') return address;229      const obj = {} as any;230      Object.keys(address).forEach(k => {231        obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];232      });233      if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);234      if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();235      return address;236    };237    let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;238    events.forEach(({event: {data, method, section}}) => {239      if ((section === 'common') && (method === 'Transfer')) {240        const hData = (data as any).toJSON();241        transfer = {242          collectionId: hData[0],243          tokenId: hData[1],244          from: normalizeAddress(hData[2]),245          to: normalizeAddress(hData[3]),246          amount: BigInt(hData[4]),247        };248      }249    });250    let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;251    isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);252    isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);253    isSuccess = isSuccess && amount === transfer.amount;254    return isSuccess;255  }256257  static bigIntToDecimals(number: bigint, decimals = 18) {258    const numberStr = number.toString();259    const dotPos = numberStr.length - decimals;260  261    if (dotPos <= 0) {262      return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;263    } else {264      const intPart = numberStr.substring(0, dotPos);265      const fractPart = numberStr.substring(dotPos);266      return intPart + '.' + fractPart;267    }268  }269}270271class UniqueEventHelper {272  private static extractIndex(index: any): [number, number] | string {273    if(index.toRawType() === '[u8;2]') return [index[0], index[1]];274    return index.toJSON();275  }276277  private static extractSub(data: any, subTypes: any): {[key: string]: any} {278    let obj: any = {};279    let index = 0;280281    if (data.entries) {282      for(const [key, value] of data.entries()) {283        obj[key] = this.extractData(value, subTypes[index]);284        index++;285      }286    } else obj = data.toJSON();287288    return obj;289  }290  291  private static extractData(data: any, type: any): any {292    if(!type) return data.toHuman();293    if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();294    if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();295    if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);296    return data.toHuman();297  }298299  public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {300    const parsedEvents: IEvent[] = [];301302    events.forEach((record) => {303      const {event, phase} = record;304      const types = event.typeDef;305306      const eventData: IEvent = {307        section: event.section.toString(),308        method: event.method.toString(),309        index: this.extractIndex(event.index),310        data: [],311        phase: phase.toJSON(),312      };313314      event.data.forEach((val: any, index: number) => {315        eventData.data.push(this.extractData(val, types[index]));316      });317318      parsedEvents.push(eventData);319    });320321    return parsedEvents;322  }323}324325export class ChainHelperBase {326  helperBase: any;327328  transactionStatus = UniqueUtil.transactionStatus;329  chainLogType = UniqueUtil.chainLogType;330  util: typeof UniqueUtil;331  eventHelper: typeof UniqueEventHelper;332  logger: ILogger;333  api: ApiPromise | null;334  forcedNetwork: TNetworks | null;335  network: TNetworks | null;336  chainLog: IUniqueHelperLog[];337  children: ChainHelperBase[];338  address: AddressGroup;339  chain: ChainGroup;340341  constructor(logger?: ILogger, helperBase?: any) {342    this.helperBase = helperBase;343344    this.util = UniqueUtil;345    this.eventHelper = UniqueEventHelper;346    if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();347    this.logger = logger;348    this.api = null;349    this.forcedNetwork = null;350    this.network = null;351    this.chainLog = [];352    this.children = [];353    this.address = new AddressGroup(this);354    this.chain = new ChainGroup(this);355  }356357  clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {358    Object.setPrototypeOf(helperCls.prototype, this);359    const newHelper = new helperCls(this.logger, options);360361    newHelper.api = this.api;362    newHelper.network = this.network;363    newHelper.forceNetwork = this.forceNetwork;364365    this.children.push(newHelper);366367    return newHelper;368  }369370  getApi(): ApiPromise {371    if(this.api === null) throw Error('API not initialized');372    return this.api;373  }374375  clearChainLog(): void {376    this.chainLog = [];377  }378379  forceNetwork(value: TNetworks): void {380    this.forcedNetwork = value;381  }382383  async connect(wsEndpoint: string, listeners?: IApiListeners) {384    if (this.api !== null) throw Error('Already connected');385    const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);386    this.api = api;387    this.network = network;388  }389390  async disconnect() {391    for (const child of this.children) {392      child.clearApi();393    }394395    if (this.api === null) return;396    await this.api.disconnect();397    this.clearApi();398  }399400  clearApi() {401    this.api = null;402    this.network = null;403  }404405  static async detectNetwork(api: ApiPromise): Promise<TNetworks> {406    const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;407    const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];408409    if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;410411    if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;412    return 'opal';413  }414415  static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {416    const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});417    await api.isReady;418419    const network = await this.detectNetwork(api);420421    await api.disconnect();422423    return network;424  }425426  static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{427    api: ApiPromise;428    network: TNetworks;429  }> {430    if(typeof network === 'undefined' || network === null) network = 'opal';431    const supportedRPC = {432      opal: {433        unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,434      },435      quartz: {436        unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,437      },438      unique: {439        unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,440      },441      rococo: {},442      westend: {},443      moonbeam: {},444      moonriver: {},445      acala: {},446      karura: {},447      westmint: {},448    };449    if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);450    const rpc = supportedRPC[network];451452    // TODO: investigate how to replace rpc in runtime453    // api._rpcCore.addUserInterfaces(rpc);454455    const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});456457    await api.isReadyOrError;458459    if (typeof listeners === 'undefined') listeners = {};460    for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {461      if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;462      api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);463    }464465    return {api, network};466  }467468  getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {469    const {events, status} = data;470    if (status.isReady) {471      return this.transactionStatus.NOT_READY;472    }473    if (status.isBroadcast) {474      return this.transactionStatus.NOT_READY;475    }476    if (status.isInBlock || status.isFinalized) {477      const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');478      if (errors.length > 0) {479        return this.transactionStatus.FAIL;480      }481      if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {482        return this.transactionStatus.SUCCESS;483      }484    }485486    return this.transactionStatus.FAIL;487  }488489  signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {490    const sign = (callback: any) => {491      if(options !== null) return transaction.signAndSend(sender, options, callback);492      return transaction.signAndSend(sender, callback);493    };494    // eslint-disable-next-line no-async-promise-executor495    return new Promise(async (resolve, reject) => {496      try {497        const unsub = await sign((result: any) => {498          const status = this.getTransactionStatus(result);499500          if (status === this.transactionStatus.SUCCESS) {501            this.logger.log(`${label} successful`);502            unsub();503            resolve({result, status});504          } else if (status === this.transactionStatus.FAIL) {505            let moduleError = null;506507            if (result.hasOwnProperty('dispatchError')) {508              const dispatchError = result['dispatchError'];509510              if (dispatchError) {511                if (dispatchError.isModule) {512                  const modErr = dispatchError.asModule;513                  const errorMeta = dispatchError.registry.findMetaError(modErr);514515                  moduleError = `${errorMeta.section}.${errorMeta.name}`;516                } else {517                  moduleError = dispatchError.toHuman();518                }519              } else {520                this.logger.log(result, this.logger.level.ERROR);521              }522            }523524            this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);525            unsub();526            reject({status, moduleError, result});527          }528        });529      } catch (e) {530        this.logger.log(e, this.logger.level.ERROR);531        reject(e);532      }533    });534  }535536  async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {537    const signingInfo = await this.api!.derive.tx.signingInfo(signer.address);538539    // We need to sign the tx because540    // unsigned transactions does not have an inclusion fee541    tx.sign(signer, {542      blockHash: this.api!.genesisHash,543      genesisHash: this.api!.genesisHash,544      runtimeVersion: this.api!.runtimeVersion,545      nonce: signingInfo.nonce,546    });547548    if (len === null) {549      return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;550    } else {551      return (await this.api!.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;552    }553  }554555  constructApiCall(apiCall: string, params: any[]) {556    if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);557    let call = this.getApi() as any;558    for(const part of apiCall.slice(4).split('.')) {559      call = call[part];560    }561    return call(...params);562  }563564  async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {565    if(this.api === null) throw Error('API not initialized');566    if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);567568    const startTime = (new Date()).getTime();569    let result: ITransactionResult;570    let events: IEvent[] = [];571    try {572      result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;573      events = this.eventHelper.extractEvents(result.result.events);574    }575    catch(e) {576      if(!(e as object).hasOwnProperty('status')) throw e;577      result = e as ITransactionResult;578    }579580    const endTime = (new Date()).getTime();581582    const log = {583      executedAt: endTime,584      executionTime: endTime - startTime,585      type: this.chainLogType.EXTRINSIC,586      status: result.status,587      call: extrinsic,588      signer: this.getSignerAddress(sender),589      params,590    } as IUniqueHelperLog;591592    if(result.status !== this.transactionStatus.SUCCESS) {593      if (result.moduleError) log.moduleError = result.moduleError;594      else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;595    }596    if(events.length > 0) log.events = events;597598    this.chainLog.push(log);599600    if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {601      if (result.moduleError) throw Error(`${result.moduleError}`);602      else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));603    }604    return result;605  }606607  async callRpc(rpc: string, params?: any[]) {608    if(typeof params === 'undefined') params = [];609    if(this.api === null) throw Error('API not initialized');610    if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);611612    const startTime = (new Date()).getTime();613    let result;614    let error = null;615    const log = {616      type: this.chainLogType.RPC,617      call: rpc,618      params,619    } as IUniqueHelperLog;620621    try {622      result = await this.constructApiCall(rpc, params);623    }624    catch(e) {625      error = e;626    }627628    const endTime = (new Date()).getTime();629630    log.executedAt = endTime;631    log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';632    log.executionTime = endTime - startTime;633634    this.chainLog.push(log);635636    if(error !== null) throw error;637638    return result;639  }640641  getSignerAddress(signer: IKeyringPair | string): string {642    if(typeof signer === 'string') return signer;643    return signer.address;644  }645646  fetchAllPalletNames(): string[] {647    if(this.api === null) throw Error('API not initialized');648    return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());649  }650651  fetchMissingPalletNames(requiredPallets: string[]): string[] {652    const palletNames = this.fetchAllPalletNames();653    return requiredPallets.filter(p => !palletNames.includes(p));654  }655}656657658class HelperGroup<T extends ChainHelperBase> {659  helper: T;660661  constructor(uniqueHelper: T) {662    this.helper = uniqueHelper;663  }664}665666667class CollectionGroup extends HelperGroup<UniqueHelper> {668  /**669 * Get number of blocks when sponsored transaction is available.670 *671 * @param collectionId ID of collection672 * @param tokenId ID of token673 * @param addressObj address for which the sponsorship is checked674 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});675 * @returns number of blocks or null if sponsorship hasn't been set676 */677  async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {678    return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();679  }680681  /**682   * Get the number of created collections.683   *684   * @returns number of created collections685   */686  async getTotalCount(): Promise<number> {687    return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();688  }689690  /**691   * Get information about the collection with additional data,692   * including the number of tokens it contains, its administrators,693   * the normalized address of the collection's owner, and decoded name and description.694   *695   * @param collectionId ID of collection696   * @example await getData(2)697   * @returns collection information object698   */699  async getData(collectionId: number): Promise<{700    id: number;701    name: string;702    description: string;703    tokensCount: number;704    admins: CrossAccountId[];705    normalizedOwner: TSubstrateAccount;706    raw: any707  } | null> {708    const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);709    const humanCollection = collection.toHuman(), collectionData = {710      id: collectionId, name: null, description: null, tokensCount: 0, admins: [],711      raw: humanCollection,712    } as any, jsonCollection = collection.toJSON();713    if (humanCollection === null) return null;714    collectionData.raw.limits = jsonCollection.limits;715    collectionData.raw.permissions = jsonCollection.permissions;716    collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);717    for (const key of ['name', 'description']) {718      collectionData[key] = this.helper.util.vec2str(humanCollection[key]);719    }720721    collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))722      ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)723      : 0;724    collectionData.admins = await this.getAdmins(collectionId);725726    return collectionData;727  }728729  /**730   * Get the addresses of the collection's administrators, optionally normalized.731   *732   * @param collectionId ID of collection733   * @param normalize whether to normalize the addresses to the default ss58 format734   * @example await getAdmins(1)735   * @returns array of administrators736   */737  async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {738    const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();739740    return normalize741      ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())742      : admins;743  }744745  /**746   * Get the addresses added to the collection allow-list, optionally normalized.747   * @param collectionId ID of collection748   * @param normalize whether to normalize the addresses to the default ss58 format749   * @example await getAllowList(1)750   * @returns array of allow-listed addresses751   */752  async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {753    const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();754    return normalize755      ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())756      : allowListed;757  }758759  /**760   * Get the effective limits of the collection instead of null for default values761   *762   * @param collectionId ID of collection763   * @example await getEffectiveLimits(2)764   * @returns object of collection limits765   */766  async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {767    return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();768  }769770  /**771   * Burns the collection if the signer has sufficient permissions and collection is empty.772   *773   * @param signer keyring of signer774   * @param collectionId ID of collection775   * @example await helper.collection.burn(aliceKeyring, 3);776   * @returns ```true``` if extrinsic success, otherwise ```false```777   */778  async burn(signer: TSigner, collectionId: number): Promise<boolean> {779    const result = await this.helper.executeExtrinsic(780      signer,781      'api.tx.unique.destroyCollection', [collectionId],782      true,783    );784785    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');786  }787788  /**789   * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.790   *791   * @param signer keyring of signer792   * @param collectionId ID of collection793   * @param sponsorAddress Sponsor substrate address794   * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")795   * @returns ```true``` if extrinsic success, otherwise ```false```796   */797  async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {798    const result = await this.helper.executeExtrinsic(799      signer,800      'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],801      true,802    );803804    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');805  }806807  /**808   * Confirms consent to sponsor the collection on behalf of the signer.809   *810   * @param signer keyring of signer811   * @param collectionId ID of collection812   * @example confirmSponsorship(aliceKeyring, 10)813   * @returns ```true``` if extrinsic success, otherwise ```false```814   */815  async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {816    const result = await this.helper.executeExtrinsic(817      signer,818      'api.tx.unique.confirmSponsorship', [collectionId],819      true,820    );821822    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');823  }824825  /**826   * Removes the sponsor of a collection, regardless if it consented or not.827   *828   * @param signer keyring of signer829   * @param collectionId ID of collection830   * @example removeSponsor(aliceKeyring, 10)831   * @returns ```true``` if extrinsic success, otherwise ```false```832   */833  async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {834    const result = await this.helper.executeExtrinsic(835      signer,836      'api.tx.unique.removeCollectionSponsor', [collectionId],837      true,838    );839840    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');841  }842843  /**844   * Sets the limits of the collection. At least one limit must be specified for a correct call.845   *846   * @param signer keyring of signer847   * @param collectionId ID of collection848   * @param limits collection limits object849   * @example850   * await setLimits(851   *   aliceKeyring,852   *   10,853   *   {854   *     sponsorTransferTimeout: 0,855   *     ownerCanDestroy: false856   *   }857   * )858   * @returns ```true``` if extrinsic success, otherwise ```false```859   */860  async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {861    const result = await this.helper.executeExtrinsic(862      signer,863      'api.tx.unique.setCollectionLimits', [collectionId, limits],864      true,865    );866867    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');868  }869870  /**871   * Changes the owner of the collection to the new Substrate address.872   *873   * @param signer keyring of signer874   * @param collectionId ID of collection875   * @param ownerAddress substrate address of new owner876   * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")877   * @returns ```true``` if extrinsic success, otherwise ```false```878   */879  async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {880    const result = await this.helper.executeExtrinsic(881      signer,882      'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],883      true,884    );885886    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');887  }888889  /**890   * Adds a collection administrator.891   *892   * @param signer keyring of signer893   * @param collectionId ID of collection894   * @param adminAddressObj Administrator address (substrate or ethereum)895   * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})896   * @returns ```true``` if extrinsic success, otherwise ```false```897   */898  async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {899    const result = await this.helper.executeExtrinsic(900      signer,901      'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],902      true,903    );904905    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');906  }907908  /**909   * Removes a collection administrator.910   *911   * @param signer keyring of signer912   * @param collectionId ID of collection913   * @param adminAddressObj Administrator address (substrate or ethereum)914   * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})915   * @returns ```true``` if extrinsic success, otherwise ```false```916   */917  async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {918    const result = await this.helper.executeExtrinsic(919      signer,920      'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],921      true,922    );923924    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');925  }926927  /**928   * Check if user is in allow list.929   * 930   * @param collectionId ID of collection931   * @param user Account to check932   * @example await getAdmins(1)933   * @returns is user in allow list934   */935  async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {936    return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();937  }938939  /**940   * Adds an address to allow list941   * @param signer keyring of signer942   * @param collectionId ID of collection943   * @param addressObj address to add to the allow list944   * @returns ```true``` if extrinsic success, otherwise ```false```945   */946  async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {947    const result = await this.helper.executeExtrinsic(948      signer,949      'api.tx.unique.addToAllowList', [collectionId, addressObj],950      true,951    );952953    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');954  }955956  /**957   * Removes an address from allow list958   *959   * @param signer keyring of signer960   * @param collectionId ID of collection961   * @param addressObj address to remove from the allow list962   * @returns ```true``` if extrinsic success, otherwise ```false```963   */964  async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {965    const result = await this.helper.executeExtrinsic(966      signer,967      'api.tx.unique.removeFromAllowList', [collectionId, addressObj],968      true,969    );970971    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');972  }973974  /**975   * Sets onchain permissions for selected collection.976   *977   * @param signer keyring of signer978   * @param collectionId ID of collection979   * @param permissions collection permissions object980   * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});981   * @returns ```true``` if extrinsic success, otherwise ```false```982   */983  async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {984    const result = await this.helper.executeExtrinsic(985      signer,986      'api.tx.unique.setCollectionPermissions', [collectionId, permissions],987      true,988    );989990    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');991  }992993  /**994   * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.995   *996   * @param signer keyring of signer997   * @param collectionId ID of collection998   * @param permissions nesting permissions object999   * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1000   * @returns ```true``` if extrinsic success, otherwise ```false```1001   */1002  async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1003    return await this.setPermissions(signer, collectionId, {nesting: permissions});1004  }10051006  /**1007   * Disables nesting for selected collection.1008   *1009   * @param signer keyring of signer1010   * @param collectionId ID of collection1011   * @example disableNesting(aliceKeyring, 10);1012   * @returns ```true``` if extrinsic success, otherwise ```false```1013   */1014  async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1015    return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1016  }10171018  /**1019   * Sets onchain properties to the collection.1020   *1021   * @param signer keyring of signer1022   * @param collectionId ID of collection1023   * @param properties array of property objects1024   * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1025   * @returns ```true``` if extrinsic success, otherwise ```false```1026   */1027  async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1028    const result = await this.helper.executeExtrinsic(1029      signer,1030      'api.tx.unique.setCollectionProperties', [collectionId, properties],1031      true,1032    );10331034    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1035  }10361037  /**1038   * Get collection properties.1039   * 1040   * @param collectionId ID of collection1041   * @param propertyKeys optionally filter the returned properties to only these keys1042   * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1043   * @returns array of key-value pairs1044   */1045  async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1046    return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1047  }10481049  async getCollectionOptions(collectionId: number) {1050    return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1051  }10521053  /**1054   * Deletes onchain properties from the collection.1055   *1056   * @param signer keyring of signer1057   * @param collectionId ID of collection1058   * @param propertyKeys array of property keys to delete1059   * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1060   * @returns ```true``` if extrinsic success, otherwise ```false```1061   */1062  async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1063    const result = await this.helper.executeExtrinsic(1064      signer,1065      'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1066      true,1067    );10681069    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1070  }10711072  /**1073   * Changes the owner of the token.1074   *1075   * @param signer keyring of signer1076   * @param collectionId ID of collection1077   * @param tokenId ID of token1078   * @param addressObj address of a new owner1079   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1080   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1081   * @returns true if the token success, otherwise false1082   */1083  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1084    const result = await this.helper.executeExtrinsic(1085      signer,1086      'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1087      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1088    );10891090    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1091  }10921093  /**1094   *1095   * Change ownership of a token(s) on behalf of the owner.1096   *1097   * @param signer keyring of signer1098   * @param collectionId ID of collection1099   * @param tokenId ID of token1100   * @param fromAddressObj address on behalf of which the token will be sent1101   * @param toAddressObj new token owner1102   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1103   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1104   * @returns true if the token success, otherwise false1105   */1106  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1107    const result = await this.helper.executeExtrinsic(1108      signer,1109      'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1110      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1111    );1112    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1113  }11141115  /**1116   *1117   * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1118   *1119   * @param signer keyring of signer1120   * @param collectionId ID of collection1121   * @param tokenId ID of token1122   * @param amount amount of tokens to be burned. For NFT must be set to 1n1123   * @example burnToken(aliceKeyring, 10, 5);1124   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1125   */1126  async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1127    const burnResult = await this.helper.executeExtrinsic(1128      signer,1129      'api.tx.unique.burnItem', [collectionId, tokenId, amount],1130      true, // `Unable to burn token for ${label}`,1131    );1132    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1133    if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1134    return burnedTokens.success;1135  }11361137  /**1138   * Destroys a concrete instance of NFT on behalf of the owner1139   *1140   * @param signer keyring of signer1141   * @param collectionId ID of collection1142   * @param tokenId ID of token1143   * @param fromAddressObj address on behalf of which the token will be burnt1144   * @param amount amount of tokens to be burned. For NFT must be set to 1n1145   * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1146   * @returns ```true``` if extrinsic success, otherwise ```false```1147   */1148  async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1149    const burnResult = await this.helper.executeExtrinsic(1150      signer,1151      'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1152      true, // `Unable to burn token from for ${label}`,1153    );1154    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1155    return burnedTokens.success && burnedTokens.tokens.length > 0;1156  }11571158  /**1159   * Set, change, or remove approved address to transfer the ownership of the NFT.1160   *1161   * @param signer keyring of signer1162   * @param collectionId ID of collection1163   * @param tokenId ID of token1164   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1165   * @param amount amount of token to be approved. For NFT must be set to 1n1166   * @returns ```true``` if extrinsic success, otherwise ```false```1167   */1168  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1169    const approveResult = await this.helper.executeExtrinsic(1170      signer,1171      'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1172      true, // `Unable to approve token for ${label}`,1173    );11741175    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1176  }11771178  /**1179   * Get the amount of token pieces approved to transfer or burn. Normally 0.1180   *1181   * @param collectionId ID of collection1182   * @param tokenId ID of token1183   * @param toAccountObj address which is approved to use token pieces1184   * @param fromAccountObj address which may have allowed the use of its owned tokens1185   * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1186   * @returns number of approved to transfer pieces1187   */1188  async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1189    return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1190  }11911192  /**1193   * Get the last created token ID in a collection1194   *1195   * @param collectionId ID of collection1196   * @example getLastTokenId(10);1197   * @returns id of the last created token1198   */1199  async getLastTokenId(collectionId: number): Promise<number> {1200    return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1201  }12021203  /**1204   * Check if token exists1205   *1206   * @param collectionId ID of collection1207   * @param tokenId ID of token1208   * @example doesTokenExist(10, 20);1209   * @returns true if the token exists, otherwise false1210   */1211  async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1212    return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1213  }1214}12151216class NFTnRFT extends CollectionGroup {1217  /**1218   * Get tokens owned by account1219   *1220   * @param collectionId ID of collection1221   * @param addressObj tokens owner1222   * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1223   * @returns array of token ids owned by account1224   */1225  async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1226    return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1227  }12281229  /**1230   * Get token data1231   *1232   * @param collectionId ID of collection1233   * @param tokenId ID of token1234   * @param propertyKeys optionally filter the token properties to only these keys1235   * @param blockHashAt optionally query the data at some block with this hash1236   * @example getToken(10, 5);1237   * @returns human readable token data1238   */1239  async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1240    properties: IProperty[];1241    owner: CrossAccountId;1242    normalizedOwner: CrossAccountId;1243  }| null> {1244    let tokenData;1245    if(typeof blockHashAt === 'undefined') {1246      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1247    }1248    else {1249      if(propertyKeys.length == 0) {1250        const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1251        if(!collection) return null;1252        propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1253      }1254      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1255    }1256    tokenData = tokenData.toHuman();1257    if (tokenData === null || tokenData.owner === null) return null;1258    const owner = {} as any;1259    for (const key of Object.keys(tokenData.owner)) {1260      owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1261        ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1262        : tokenData.owner[key];1263    }1264    tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1265    return tokenData;1266  }12671268  /**1269   * Set permissions to change token properties1270   *1271   * @param signer keyring of signer1272   * @param collectionId ID of collection1273   * @param permissions permissions to change a property by the collection admin or token owner1274   * @example setTokenPropertyPermissions(1275   *   aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1276   * )1277   * @returns true if extrinsic success otherwise false1278   */1279  async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1280    const result = await this.helper.executeExtrinsic(1281      signer,1282      'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1283      true,1284    );12851286    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1287  }12881289  /**1290   * Get token property permissions.1291   * 1292   * @param collectionId ID of collection1293   * @param propertyKeys optionally filter the returned property permissions to only these keys1294   * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1295   * @returns array of key-permission pairs1296   */1297  async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1298    return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1299  }13001301  /**1302   * Set token properties1303   *1304   * @param signer keyring of signer1305   * @param collectionId ID of collection1306   * @param tokenId ID of token1307   * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1308   * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1309   * @returns ```true``` if extrinsic success, otherwise ```false```1310   */1311  async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1312    const result = await this.helper.executeExtrinsic(1313      signer,1314      'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1315      true,1316    );13171318    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1319  }13201321  /**1322   * Get properties, metadata assigned to a token.1323   * 1324   * @param collectionId ID of collection1325   * @param tokenId ID of token1326   * @param propertyKeys optionally filter the returned properties to only these keys1327   * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1328   * @returns array of key-value pairs1329   */1330  async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1331    return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1332  }13331334  /**1335   * Delete the provided properties of a token1336   * @param signer keyring of signer1337   * @param collectionId ID of collection1338   * @param tokenId ID of token1339   * @param propertyKeys property keys to be deleted1340   * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1341   * @returns ```true``` if extrinsic success, otherwise ```false```1342   */1343  async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1344    const result = await this.helper.executeExtrinsic(1345      signer,1346      'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1347      true,1348    );13491350    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1351  }13521353  /**1354   * Mint new collection1355   *1356   * @param signer keyring of signer1357   * @param collectionOptions basic collection options and properties1358   * @param mode NFT or RFT type of a collection1359   * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1360   * @returns object of the created collection1361   */1362  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1363    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1364    collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1365    for (const key of ['name', 'description', 'tokenPrefix']) {1366      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);1367    }1368    const creationResult = await this.helper.executeExtrinsic(1369      signer,1370      'api.tx.unique.createCollectionEx', [collectionOptions],1371      true, // errorLabel,1372    );1373    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1374  }13751376  async mintDefaultCollection(signer: TSigner, mode: 'NFT' | 'RFT'): Promise<UniqueCollectionBase> {1377    const defaultCreateCollectionParams: ICollectionCreationOptions = {1378      description: 'description',1379      name: 'name',1380      tokenPrefix: 'prfx',1381    };13821383    return this.mintCollection(signer, defaultCreateCollectionParams, mode);1384  }13851386  getCollectionObject(_collectionId: number): any {1387    return null;1388  }13891390  getTokenObject(_collectionId: number, _tokenId: number): any {1391    return null;1392  }1393}139413951396class NFTGroup extends NFTnRFT {1397  /**1398   * Get collection object1399   * @param collectionId ID of collection1400   * @example getCollectionObject(2);1401   * @returns instance of UniqueNFTCollection1402   */1403  getCollectionObject(collectionId: number): UniqueNFTCollection {1404    return new UniqueNFTCollection(collectionId, this.helper);1405  }14061407  /**1408   * Get token object1409   * @param collectionId ID of collection1410   * @param tokenId ID of token1411   * @example getTokenObject(10, 5);1412   * @returns instance of UniqueNFTToken1413   */1414  getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1415    return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1416  }14171418  /**1419   * Get token's owner1420   * @param collectionId ID of collection1421   * @param tokenId ID of token1422   * @param blockHashAt optionally query the data at the block with this hash1423   * @example getTokenOwner(10, 5);1424   * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1425   */1426  async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1427    let owner;1428    if (typeof blockHashAt === 'undefined') {1429      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1430    } else {1431      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1432    }1433    return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1434  }14351436  /**1437   * Is token approved to transfer1438   * @param collectionId ID of collection1439   * @param tokenId ID of token1440   * @param toAccountObj address to be approved1441   * @returns ```true``` if extrinsic success, otherwise ```false```1442   */1443  async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1444    return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1445  }14461447  /**1448   * Changes the owner of the token.1449   *1450   * @param signer keyring of signer1451   * @param collectionId ID of collection1452   * @param tokenId ID of token1453   * @param addressObj address of a new owner1454   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1455   * @returns ```true``` if extrinsic success, otherwise ```false```1456   */1457  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1458    return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1459  }14601461  /**1462   *1463   * Change ownership of a NFT on behalf of the owner.1464   *1465   * @param signer keyring of signer1466   * @param collectionId ID of collection1467   * @param tokenId ID of token1468   * @param fromAddressObj address on behalf of which the token will be sent1469   * @param toAddressObj new token owner1470   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1471   * @returns ```true``` if extrinsic success, otherwise ```false```1472   */1473  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1474    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1475  }14761477  /**1478   * Recursively find the address that owns the token1479   * @param collectionId ID of collection1480   * @param tokenId ID of token1481   * @param blockHashAt1482   * @example getTokenTopmostOwner(10, 5);1483   * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1484   */1485  async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1486    let owner;1487    if (typeof blockHashAt === 'undefined') {1488      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1489    } else {1490      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1491    }14921493    if (owner === null) return null;14941495    return owner.toHuman();1496  }14971498  /**1499   * Get tokens nested in the provided token1500   * @param collectionId ID of collection1501   * @param tokenId ID of token1502   * @param blockHashAt optionally query the data at the block with this hash1503   * @example getTokenChildren(10, 5);1504   * @returns tokens whose depth of nesting is <= 51505   */1506  async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1507    let children;1508    if(typeof blockHashAt === 'undefined') {1509      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1510    } else {1511      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1512    }15131514    return children.toJSON().map((x: any) => {1515      return {collectionId: x.collection, tokenId: x.token};1516    });1517  }15181519  /**1520   * Nest one token into another1521   * @param signer keyring of signer1522   * @param tokenObj token to be nested1523   * @param rootTokenObj token to be parent1524   * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1525   * @returns ```true``` if extrinsic success, otherwise ```false```1526   */1527  async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1528    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1529    const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1530    if(!result) {1531      throw Error('Unable to nest token!');1532    }1533    return result;1534  }15351536  /**1537   * Remove token from nested state1538   * @param signer keyring of signer1539   * @param tokenObj token to unnest1540   * @param rootTokenObj parent of a token1541   * @param toAddressObj address of a new token owner1542   * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1543   * @returns ```true``` if extrinsic success, otherwise ```false```1544   */1545  async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1546    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1547    const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1548    if(!result) {1549      throw Error('Unable to unnest token!');1550    }1551    return result;1552  }15531554  /**1555   * Mint new collection1556   * @param signer keyring of signer1557   * @param collectionOptions Collection options1558   * @example1559   * mintCollection(aliceKeyring, {1560   *   name: 'New',1561   *   description: 'New collection',1562   *   tokenPrefix: 'NEW',1563   * })1564   * @returns object of the created collection1565   */1566  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1567    return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1568  }15691570  async mintDefaultCollection(signer: IKeyringPair): Promise<UniqueNFTCollection> {1571    return await super.mintDefaultCollection(signer, 'NFT') as UniqueNFTCollection;1572  }15731574  /**1575   * Mint new token1576   * @param signer keyring of signer1577   * @param data token data1578   * @returns created token object1579   */1580  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1581    const creationResult = await this.helper.executeExtrinsic(1582      signer,1583      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1584        nft: {1585          properties: data.properties,1586        },1587      }],1588      true,1589    );1590    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1591    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1592    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1593    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1594  }15951596  /**1597   * Mint multiple NFT tokens1598   * @param signer keyring of signer1599   * @param collectionId ID of collection1600   * @param tokens array of tokens with owner and properties1601   * @example1602   * mintMultipleTokens(aliceKeyring, 10, [{1603   *     owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1604   *     properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1605   *   },{1606   *     owner: {Ethereum: "0x9F0583DbB855d..."},1607   *     properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1608   * }]);1609   * @returns ```true``` if extrinsic success, otherwise ```false```1610   */1611  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1612    const creationResult = await this.helper.executeExtrinsic(1613      signer,1614      'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1615      true,1616    );1617    const collection = this.getCollectionObject(collectionId);1618    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1619  }16201621  /**1622   * Mint multiple NFT tokens with one owner1623   * @param signer keyring of signer1624   * @param collectionId ID of collection1625   * @param owner tokens owner1626   * @param tokens array of tokens with owner and properties1627   * @example1628   * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1629   *   properties: [{1630   *   key: "gender",1631   *   value: "female",1632   *  },{1633   *   key: "age",1634   *   value: "33",1635   *  }],1636   * }]);1637   * @returns array of newly created tokens1638   */1639  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1640    const rawTokens = [];1641    for (const token of tokens) {1642      const raw = {NFT: {properties: token.properties}};1643      rawTokens.push(raw);1644    }1645    const creationResult = await this.helper.executeExtrinsic(1646      signer,1647      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1648      true,1649    );1650    const collection = this.getCollectionObject(collectionId);1651    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1652  }16531654  /**1655   * Set, change, or remove approved address to transfer the ownership of the NFT.1656   *1657   * @param signer keyring of signer1658   * @param collectionId ID of collection1659   * @param tokenId ID of token1660   * @param toAddressObj address to approve1661   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1662   * @returns ```true``` if extrinsic success, otherwise ```false```1663   */1664  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1665    return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1666  }1667}166816691670class RFTGroup extends NFTnRFT {1671  /**1672   * Get collection object1673   * @param collectionId ID of collection1674   * @example getCollectionObject(2);1675   * @returns instance of UniqueRFTCollection1676   */1677  getCollectionObject(collectionId: number): UniqueRFTCollection {1678    return new UniqueRFTCollection(collectionId, this.helper);1679  }16801681  /**1682   * Get token object1683   * @param collectionId ID of collection1684   * @param tokenId ID of token1685   * @example getTokenObject(10, 5);1686   * @returns instance of UniqueNFTToken1687   */1688  getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1689    return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1690  }16911692  /**1693   * Get top 10 token owners with the largest number of pieces1694   * @param collectionId ID of collection1695   * @param tokenId ID of token1696   * @example getTokenTop10Owners(10, 5);1697   * @returns array of top 10 owners1698   */1699  async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1700    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1701  }17021703  /**1704   * Get number of pieces owned by address1705   * @param collectionId ID of collection1706   * @param tokenId ID of token1707   * @param addressObj address token owner1708   * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1709   * @returns number of pieces ownerd by address1710   */1711  async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1712    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1713  }17141715  /**1716   * Transfer pieces of token to another address1717   * @param signer keyring of signer1718   * @param collectionId ID of collection1719   * @param tokenId ID of token1720   * @param addressObj address of a new owner1721   * @param amount number of pieces to be transfered1722   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1723   * @returns ```true``` if extrinsic success, otherwise ```false```1724   */1725  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1726    return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1727  }17281729  /**1730   * Change ownership of some pieces of RFT on behalf of the owner.1731   * @param signer keyring of signer1732   * @param collectionId ID of collection1733   * @param tokenId ID of token1734   * @param fromAddressObj address on behalf of which the token will be sent1735   * @param toAddressObj new token owner1736   * @param amount number of pieces to be transfered1737   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1738   * @returns ```true``` if extrinsic success, otherwise ```false```1739   */1740  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1741    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1742  }17431744  /**1745   * Mint new collection1746   * @param signer keyring of signer1747   * @param collectionOptions Collection options1748   * @example1749   * mintCollection(aliceKeyring, {1750   *   name: 'New',1751   *   description: 'New collection',1752   *   tokenPrefix: 'NEW',1753   * })1754   * @returns object of the created collection1755   */1756  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1757    return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1758  }17591760  async mintDefaultCollection(signer: IKeyringPair): Promise<UniqueRFTCollection> {1761    return await super.mintDefaultCollection(signer, 'RFT') as UniqueRFTCollection;1762  }17631764  /**1765   * Mint new token1766   * @param signer keyring of signer1767   * @param data token data1768   * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1769   * @returns created token object1770   */1771  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1772    const creationResult = await this.helper.executeExtrinsic(1773      signer,1774      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1775        refungible: {1776          pieces: data.pieces,1777          properties: data.properties,1778        },1779      }],1780      true,1781    );1782    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1783    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1784    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1785    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1786  }17871788  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1789    throw Error('Not implemented');1790    const creationResult = await this.helper.executeExtrinsic(1791      signer,1792      'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1793      true, // `Unable to mint RFT tokens for ${label}`,1794    );1795    const collection = this.getCollectionObject(collectionId);1796    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1797  }17981799  /**1800   * Mint multiple RFT tokens with one owner1801   * @param signer keyring of signer1802   * @param collectionId ID of collection1803   * @param owner tokens owner1804   * @param tokens array of tokens with properties and pieces1805   * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1806   * @returns array of newly created RFT tokens1807   */1808  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1809    const rawTokens = [];1810    for (const token of tokens) {1811      const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1812      rawTokens.push(raw);1813    }1814    const creationResult = await this.helper.executeExtrinsic(1815      signer,1816      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1817      true,1818    );1819    const collection = this.getCollectionObject(collectionId);1820    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1821  }18221823  /**1824   * Destroys a concrete instance of RFT.1825   * @param signer keyring of signer1826   * @param collectionId ID of collection1827   * @param tokenId ID of token1828   * @param amount number of pieces to be burnt1829   * @example burnToken(aliceKeyring, 10, 5);1830   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1831   */1832  async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1833    return await super.burnToken(signer, collectionId, tokenId, amount);1834  }18351836  /**1837   * Destroys a concrete instance of RFT on behalf of the owner.1838   * @param signer keyring of signer1839   * @param collectionId ID of collection1840   * @param tokenId ID of token1841   * @param fromAddressObj address on behalf of which the token will be burnt1842   * @param amount number of pieces to be burnt1843   * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1844   * @returns ```true``` if extrinsic success, otherwise ```false```1845   */1846  async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1847    return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1848  }18491850  /**1851   * Set, change, or remove approved address to transfer the ownership of the RFT.1852   *1853   * @param signer keyring of signer1854   * @param collectionId ID of collection1855   * @param tokenId ID of token1856   * @param toAddressObj address to approve1857   * @param amount number of pieces to be approved1858   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1859   * @returns true if the token success, otherwise false1860   */1861  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1862    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1863  }18641865  /**1866   * Get total number of pieces1867   * @param collectionId ID of collection1868   * @param tokenId ID of token1869   * @example getTokenTotalPieces(10, 5);1870   * @returns number of pieces1871   */1872  async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1873    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1874  }18751876  /**1877   * Change number of token pieces. Signer must be the owner of all token pieces.1878   * @param signer keyring of signer1879   * @param collectionId ID of collection1880   * @param tokenId ID of token1881   * @param amount new number of pieces1882   * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1883   * @returns true if the repartion was success, otherwise false1884   */1885  async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1886    const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1887    const repartitionResult = await this.helper.executeExtrinsic(1888      signer,1889      'api.tx.unique.repartition', [collectionId, tokenId, amount],1890      true,1891    );1892    if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1893    return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1894  }1895}189618971898class FTGroup extends CollectionGroup {1899  /**1900   * Get collection object1901   * @param collectionId ID of collection1902   * @example getCollectionObject(2);1903   * @returns instance of UniqueFTCollection1904   */1905  getCollectionObject(collectionId: number): UniqueFTCollection {1906    return new UniqueFTCollection(collectionId, this.helper);1907  }19081909  /**1910   * Mint new fungible collection1911   * @param signer keyring of signer1912   * @param collectionOptions Collection options1913   * @param decimalPoints number of token decimals1914   * @example1915   * mintCollection(aliceKeyring, {1916   *   name: 'New',1917   *   description: 'New collection',1918   *   tokenPrefix: 'NEW',1919   * }, 18)1920   * @returns newly created fungible collection1921   */1922  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1923    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1924    if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1925    collectionOptions.mode = {fungible: decimalPoints};1926    for (const key of ['name', 'description', 'tokenPrefix']) {1927      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);1928    }1929    const creationResult = await this.helper.executeExtrinsic(1930      signer,1931      'api.tx.unique.createCollectionEx', [collectionOptions],1932      true,1933    );1934    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1935  }19361937  /**1938   * Mint tokens1939   * @param signer keyring of signer1940   * @param collectionId ID of collection1941   * @param owner address owner of new tokens1942   * @param amount amount of tokens to be meanted1943   * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1944   * @returns ```true``` if extrinsic success, otherwise ```false```1945   */1946  async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1947    const creationResult = await this.helper.executeExtrinsic(1948      signer,1949      'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1950        fungible: {1951          value: amount,1952        },1953      }],1954      true, // `Unable to mint fungible tokens for ${label}`,1955    );1956    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1957  }19581959  /**1960   * Mint multiple Fungible tokens with one owner1961   * @param signer keyring of signer1962   * @param collectionId ID of collection1963   * @param owner tokens owner1964   * @param tokens array of tokens with properties and pieces1965   * @returns ```true``` if extrinsic success, otherwise ```false```1966   */1967  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1968    const rawTokens = [];1969    for (const token of tokens) {1970      const raw = {Fungible: {Value: token.value}};1971      rawTokens.push(raw);1972    }1973    const creationResult = await this.helper.executeExtrinsic(1974      signer,1975      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1976      true,1977    );1978    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1979  }19801981  /**1982   * Get the top 10 owners with the largest balance for the Fungible collection1983   * @param collectionId ID of collection1984   * @example getTop10Owners(10);1985   * @returns array of ```ICrossAccountId```1986   */1987  async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1988    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1989  }19901991  /**1992   * Get account balance1993   * @param collectionId ID of collection1994   * @param addressObj address of owner1995   * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1996   * @returns amount of fungible tokens owned by address1997   */1998  async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1999    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2000  }20012002  /**2003   * Transfer tokens to address2004   * @param signer keyring of signer2005   * @param collectionId ID of collection2006   * @param toAddressObj address recipient2007   * @param amount amount of tokens to be sent2008   * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2009   * @returns ```true``` if extrinsic success, otherwise ```false```2010   */2011  async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2012    return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2013  }20142015  /**2016   * Transfer some tokens on behalf of the owner.2017   * @param signer keyring of signer2018   * @param collectionId ID of collection2019   * @param fromAddressObj address on behalf of which tokens will be sent2020   * @param toAddressObj address where token to be sent2021   * @param amount number of tokens to be sent2022   * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2023   * @returns ```true``` if extrinsic success, otherwise ```false```2024   */2025  async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2026    return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2027  }20282029  /**2030   * Destroy some amount of tokens2031   * @param signer keyring of signer2032   * @param collectionId ID of collection2033   * @param amount amount of tokens to be destroyed2034   * @example burnTokens(aliceKeyring, 10, 1000n);2035   * @returns ```true``` if extrinsic success, otherwise ```false```2036   */2037  async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2038    return await super.burnToken(signer, collectionId, 0, amount);2039  }20402041  /**2042   * Burn some tokens on behalf of the owner.2043   * @param signer keyring of signer2044   * @param collectionId ID of collection2045   * @param fromAddressObj address on behalf of which tokens will be burnt2046   * @param amount amount of tokens to be burnt2047   * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2048   * @returns ```true``` if extrinsic success, otherwise ```false```2049   */2050  async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2051    return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2052  }20532054  /**2055   * Get total collection supply2056   * @param collectionId2057   * @returns2058   */2059  async getTotalPieces(collectionId: number): Promise<bigint> {2060    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2061  }20622063  /**2064   * Set, change, or remove approved address to transfer tokens.2065   *2066   * @param signer keyring of signer2067   * @param collectionId ID of collection2068   * @param toAddressObj address to be approved2069   * @param amount amount of tokens to be approved2070   * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2071   * @returns ```true``` if extrinsic success, otherwise ```false```2072   */2073  async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2074    return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2075  }20762077  /**2078   * Get amount of fungible tokens approved to transfer2079   * @param collectionId ID of collection2080   * @param fromAddressObj owner of tokens2081   * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2082   * @returns number of tokens approved for the transfer2083   */2084  async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2085    return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2086  }2087}208820892090class ChainGroup extends HelperGroup<ChainHelperBase> {2091  /**2092   * Get system properties of a chain2093   * @example getChainProperties();2094   * @returns ss58Format, token decimals, and token symbol2095   */2096  getChainProperties(): IChainProperties {2097    const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2098    return {2099      ss58Format: properties.ss58Format.toJSON(),2100      tokenDecimals: properties.tokenDecimals.toJSON(),2101      tokenSymbol: properties.tokenSymbol.toJSON(),2102    };2103  }21042105  /**2106   * Get chain header2107   * @example getLatestBlockNumber();2108   * @returns the number of the last block2109   */2110  async getLatestBlockNumber(): Promise<number> {2111    return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2112  }21132114  /**2115   * Get block hash by block number2116   * @param blockNumber number of block2117   * @example getBlockHashByNumber(12345);2118   * @returns hash of a block2119   */2120  async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2121    const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2122    if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2123    return blockHash;2124  }21252126  // TODO add docs2127  async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2128    const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2129    if (!blockHash) return null;2130    return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2131  }21322133  /**2134   * Get account nonce2135   * @param address substrate address2136   * @example getNonce("5GrwvaEF5zXb26Fz...");2137   * @returns number, account's nonce2138   */2139  async getNonce(address: TSubstrateAccount): Promise<number> {2140    return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2141  }2142}21432144class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2145  /**2146 * Get substrate address balance2147 * @param address substrate address2148 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2149 * @returns amount of tokens on address2150 */2151  async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2152    return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2153  }21542155  /**2156   * Transfer tokens to substrate address2157   * @param signer keyring of signer2158   * @param address substrate address of a recipient2159   * @param amount amount of tokens to be transfered2160   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2161   * @returns ```true``` if extrinsic success, otherwise ```false```2162   */2163  async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2164    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}`*/);21652166    let transfer = {from: null, to: null, amount: 0n} as any;2167    result.result.events.forEach(({event: {data, method, section}}) => {2168      if ((section === 'balances') && (method === 'Transfer')) {2169        transfer = {2170          from: this.helper.address.normalizeSubstrate(data[0]),2171          to: this.helper.address.normalizeSubstrate(data[1]),2172          amount: BigInt(data[2]),2173        };2174      }2175    });2176    const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2177      && this.helper.address.normalizeSubstrate(address) === transfer.to 2178      && BigInt(amount) === transfer.amount;2179    return isSuccess;2180  }21812182  /**2183   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2184   * @param address substrate address2185   * @returns2186   */2187  async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2188    const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2189    return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2190  }2191}21922193class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2194  /**2195   * Get ethereum address balance2196   * @param address ethereum address2197   * @example getEthereum("0x9F0583DbB855d...")2198   * @returns amount of tokens on address2199   */2200  async getEthereum(address: TEthereumAccount): Promise<bigint> {2201    return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2202  }22032204  /**2205   * Transfer tokens to address2206   * @param signer keyring of signer2207   * @param address Ethereum address of a recipient2208   * @param amount amount of tokens to be transfered2209   * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2210   * @returns ```true``` if extrinsic success, otherwise ```false```2211   */2212  async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2213    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);22142215    let transfer = {from: null, to: null, amount: 0n} as any;2216    result.result.events.forEach(({event: {data, method, section}}) => {2217      if ((section === 'balances') && (method === 'Transfer')) {2218        transfer = {2219          from: data[0].toString(),2220          to: data[1].toString(),2221          amount: BigInt(data[2]),2222        };2223      }2224    });2225    const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from 2226      && address === transfer.to 2227      && BigInt(amount) === transfer.amount;2228    return isSuccess;2229  }2230}22312232class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2233  subBalanceGroup: SubstrateBalanceGroup<T>;2234  ethBalanceGroup: EthereumBalanceGroup<T>;22352236  constructor(helper: T) {2237    super(helper);2238    this.subBalanceGroup = new SubstrateBalanceGroup(helper);2239    this.ethBalanceGroup = new EthereumBalanceGroup(helper);2240  }22412242  getCollectionCreationPrice(): bigint {2243    return 2n * this.getOneTokenNominal();2244  }2245  /**2246   * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2247   * @example getOneTokenNominal()2248   * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2249   */2250  getOneTokenNominal(): bigint {2251    const chainProperties = this.helper.chain.getChainProperties();2252    return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2253  }22542255  /**2256   * Get substrate address balance2257   * @param address substrate address2258   * @example getSubstrate("5GrwvaEF5zXb26Fz...")2259   * @returns amount of tokens on address2260   */2261  async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2262    return this.subBalanceGroup.getSubstrate(address);2263  }22642265  /**2266   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2267   * @param address substrate address2268   * @returns2269   */2270  async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2271    return this.subBalanceGroup.getSubstrateFull(address);2272  }22732274  /**2275   * Get ethereum address balance2276   * @param address ethereum address2277   * @example getEthereum("0x9F0583DbB855d...")2278   * @returns amount of tokens on address2279   */2280  async getEthereum(address: TEthereumAccount): Promise<bigint> {2281    return this.ethBalanceGroup.getEthereum(address);2282  }22832284  /**2285   * Transfer tokens to substrate address2286   * @param signer keyring of signer2287   * @param address substrate address of a recipient2288   * @param amount amount of tokens to be transfered2289   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2290   * @returns ```true``` if extrinsic success, otherwise ```false```2291   */2292  async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2293    return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2294  }2295}22962297class AddressGroup extends HelperGroup<ChainHelperBase> {2298  /**2299   * Normalizes the address to the specified ss58 format, by default ```42```.2300   * @param address substrate address2301   * @param ss58Format format for address conversion, by default ```42```2302   * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2303   * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2304   */2305  normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2306    return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2307  }23082309  /**2310   * Get address in the connected chain format2311   * @param address substrate address2312   * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2313   * @returns address in chain format2314   */2315  normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2316    return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2317  }23182319  /**2320   * Get substrate mirror of an ethereum address2321   * @param ethAddress ethereum address2322   * @param toChainFormat false for normalized account2323   * @example ethToSubstrate('0x9F0583DbB855d...')2324   * @returns substrate mirror of a provided ethereum address2325   */2326  ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2327    return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2328  }23292330  /**2331   * Get ethereum mirror of a substrate address2332   * @param subAddress substrate account2333   * @example substrateToEth("5DnSF6RRjwteE3BrC...")2334   * @returns ethereum mirror of a provided substrate address2335   */2336  substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2337    return CrossAccountId.translateSubToEth(subAddress);2338  }23392340  paraSiblingSovereignAccount(paraid: number) {2341    // We are getting a *sibling* parachain sovereign account,2342    // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2343    const siblingPrefix = '0x7369626c';23442345    const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2346    const suffix = '000000000000000000000000000000000000000000000000';23472348    return siblingPrefix + encodedParaId + suffix;2349  }2350}23512352class StakingGroup extends HelperGroup<UniqueHelper> {2353  /**2354   * Stake tokens for App Promotion2355   * @param signer keyring of signer2356   * @param amountToStake amount of tokens to stake2357   * @param label extra label for log2358   * @returns2359   */2360  async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2361    if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2362    const _stakeResult = await this.helper.executeExtrinsic(2363      signer, 'api.tx.appPromotion.stake',2364      [amountToStake], true,2365    );2366    // TODO extract info from stakeResult2367    return true;2368  }23692370  /**2371   * Unstake tokens for App Promotion2372   * @param signer keyring of signer2373   * @param amountToUnstake amount of tokens to unstake2374   * @param label extra label for log2375   * @returns block number where balances will be unlocked2376   */2377  async unstake(signer: TSigner, label?: string): Promise<number> {2378    if(typeof label === 'undefined') label = `${signer.address}`;2379    const _unstakeResult = await this.helper.executeExtrinsic(2380      signer, 'api.tx.appPromotion.unstake',2381      [], true,2382    );2383    // TODO extract block number fron events2384    return 1;2385  }23862387  /**2388   * Get total staked amount for address2389   * @param address substrate or ethereum address2390   * @returns total staked amount2391   */2392  async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2393    if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2394    return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2395  }23962397  /**2398   * Get total staked per block2399   * @param address substrate or ethereum address2400   * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2401   */2402  async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2403    const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2404    return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2405      return { 2406        block: block.toBigInt(),2407        amount: amount.toBigInt(),2408      };2409    });2410  }24112412  /**2413   * Get total pending unstake amount for address2414   * @param address substrate or ethereum address2415   * @returns total pending unstake amount2416   */2417  async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2418    return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2419  }24202421  /**2422   * Get pending unstake amount per block for address2423   * @param address substrate or ethereum address2424   * @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 block2425   */2426  async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2427    const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2428    const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2429      return {2430        block: block.toBigInt(),2431        amount: amount.toBigInt(),2432      };2433    });2434    return result;2435  }2436}24372438class SchedulerGroup extends HelperGroup<UniqueHelper> {2439  scheduledIdSlider = 0;24402441  async waitNoScheduledTasks() {2442    const api = this.helper.api!;2443    2444    // eslint-disable-next-line no-async-promise-executor2445    const promise = new Promise<void>(async resolve => {2446      const unsubscribe = await api.rpc.chain.subscribeNewHeads(async () => {2447        const areThereScheduledTasks = await api.query.scheduler.lookup.entries();24482449        if(areThereScheduledTasks.length == 0) {2450          unsubscribe();2451          resolve();2452        }2453      }); 2454    });24552456    return promise;2457  }24582459  async makeScheduledIds(num: number): Promise<string[]> {2460    await this.waitNoScheduledTasks();24612462    function makeId(slider: number) {2463      const scheduledIdSize = 32;2464      const hexId = slider.toString(16);2465      const prefixSize = scheduledIdSize - hexId.length;24662467      const scheduledId = '0x' + '0'.repeat(prefixSize) + hexId;24682469      return scheduledId;  2470    }24712472    const ids = [];2473    for (let i = 0; i < num; i++) {2474      ids.push(makeId(this.scheduledIdSlider));2475      this.scheduledIdSlider += 1;2476    }24772478    return ids;2479  }24802481  async makeScheduledId(): Promise<string> {2482    return (await this.makeScheduledIds(1))[0];2483  }24842485  async cancelScheduled(signer: TSigner, scheduledId: string) {2486    return this.helper.executeExtrinsic(2487      signer,2488      'api.tx.scheduler.cancelNamed',2489      [scheduledId],2490      true,2491    );2492  }24932494  async changePriority(signer: TSigner, scheduledId: string, priority: number) {2495    return this.helper.executeExtrinsic(2496      signer,2497      'api.tx.scheduler.changeNamedPriority',2498      [scheduledId, priority],2499      true,2500    );2501  }25022503  scheduleAt<T extends UniqueHelper>(2504    scheduledId: string,2505    executionBlockNumber: number,2506    options: ISchedulerOptions = {},2507  ) {2508    return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2509  }25102511  scheduleAfter<T extends UniqueHelper>(2512    scheduledId: string,2513    blocksBeforeExecution: number,2514    options: ISchedulerOptions = {},2515  ) {2516    return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2517  }25182519  schedule<T extends UniqueHelper>(2520    scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2521    scheduledId: string,2522    blocksNum: number,2523    options: ISchedulerOptions = {},2524  ) {2525    // eslint-disable-next-line @typescript-eslint/naming-convention2526    const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2527    return this.helper.clone(ScheduledHelperType, {2528      scheduleFn,2529      scheduledId,2530      blocksNum,2531      options,2532    }) as T;2533  }2534}25352536class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2537  async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2538    await this.helper.executeExtrinsic(2539      signer,2540      'api.tx.foreignAssets.registerForeignAsset',2541      [ownerAddress, location, metadata],2542      true,2543    );2544  }25452546  async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2547    await this.helper.executeExtrinsic(2548      signer,2549      'api.tx.foreignAssets.updateForeignAsset',2550      [foreignAssetId, location, metadata],2551      true,2552    );2553  }2554}25552556class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2557  palletName: string;25582559  constructor(helper: T, palletName: string) {2560    super(helper);25612562    this.palletName = palletName;2563  }25642565  async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2566    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2567  }2568}25692570class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2571  async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2572    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2573  }25742575  async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2576    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2577  }25782579  async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2580    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2581  }2582}25832584class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2585  async accounts(address: string, currencyId: any) {2586    const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2587    return BigInt(free);2588  }2589}25902591class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2592  async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2593    await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2594  }25952596  async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2597    await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2598  }25992600  async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2601    await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2602  }26032604  async account(assetId: string | number, address: string) {2605    const accountAsset = (2606      await this.helper.callRpc('api.query.assets.account', [assetId, address])2607    ).toJSON()! as any;26082609    if (accountAsset !== null) {2610      return BigInt(accountAsset['balance']);2611    } else {2612      return null;2613    }2614  }2615}26162617class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2618  async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2619    await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2620  }2621}26222623class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2624  makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2625    const apiPrefix = 'api.tx.assetManager.';26262627    const registerTx = this.helper.constructApiCall(2628      apiPrefix + 'registerForeignAsset',2629      [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2630    );26312632    const setUnitsTx = this.helper.constructApiCall(2633      apiPrefix + 'setAssetUnitsPerSecond',2634      [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2635    );26362637    const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2638    const encodedProposal = batchCall?.method.toHex() || '';2639    return encodedProposal;2640  }26412642  async assetTypeId(location: any) {2643    return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2644  }2645}26462647class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2648  async notePreimage(signer: TSigner, encodedProposal: string) {2649    await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2650  }26512652  externalProposeMajority(proposalHash: string) {2653    return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2654  }26552656  fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2657    return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2658  }26592660  async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2661    await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2662  }2663}26642665class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2666  collective: string;26672668  constructor(helper: MoonbeamHelper, collective: string) {2669    super(helper);26702671    this.collective = collective;2672  }26732674  async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2675    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2676  }26772678  async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2679    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2680  }26812682  async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2683    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2684  }26852686  async proposalCount() {2687    return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2688  }2689}26902691export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2692export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;26932694export class UniqueHelper extends ChainHelperBase {2695  balance: BalanceGroup<UniqueHelper>;2696  collection: CollectionGroup;2697  nft: NFTGroup;2698  rft: RFTGroup;2699  ft: FTGroup;2700  staking: StakingGroup;2701  scheduler: SchedulerGroup;2702  foreignAssets: ForeignAssetsGroup;2703  xcm: XcmGroup<UniqueHelper>;2704  xTokens: XTokensGroup<UniqueHelper>;2705  tokens: TokensGroup<UniqueHelper>;27062707  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2708    super(logger, options.helperBase ?? UniqueHelper);27092710    this.balance = new BalanceGroup(this);2711    this.collection = new CollectionGroup(this);2712    this.nft = new NFTGroup(this);2713    this.rft = new RFTGroup(this);2714    this.ft = new FTGroup(this);2715    this.staking = new StakingGroup(this);2716    this.scheduler = new SchedulerGroup(this);2717    this.foreignAssets = new ForeignAssetsGroup(this);2718    this.xcm = new XcmGroup(this, 'polkadotXcm');2719    this.xTokens = new XTokensGroup(this);2720    this.tokens = new TokensGroup(this);2721  }27222723  getSudo<T extends UniqueHelper>() {2724    // eslint-disable-next-line @typescript-eslint/naming-convention2725    const SudoHelperType = SudoHelper(this.helperBase);2726    return this.clone(SudoHelperType) as T;2727  }2728}27292730export class XcmChainHelper extends ChainHelperBase {2731  async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2732    const wsProvider = new WsProvider(wsEndpoint);2733    this.api = new ApiPromise({2734      provider: wsProvider,2735    });2736    await this.api.isReadyOrError;2737    this.network = await UniqueHelper.detectNetwork(this.api);2738  }2739}27402741export class RelayHelper extends XcmChainHelper {2742  xcm: XcmGroup<RelayHelper>;27432744  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2745    super(logger, options.helperBase ?? RelayHelper);27462747    this.xcm = new XcmGroup(this, 'xcmPallet');2748  }2749}27502751export class WestmintHelper extends XcmChainHelper {2752  balance: SubstrateBalanceGroup<WestmintHelper>;2753  xcm: XcmGroup<WestmintHelper>;2754  assets: AssetsGroup<WestmintHelper>;2755  xTokens: XTokensGroup<WestmintHelper>;27562757  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2758    super(logger, options.helperBase ?? WestmintHelper);27592760    this.balance = new SubstrateBalanceGroup(this);2761    this.xcm = new XcmGroup(this, 'polkadotXcm');2762    this.assets = new AssetsGroup(this);2763    this.xTokens = new XTokensGroup(this);2764  }2765}27662767export class MoonbeamHelper extends XcmChainHelper {2768  balance: EthereumBalanceGroup<MoonbeamHelper>;2769  assetManager: MoonbeamAssetManagerGroup;2770  assets: AssetsGroup<MoonbeamHelper>;2771  xTokens: XTokensGroup<MoonbeamHelper>;2772  democracy: MoonbeamDemocracyGroup;2773  collective: {2774    council: MoonbeamCollectiveGroup,2775    techCommittee: MoonbeamCollectiveGroup,2776  };27772778  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2779    super(logger, options.helperBase ?? MoonbeamHelper);27802781    this.balance = new EthereumBalanceGroup(this);2782    this.assetManager = new MoonbeamAssetManagerGroup(this);2783    this.assets = new AssetsGroup(this);2784    this.xTokens = new XTokensGroup(this);2785    this.democracy = new MoonbeamDemocracyGroup(this);2786    this.collective = {2787      council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2788      techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2789    };2790  }2791}27922793export class AcalaHelper extends XcmChainHelper {2794  balance: SubstrateBalanceGroup<AcalaHelper>;2795  assetRegistry: AcalaAssetRegistryGroup;2796  xTokens: XTokensGroup<AcalaHelper>;2797  tokens: TokensGroup<AcalaHelper>;27982799  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2800    super(logger, options.helperBase ?? AcalaHelper);28012802    this.balance = new SubstrateBalanceGroup(this);2803    this.assetRegistry = new AcalaAssetRegistryGroup(this);2804    this.xTokens = new XTokensGroup(this);2805    this.tokens = new TokensGroup(this);2806  }28072808  getSudo<T extends AcalaHelper>() {2809    // eslint-disable-next-line @typescript-eslint/naming-convention2810    const SudoHelperType = SudoHelper(this.helperBase);2811    return this.clone(SudoHelperType) as T;2812  }2813}28142815// eslint-disable-next-line @typescript-eslint/naming-convention2816function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2817  return class extends Base {2818    scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2819    scheduledId: string;2820    blocksNum: number;2821    options: ISchedulerOptions;28222823    constructor(...args: any[]) {2824      const logger = args[0] as ILogger;2825      const options = args[1] as {2826        scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2827        scheduledId: string,2828        blocksNum: number,2829        options: ISchedulerOptions2830      };28312832      super(logger);28332834      this.scheduleFn = options.scheduleFn;2835      this.scheduledId = options.scheduledId;2836      this.blocksNum = options.blocksNum;2837      this.options = options.options;2838    }28392840    executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2841      const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2842      const extrinsic = 'api.tx.scheduler.' +  this.scheduleFn;28432844      return super.executeExtrinsic(2845        sender,2846        extrinsic,2847        [2848          this.scheduledId,2849          this.blocksNum,2850          this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2851          this.options.priority ?? null,2852          {Value: scheduledTx},2853        ],2854        expectSuccess,2855      );2856    }2857  };2858}28592860// eslint-disable-next-line @typescript-eslint/naming-convention2861function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2862  return class extends Base {2863    constructor(...args: any[]) {2864      super(...args);2865    }28662867    executeExtrinsic (2868      sender: IKeyringPair,2869      extrinsic: string,2870      params: any[],2871      expectSuccess?: boolean,2872    ): Promise<ITransactionResult> {2873      const call = this.constructApiCall(extrinsic, params);28742875      return super.executeExtrinsic(2876        sender,2877        'api.tx.sudo.sudo',2878        [call],2879        expectSuccess,2880      );2881    }2882  };2883}28842885export class UniqueBaseCollection {2886  helper: UniqueHelper;2887  collectionId: number;28882889  constructor(collectionId: number, uniqueHelper: UniqueHelper) {2890    this.collectionId = collectionId;2891    this.helper = uniqueHelper;2892  }28932894  async getData() {2895    return await this.helper.collection.getData(this.collectionId);2896  }28972898  async getLastTokenId() {2899    return await this.helper.collection.getLastTokenId(this.collectionId);2900  }29012902  async doesTokenExist(tokenId: number) {2903    return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2904  }29052906  async getAdmins() {2907    return await this.helper.collection.getAdmins(this.collectionId);2908  }29092910  async getAllowList() {2911    return await this.helper.collection.getAllowList(this.collectionId);2912  }29132914  async getEffectiveLimits() {2915    return await this.helper.collection.getEffectiveLimits(this.collectionId);2916  }29172918  async getProperties(propertyKeys?: string[] | null) {2919    return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2920  }29212922  async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2923    return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2924  }29252926  async getOptions() {2927    return await this.helper.collection.getCollectionOptions(this.collectionId);2928  }29292930  async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2931    return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2932  }29332934  async confirmSponsorship(signer: TSigner) {2935    return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2936  }29372938  async removeSponsor(signer: TSigner) {2939    return await this.helper.collection.removeSponsor(signer, this.collectionId);2940  }29412942  async setLimits(signer: TSigner, limits: ICollectionLimits) {2943    return await this.helper.collection.setLimits(signer, this.collectionId, limits);2944  }29452946  async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2947    return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2948  }29492950  async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2951    return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2952  }29532954  async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2955    return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2956  }29572958  async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2959    return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2960  }29612962  async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2963    return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2964  }29652966  async setProperties(signer: TSigner, properties: IProperty[]) {2967    return await this.helper.collection.setProperties(signer, this.collectionId, properties);2968  }29692970  async deleteProperties(signer: TSigner, propertyKeys: string[]) {2971    return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2972  }29732974  async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2975    return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2976  }29772978  async enableNesting(signer: TSigner, permissions: INestingPermissions) {2979    return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2980  }29812982  async disableNesting(signer: TSigner) {2983    return await this.helper.collection.disableNesting(signer, this.collectionId);2984  }29852986  async burn(signer: TSigner) {2987    return await this.helper.collection.burn(signer, this.collectionId);2988  }29892990  scheduleAt<T extends UniqueHelper>(2991    scheduledId: string,2992    executionBlockNumber: number,2993    options: ISchedulerOptions = {},2994  ) {2995    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2996    return new UniqueBaseCollection(this.collectionId, scheduledHelper);2997  }29982999  scheduleAfter<T extends UniqueHelper>(3000    scheduledId: string,3001    blocksBeforeExecution: number,3002    options: ISchedulerOptions = {},3003  ) {3004    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3005    return new UniqueBaseCollection(this.collectionId, scheduledHelper);3006  }30073008  getSudo<T extends UniqueHelper>() {3009    return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3010  }3011}301230133014export class UniqueNFTCollection extends UniqueBaseCollection {3015  getTokenObject(tokenId: number) {3016    return new UniqueNFToken(tokenId, this);3017  }30183019  async getTokensByAddress(addressObj: ICrossAccountId) {3020    return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3021  }30223023  async getToken(tokenId: number, blockHashAt?: string) {3024    return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3025  }30263027  async getTokenOwner(tokenId: number, blockHashAt?: string) {3028    return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3029  }30303031  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3032    return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3033  }30343035  async getTokenChildren(tokenId: number, blockHashAt?: string) {3036    return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3037  }30383039  async getPropertyPermissions(propertyKeys: string[] | null = null) {3040    return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3041  }30423043  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3044    return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3045  }30463047  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3048    return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3049  }30503051  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3052    return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3053  }30543055  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3056    return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3057  }30583059  async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3060    return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3061  }30623063  async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3064    return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3065  }30663067  async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3068    return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3069  }30703071  async burnToken(signer: TSigner, tokenId: number) {3072    return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3073  }30743075  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3076    return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3077  }30783079  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3080    return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3081  }30823083  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3084    return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3085  }30863087  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3088    return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3089  }30903091  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3092    return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3093  }30943095  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3096    return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3097  }30983099  scheduleAt<T extends UniqueHelper>(3100    scheduledId: string,3101    executionBlockNumber: number,3102    options: ISchedulerOptions = {},3103  ) {3104    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3105    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3106  }31073108  scheduleAfter<T extends UniqueHelper>(3109    scheduledId: string,3110    blocksBeforeExecution: number,3111    options: ISchedulerOptions = {},3112  ) {3113    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3114    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3115  }31163117  getSudo<T extends UniqueHelper>() {3118    return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3119  }3120}312131223123export class UniqueRFTCollection extends UniqueBaseCollection {3124  getTokenObject(tokenId: number) {3125    return new UniqueRFToken(tokenId, this);3126  }31273128  async getToken(tokenId: number, blockHashAt?: string) {3129    return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3130  }31313132  async getTokensByAddress(addressObj: ICrossAccountId) {3133    return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3134  }31353136  async getTop10TokenOwners(tokenId: number) {3137    return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3138  }31393140  async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3141    return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3142  }31433144  async getTokenTotalPieces(tokenId: number) {3145    return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3146  }31473148  async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3149    return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3150  }31513152  async getPropertyPermissions(propertyKeys: string[] | null = null) {3153    return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3154  }31553156  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3157    return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3158  }31593160  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3161    return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3162  }31633164  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3165    return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3166  }31673168  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3169    return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3170  }31713172  async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3173    return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3174  }31753176  async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3177    return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3178  }31793180  async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3181    return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3182  }31833184  async burnToken(signer: TSigner, tokenId: number, amount=1n) {3185    return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3186  }31873188  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId,  amount=1n) {3189    return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3190  }31913192  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3193    return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3194  }31953196  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3197    return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3198  }31993200  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3201    return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3202  }32033204  scheduleAt<T extends UniqueHelper>(3205    scheduledId: string,3206    executionBlockNumber: number,3207    options: ISchedulerOptions = {},3208  ) {3209    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3210    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3211  }32123213  scheduleAfter<T extends UniqueHelper>(3214    scheduledId: string,3215    blocksBeforeExecution: number,3216    options: ISchedulerOptions = {},3217  ) {3218    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3219    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3220  }32213222  getSudo<T extends UniqueHelper>() {3223    return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3224  }3225}322632273228export class UniqueFTCollection extends UniqueBaseCollection {3229  async getBalance(addressObj: ICrossAccountId) {3230    return await this.helper.ft.getBalance(this.collectionId, addressObj);3231  }32323233  async getTotalPieces() {3234    return await this.helper.ft.getTotalPieces(this.collectionId);3235  }32363237  async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3238    return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3239  }32403241  async getTop10Owners() {3242    return await this.helper.ft.getTop10Owners(this.collectionId);3243  }32443245  async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3246    return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3247  }32483249  async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3250    return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3251  }32523253  async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3254    return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3255  }32563257  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3258    return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3259  }32603261  async burnTokens(signer: TSigner, amount=1n) {3262    return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3263  }32643265  async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3266    return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3267  }32683269  async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3270    return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3271  }32723273  scheduleAt<T extends UniqueHelper>(3274    scheduledId: string,3275    executionBlockNumber: number,3276    options: ISchedulerOptions = {},3277  ) {3278    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3279    return new UniqueFTCollection(this.collectionId, scheduledHelper);3280  }32813282  scheduleAfter<T extends UniqueHelper>(3283    scheduledId: string,3284    blocksBeforeExecution: number,3285    options: ISchedulerOptions = {},3286  ) {3287    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3288    return new UniqueFTCollection(this.collectionId, scheduledHelper);3289  }32903291  getSudo<T extends UniqueHelper>() {3292    return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3293  }3294}329532963297export class UniqueBaseToken {3298  collection: UniqueNFTCollection | UniqueRFTCollection;3299  collectionId: number;3300  tokenId: number;33013302  constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3303    this.collection = collection;3304    this.collectionId = collection.collectionId;3305    this.tokenId = tokenId;3306  }33073308  async getNextSponsored(addressObj: ICrossAccountId) {3309    return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3310  }33113312  async getProperties(propertyKeys?: string[] | null) {3313    return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3314  }33153316  async setProperties(signer: TSigner, properties: IProperty[]) {3317    return await this.collection.setTokenProperties(signer, this.tokenId, properties);3318  }33193320  async deleteProperties(signer: TSigner, propertyKeys: string[]) {3321    return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3322  }33233324  async doesExist() {3325    return await this.collection.doesTokenExist(this.tokenId);3326  }33273328  nestingAccount() {3329    return this.collection.helper.util.getTokenAccount(this);3330  }33313332  scheduleAt<T extends UniqueHelper>(3333    scheduledId: string,3334    executionBlockNumber: number,3335    options: ISchedulerOptions = {},3336  ) {3337    const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3338    return new UniqueBaseToken(this.tokenId, scheduledCollection);3339  }33403341  scheduleAfter<T extends UniqueHelper>(3342    scheduledId: string,3343    blocksBeforeExecution: number,3344    options: ISchedulerOptions = {},3345  ) {3346    const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3347    return new UniqueBaseToken(this.tokenId, scheduledCollection);3348  }33493350  getSudo<T extends UniqueHelper>() {3351    return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3352  }3353}335433553356export class UniqueNFToken extends UniqueBaseToken {3357  collection: UniqueNFTCollection;33583359  constructor(tokenId: number, collection: UniqueNFTCollection) {3360    super(tokenId, collection);3361    this.collection = collection;3362  }33633364  async getData(blockHashAt?: string) {3365    return await this.collection.getToken(this.tokenId, blockHashAt);3366  }33673368  async getOwner(blockHashAt?: string) {3369    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3370  }33713372  async getTopmostOwner(blockHashAt?: string) {3373    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3374  }33753376  async getChildren(blockHashAt?: string) {3377    return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3378  }33793380  async nest(signer: TSigner, toTokenObj: IToken) {3381    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3382  }33833384  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3385    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3386  }33873388  async transfer(signer: TSigner, addressObj: ICrossAccountId) {3389    return await this.collection.transferToken(signer, this.tokenId, addressObj);3390  }33913392  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3393    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3394  }33953396  async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3397    return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3398  }33993400  async isApproved(toAddressObj: ICrossAccountId) {3401    return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3402  }34033404  async burn(signer: TSigner) {3405    return await this.collection.burnToken(signer, this.tokenId);3406  }34073408  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3409    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3410  }34113412  scheduleAt<T extends UniqueHelper>(3413    scheduledId: string,3414    executionBlockNumber: number,3415    options: ISchedulerOptions = {},3416  ) {3417    const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3418    return new UniqueNFToken(this.tokenId, scheduledCollection);3419  }34203421  scheduleAfter<T extends UniqueHelper>(3422    scheduledId: string,3423    blocksBeforeExecution: number,3424    options: ISchedulerOptions = {},3425  ) {3426    const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3427    return new UniqueNFToken(this.tokenId, scheduledCollection);3428  }34293430  getSudo<T extends UniqueHelper>() {3431    return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3432  }3433}34343435export class UniqueRFToken extends UniqueBaseToken {3436  collection: UniqueRFTCollection;34373438  constructor(tokenId: number, collection: UniqueRFTCollection) {3439    super(tokenId, collection);3440    this.collection = collection;3441  }34423443  async getData(blockHashAt?: string) {3444    return await this.collection.getToken(this.tokenId, blockHashAt);3445  }34463447  async getTop10Owners() {3448    return await this.collection.getTop10TokenOwners(this.tokenId);3449  }34503451  async getBalance(addressObj: ICrossAccountId) {3452    return await this.collection.getTokenBalance(this.tokenId, addressObj);3453  }34543455  async getTotalPieces() {3456    return await this.collection.getTokenTotalPieces(this.tokenId);3457  }34583459  async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3460    return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3461  }34623463  async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3464    return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3465  }34663467  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3468    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3469  }34703471  async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3472    return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3473  }34743475  async repartition(signer: TSigner, amount: bigint) {3476    return await this.collection.repartitionToken(signer, this.tokenId, amount);3477  }34783479  async burn(signer: TSigner, amount=1n) {3480    return await this.collection.burnToken(signer, this.tokenId, amount);3481  }34823483  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3484    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3485  }34863487  scheduleAt<T extends UniqueHelper>(3488    scheduledId: string,3489    executionBlockNumber: number,3490    options: ISchedulerOptions = {},3491  ) {3492    const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3493    return new UniqueRFToken(this.tokenId, scheduledCollection);3494  }34953496  scheduleAfter<T extends UniqueHelper>(3497    scheduledId: string,3498    blocksBeforeExecution: number,3499    options: ISchedulerOptions = {},3500  ) {3501    const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3502    return new UniqueRFToken(this.tokenId, scheduledCollection);3503  }35043505  getSudo<T extends UniqueHelper>() {3506    return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3507  }3508}