git.delta.rocks / unique-network / refs/commits / 52ec20b9c55b

difftreelog

feat calculatePovInfo playgrnd method

Daniel Shiposha2022-11-24parent: #2aae8ed.patch.diff
in: master

3 files changed

modifiedtests/src/util/playgrounds/types.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -171,6 +171,14 @@
   amount: bigint,
 }
 
+export interface IPovInfo {
+  proofSize: number,
+  compactProofSize: number,
+  compressedProofSize: number,
+  results: any[],
+  kv: any,
+}
+
 export interface ISchedulerOptions {
   scheduledId?: string,
   priority?: number,
modifiedtests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -8,10 +8,11 @@
 import * as defs from '../../interfaces/definitions';
 import {IKeyringPair} from '@polkadot/types/types';
 import {EventRecord} from '@polkadot/types/interfaces';
-import {ICrossAccountId, TSigner} from './types';
+import {ICrossAccountId, IPovInfo, TSigner} from './types';
 import {FrameSystemEventRecord} from '@polkadot/types/lookup';
 import {VoidFn} from '@polkadot/api/types';
 import {Pallets} from '..';
+import {spawnSync} from 'child_process';
 
 export class SilentLogger {
   log(_msg: any, _level: any): void { }
@@ -322,6 +323,34 @@
     return balance;
   }
 
+  async calculatePoVInfo(txs: any[]): Promise<IPovInfo> {
+    const rawPovInfo = await this.helper.callRpc('api.rpc.unique.estimateExtrinsicPoV', [txs]);
+
+    const kvJson: {[key: string]: string} = {};
+
+    for (const kv of rawPovInfo.keyValues) {
+      kvJson[kv.key.toHex()] = kv.value.toHex();
+    }
+
+    const kvStr = JSON.stringify(kvJson);
+
+    const chainql = spawnSync(
+      'chainql', 
+      [
+        `--tla-code=data=${kvStr}`,
+        '-e', 'function(data) cql.dump(cql.chain("wss://ws-opal.unique.network:443").latest._meta, data, {omit_empty:true})',
+      ],
+    );
+
+    return {
+      proofSize: rawPovInfo.proofSize.toNumber(),
+      compactProofSize: rawPovInfo.compactProofSize.toNumber(),
+      compressedProofSize: rawPovInfo.compressedProofSize.toNumber(),
+      results: rawPovInfo.results,
+      kv: JSON.parse(chainql.stdout.toString()),
+    };
+  }
+
   calculatePalletAddress(palletId: any) {
     const address = stringToU8a(('modl' + palletId).padEnd(32, '\0'));
     return encodeAddress(address, this.helper.chain.getChainProperties().ss58Format);
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
before · tests/src/util/playgrounds/unique.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {hexToU8a} from '@polkadot/util/hex';13import {u8aConcat} from '@polkadot/util/u8a';14import {15  IApiListeners,16  IBlock,17  IEvent,18  IChainProperties,19  ICollectionCreationOptions,20  ICollectionLimits,21  ICollectionPermissions,22  ICrossAccountId,23  ICrossAccountIdLower,24  ILogger,25  INestingPermissions,26  IProperty,27  IStakingInfo,28  ISchedulerOptions,29  ISubstrateBalance,30  IToken,31  ITokenPropertyPermission,32  ITransactionResult,33  IUniqueHelperLog,34  TApiAllowedListeners,35  TEthereumAccount,36  TSigner,37  TSubstrateAccount,38  TNetworks,39  IForeignAssetMetadata,40  AcalaAssetMetadata,41  MoonbeamAssetInfo,42  DemocracyStandardAccountVote,43  IEthCrossAccountId,44} from './types';45import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';46import type {Vec} from '@polkadot/types-codec';47import {FrameSystemEventRecord} from '@polkadot/types/lookup';4849export class CrossAccountId implements ICrossAccountId {50  Substrate?: TSubstrateAccount;51  Ethereum?: TEthereumAccount;5253  constructor(account: ICrossAccountId) {54    if (account.Substrate) this.Substrate = account.Substrate;55    if (account.Ethereum) this.Ethereum = account.Ethereum;56  }5758  static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {59    switch (domain) {60      case 'Substrate': return new CrossAccountId({Substrate: account.address});61      case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();62    }63  }6465  static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {66    return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});67  }6869  static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {70    return encodeAddress(decodeAddress(address), ss58Format);71  }7273  static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {74    return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});75  }7677  withNormalizedSubstrate(ss58Format = 42): CrossAccountId {78    if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);79    return this;80  }8182  static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {83    return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));84  }8586  toEthereum(): CrossAccountId {87    if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});88    return this;89  }9091  static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {92    return evmToAddress(address, ss58Format);93  }9495  toSubstrate(ss58Format?: number): CrossAccountId {96    if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});97    return this;98  }99100  toLowerCase(): CrossAccountId {101    if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();102    if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();103    return this;104  }105}106107const nesting = {108  toChecksumAddress(address: string): string {109    if (typeof address === 'undefined') return '';110111    if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);112113    address = address.toLowerCase().replace(/^0x/i,'');114    const addressHash = keccakAsHex(address).replace(/^0x/i,'');115    const checksumAddress = ['0x'];116117    for (let i = 0; i < address.length; i++) {118      // If ith character is 8 to f then make it uppercase119      if (parseInt(addressHash[i], 16) > 7) {120        checksumAddress.push(address[i].toUpperCase());121      } else {122        checksumAddress.push(address[i]);123      }124    }125    return checksumAddress.join('');126  },127  tokenIdToAddress(collectionId: number, tokenId: number) {128    return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);129  },130};131132class UniqueUtil {133  static transactionStatus = {134    NOT_READY: 'NotReady',135    FAIL: 'Fail',136    SUCCESS: 'Success',137  };138139  static chainLogType = {140    EXTRINSIC: 'extrinsic',141    RPC: 'rpc',142  };143144  static getTokenAccount(token: IToken): CrossAccountId {145    return new CrossAccountId({Ethereum: this.getTokenAddress(token)});146  }147148  static getTokenAddress(token: IToken): string {149    return nesting.tokenIdToAddress(token.collectionId, token.tokenId);150  }151152  static getDefaultLogger(): ILogger {153    return {154      log(msg: any, level = 'INFO') {155        console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));156      },157      level: {158        ERROR: 'ERROR',159        WARNING: 'WARNING',160        INFO: 'INFO',161      },162    };163  }164165  static vec2str(arr: string[] | number[]) {166    return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');167  }168169  static str2vec(string: string) {170    if (typeof string !== 'string') return string;171    return Array.from(string).map(x => x.charCodeAt(0));172  }173174  static fromSeed(seed: string, ss58Format = 42) {175    const keyring = new Keyring({type: 'sr25519', ss58Format});176    return keyring.addFromUri(seed);177  }178179  static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {180    if (creationResult.status !== this.transactionStatus.SUCCESS) {181      throw Error('Unable to create collection!');182    }183184    let collectionId = null;185    creationResult.result.events.forEach(({event: {data, method, section}}) => {186      if ((section === 'common') && (method === 'CollectionCreated')) {187        collectionId = parseInt(data[0].toString(), 10);188      }189    });190191    if (collectionId === null) {192      throw Error('No CollectionCreated event was found!');193    }194195    return collectionId;196  }197198  static extractTokensFromCreationResult(creationResult: ITransactionResult): {199    success: boolean,200    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],201  } {202    if (creationResult.status !== this.transactionStatus.SUCCESS) {203      throw Error('Unable to create tokens!');204    }205    let success = false;206    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];207    creationResult.result.events.forEach(({event: {data, method, section}}) => {208      if (method === 'ExtrinsicSuccess') {209        success = true;210      } else if ((section === 'common') && (method === 'ItemCreated')) {211        tokens.push({212          collectionId: parseInt(data[0].toString(), 10),213          tokenId: parseInt(data[1].toString(), 10),214          owner: data[2].toHuman(),215          amount: data[3].toBigInt(),216        });217      }218    });219    return {success, tokens};220  }221222  static extractTokensFromBurnResult(burnResult: ITransactionResult): {223    success: boolean,224    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],225  } {226    if (burnResult.status !== this.transactionStatus.SUCCESS) {227      throw Error('Unable to burn tokens!');228    }229    let success = false;230    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];231    burnResult.result.events.forEach(({event: {data, method, section}}) => {232      if (method === 'ExtrinsicSuccess') {233        success = true;234      } else if ((section === 'common') && (method === 'ItemDestroyed')) {235        tokens.push({236          collectionId: parseInt(data[0].toString(), 10),237          tokenId: parseInt(data[1].toString(), 10),238          owner: data[2].toHuman(),239          amount: data[3].toBigInt(),240        });241      }242    });243    return {success, tokens};244  }245246  static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {247    let eventId = null;248    events.forEach(({event: {data, method, section}}) => {249      if ((section === expectedSection) && (method === expectedMethod)) {250        eventId = parseInt(data[0].toString(), 10);251      }252    });253254    if (eventId === null) {255      throw Error(`No ${expectedMethod} event was found!`);256    }257    return eventId === collectionId;258  }259260  static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {261    const normalizeAddress = (address: string | ICrossAccountId) => {262      if(typeof address === 'string') return address;263      const obj = {} as any;264      Object.keys(address).forEach(k => {265        obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];266      });267      if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);268      if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();269      return address;270    };271    let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;272    events.forEach(({event: {data, method, section}}) => {273      if ((section === 'common') && (method === 'Transfer')) {274        const hData = (data as any).toJSON();275        transfer = {276          collectionId: hData[0],277          tokenId: hData[1],278          from: normalizeAddress(hData[2]),279          to: normalizeAddress(hData[3]),280          amount: BigInt(hData[4]),281        };282      }283    });284    let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;285    isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);286    isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);287    isSuccess = isSuccess && amount === transfer.amount;288    return isSuccess;289  }290291  static bigIntToDecimals(number: bigint, decimals = 18) {292    const numberStr = number.toString();293    const dotPos = numberStr.length - decimals;294295    if (dotPos <= 0) {296      return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;297    } else {298      const intPart = numberStr.substring(0, dotPos);299      const fractPart = numberStr.substring(dotPos);300      return intPart + '.' + fractPart;301    }302  }303}304305class UniqueEventHelper {306  private static extractIndex(index: any): [number, number] | string {307    if(index.toRawType() === '[u8;2]') return [index[0], index[1]];308    return index.toJSON();309  }310311  private static extractSub(data: any, subTypes: any): {[key: string]: any} {312    let obj: any = {};313    let index = 0;314315    if (data.entries) {316      for(const [key, value] of data.entries()) {317        obj[key] = this.extractData(value, subTypes[index]);318        index++;319      }320    } else obj = data.toJSON();321322    return obj;323  }324325  private static toHuman(data: any) {326    return data && data.toHuman ? data.toHuman() : `${data}`;327  }328329  private static extractData(data: any, type: any): any {330    if(!type) return this.toHuman(data);331    if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();332    if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();333    if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);334    return this.toHuman(data);335  }336337  public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {338    const parsedEvents: IEvent[] = [];339340    events.forEach((record) => {341      const {event, phase} = record;342      const types = event.typeDef;343344      const eventData: IEvent = {345        section: event.section.toString(),346        method: event.method.toString(),347        index: this.extractIndex(event.index),348        data: [],349        phase: phase.toJSON(),350      };351352      event.data.forEach((val: any, index: number) => {353        eventData.data.push(this.extractData(val, types[index]));354      });355356      parsedEvents.push(eventData);357    });358359    return parsedEvents;360  }361}362363export class ChainHelperBase {364  helperBase: any;365366  transactionStatus = UniqueUtil.transactionStatus;367  chainLogType = UniqueUtil.chainLogType;368  util: typeof UniqueUtil;369  eventHelper: typeof UniqueEventHelper;370  logger: ILogger;371  api: ApiPromise | null;372  forcedNetwork: TNetworks | null;373  network: TNetworks | null;374  chainLog: IUniqueHelperLog[];375  children: ChainHelperBase[];376  address: AddressGroup;377  chain: ChainGroup;378379  constructor(logger?: ILogger, helperBase?: any) {380    this.helperBase = helperBase;381382    this.util = UniqueUtil;383    this.eventHelper = UniqueEventHelper;384    if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();385    this.logger = logger;386    this.api = null;387    this.forcedNetwork = null;388    this.network = null;389    this.chainLog = [];390    this.children = [];391    this.address = new AddressGroup(this);392    this.chain = new ChainGroup(this);393  }394395  clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {396    Object.setPrototypeOf(helperCls.prototype, this);397    const newHelper = new helperCls(this.logger, options);398399    newHelper.api = this.api;400    newHelper.network = this.network;401    newHelper.forceNetwork = this.forceNetwork;402403    this.children.push(newHelper);404405    return newHelper;406  }407408  getApi(): ApiPromise {409    if(this.api === null) throw Error('API not initialized');410    return this.api;411  }412413  async subscribeEvents(expectedEvents: {section: string, names: string[]}[]) {414    const collectedEvents: IEvent[] = [];415    const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {416      const ievents = this.eventHelper.extractEvents(events);417      ievents.forEach((event) => {418        expectedEvents.forEach((e => {419          if (event.section === e.section && e.names.includes(event.method)) {420            collectedEvents.push(event);421          }422        }));423      });424    });425    return {unsubscribe: unsubscribe as any, collectedEvents};426  }427428  clearChainLog(): void {429    this.chainLog = [];430  }431432  forceNetwork(value: TNetworks): void {433    this.forcedNetwork = value;434  }435436  async connect(wsEndpoint: string, listeners?: IApiListeners) {437    if (this.api !== null) throw Error('Already connected');438    const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);439    this.api = api;440    this.network = network;441  }442443  async disconnect() {444    for (const child of this.children) {445      child.clearApi();446    }447448    if (this.api === null) return;449    await this.api.disconnect();450    this.clearApi();451  }452453  clearApi() {454    this.api = null;455    this.network = null;456  }457458  static async detectNetwork(api: ApiPromise): Promise<TNetworks> {459    const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;460    const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];461462    if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;463464    if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;465    return 'opal';466  }467468  static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {469    const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});470    await api.isReady;471472    const network = await this.detectNetwork(api);473474    await api.disconnect();475476    return network;477  }478479  static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{480    api: ApiPromise;481    network: TNetworks;482  }> {483    if(typeof network === 'undefined' || network === null) network = 'opal';484    const supportedRPC = {485      opal: {486        unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,487      },488      quartz: {489        unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,490      },491      unique: {492        unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,493      },494      rococo: {},495      westend: {},496      moonbeam: {},497      moonriver: {},498      acala: {},499      karura: {},500      westmint: {},501    };502    if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);503    const rpc = supportedRPC[network];504505    // TODO: investigate how to replace rpc in runtime506    // api._rpcCore.addUserInterfaces(rpc);507508    const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});509510    await api.isReadyOrError;511512    if (typeof listeners === 'undefined') listeners = {};513    for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {514      if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;515      api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);516    }517518    return {api, network};519  }520521  getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {522    const {events, status} = data;523    if (status.isReady) {524      return this.transactionStatus.NOT_READY;525    }526    if (status.isBroadcast) {527      return this.transactionStatus.NOT_READY;528    }529    if (status.isInBlock || status.isFinalized) {530      const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');531      if (errors.length > 0) {532        return this.transactionStatus.FAIL;533      }534      if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {535        return this.transactionStatus.SUCCESS;536      }537    }538539    return this.transactionStatus.FAIL;540  }541542  signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {543    const sign = (callback: any) => {544      if(options !== null) return transaction.signAndSend(sender, options, callback);545      return transaction.signAndSend(sender, callback);546    };547    // eslint-disable-next-line no-async-promise-executor548    return new Promise(async (resolve, reject) => {549      try {550        const unsub = await sign((result: any) => {551          const status = this.getTransactionStatus(result);552553          if (status === this.transactionStatus.SUCCESS) {554            this.logger.log(`${label} successful`);555            unsub();556            resolve({result, status});557          } else if (status === this.transactionStatus.FAIL) {558            let moduleError = null;559560            if (result.hasOwnProperty('dispatchError')) {561              const dispatchError = result['dispatchError'];562563              if (dispatchError) {564                if (dispatchError.isModule) {565                  const modErr = dispatchError.asModule;566                  const errorMeta = dispatchError.registry.findMetaError(modErr);567568                  moduleError = `${errorMeta.section}.${errorMeta.name}`;569                } else {570                  moduleError = dispatchError.toHuman();571                }572              } else {573                this.logger.log(result, this.logger.level.ERROR);574              }575            }576577            this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);578            unsub();579            reject({status, moduleError, result});580          }581        });582      } catch (e) {583        this.logger.log(e, this.logger.level.ERROR);584        reject(e);585      }586    });587  }588589  async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {590    const api = this.getApi();591    const signingInfo = await api.derive.tx.signingInfo(signer.address);592593    // We need to sign the tx because594    // unsigned transactions does not have an inclusion fee595    tx.sign(signer, {596      blockHash: api.genesisHash,597      genesisHash: api.genesisHash,598      runtimeVersion: api.runtimeVersion,599      nonce: signingInfo.nonce,600    });601602    if (len === null) {603      return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;604    } else {605      return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;606    }607  }608609  constructApiCall(apiCall: string, params: any[]) {610    if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);611    let call = this.getApi() as any;612    for(const part of apiCall.slice(4).split('.')) {613      call = call[part];614    }615    return call(...params);616  }617618  async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {619    if(this.api === null) throw Error('API not initialized');620    if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);621622    const startTime = (new Date()).getTime();623    let result: ITransactionResult;624    let events: IEvent[] = [];625    try {626      result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;627      events = this.eventHelper.extractEvents(result.result.events);628    }629    catch(e) {630      if(!(e as object).hasOwnProperty('status')) throw e;631      result = e as ITransactionResult;632    }633634    const endTime = (new Date()).getTime();635636    const log = {637      executedAt: endTime,638      executionTime: endTime - startTime,639      type: this.chainLogType.EXTRINSIC,640      status: result.status,641      call: extrinsic,642      signer: this.getSignerAddress(sender),643      params,644    } as IUniqueHelperLog;645646    if(result.status !== this.transactionStatus.SUCCESS) {647      if (result.moduleError) log.moduleError = result.moduleError;648      else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;649    }650    if(events.length > 0) log.events = events;651652    this.chainLog.push(log);653654    if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {655      if (result.moduleError) throw Error(`${result.moduleError}`);656      else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));657    }658    return result;659  }660661  async callRpc(rpc: string, params?: any[]) {662    if(typeof params === 'undefined') params = [];663    if(this.api === null) throw Error('API not initialized');664    if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);665666    const startTime = (new Date()).getTime();667    let result;668    let error = null;669    const log = {670      type: this.chainLogType.RPC,671      call: rpc,672      params,673    } as IUniqueHelperLog;674675    try {676      result = await this.constructApiCall(rpc, params);677    }678    catch(e) {679      error = e;680    }681682    const endTime = (new Date()).getTime();683684    log.executedAt = endTime;685    log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';686    log.executionTime = endTime - startTime;687688    this.chainLog.push(log);689690    if(error !== null) throw error;691692    return result;693  }694695  getSignerAddress(signer: IKeyringPair | string): string {696    if(typeof signer === 'string') return signer;697    return signer.address;698  }699700  fetchAllPalletNames(): string[] {701    if(this.api === null) throw Error('API not initialized');702    return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());703  }704705  fetchMissingPalletNames(requiredPallets: string[]): string[] {706    const palletNames = this.fetchAllPalletNames();707    return requiredPallets.filter(p => !palletNames.includes(p));708  }709}710711712class HelperGroup<T extends ChainHelperBase> {713  helper: T;714715  constructor(uniqueHelper: T) {716    this.helper = uniqueHelper;717  }718}719720721class CollectionGroup extends HelperGroup<UniqueHelper> {722  /**723 * Get number of blocks when sponsored transaction is available.724 *725 * @param collectionId ID of collection726 * @param tokenId ID of token727 * @param addressObj address for which the sponsorship is checked728 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});729 * @returns number of blocks or null if sponsorship hasn't been set730 */731  async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {732    return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();733  }734735  /**736   * Get the number of created collections.737   *738   * @returns number of created collections739   */740  async getTotalCount(): Promise<number> {741    return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();742  }743744  /**745   * Get information about the collection with additional data,746   * including the number of tokens it contains, its administrators,747   * the normalized address of the collection's owner, and decoded name and description.748   *749   * @param collectionId ID of collection750   * @example await getData(2)751   * @returns collection information object752   */753  async getData(collectionId: number): Promise<{754    id: number;755    name: string;756    description: string;757    tokensCount: number;758    admins: CrossAccountId[];759    normalizedOwner: TSubstrateAccount;760    raw: any761  } | null> {762    const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);763    const humanCollection = collection.toHuman(), collectionData = {764      id: collectionId, name: null, description: null, tokensCount: 0, admins: [],765      raw: humanCollection,766    } as any, jsonCollection = collection.toJSON();767    if (humanCollection === null) return null;768    collectionData.raw.limits = jsonCollection.limits;769    collectionData.raw.permissions = jsonCollection.permissions;770    collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);771    for (const key of ['name', 'description']) {772      collectionData[key] = this.helper.util.vec2str(humanCollection[key]);773    }774775    collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))776      ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)777      : 0;778    collectionData.admins = await this.getAdmins(collectionId);779780    return collectionData;781  }782783  /**784   * Get the addresses of the collection's administrators, optionally normalized.785   *786   * @param collectionId ID of collection787   * @param normalize whether to normalize the addresses to the default ss58 format788   * @example await getAdmins(1)789   * @returns array of administrators790   */791  async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {792    const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();793794    return normalize795      ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())796      : admins;797  }798799  /**800   * Get the addresses added to the collection allow-list, optionally normalized.801   * @param collectionId ID of collection802   * @param normalize whether to normalize the addresses to the default ss58 format803   * @example await getAllowList(1)804   * @returns array of allow-listed addresses805   */806  async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {807    const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();808    return normalize809      ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())810      : allowListed;811  }812813  /**814   * Get the effective limits of the collection instead of null for default values815   *816   * @param collectionId ID of collection817   * @example await getEffectiveLimits(2)818   * @returns object of collection limits819   */820  async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {821    return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();822  }823824  /**825   * Burns the collection if the signer has sufficient permissions and collection is empty.826   *827   * @param signer keyring of signer828   * @param collectionId ID of collection829   * @example await helper.collection.burn(aliceKeyring, 3);830   * @returns ```true``` if extrinsic success, otherwise ```false```831   */832  async burn(signer: TSigner, collectionId: number): Promise<boolean> {833    const result = await this.helper.executeExtrinsic(834      signer,835      'api.tx.unique.destroyCollection', [collectionId],836      true,837    );838839    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');840  }841842  /**843   * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.844   *845   * @param signer keyring of signer846   * @param collectionId ID of collection847   * @param sponsorAddress Sponsor substrate address848   * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")849   * @returns ```true``` if extrinsic success, otherwise ```false```850   */851  async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {852    const result = await this.helper.executeExtrinsic(853      signer,854      'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],855      true,856    );857858    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');859  }860861  /**862   * Confirms consent to sponsor the collection on behalf of the signer.863   *864   * @param signer keyring of signer865   * @param collectionId ID of collection866   * @example confirmSponsorship(aliceKeyring, 10)867   * @returns ```true``` if extrinsic success, otherwise ```false```868   */869  async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {870    const result = await this.helper.executeExtrinsic(871      signer,872      'api.tx.unique.confirmSponsorship', [collectionId],873      true,874    );875876    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');877  }878879  /**880   * Removes the sponsor of a collection, regardless if it consented or not.881   *882   * @param signer keyring of signer883   * @param collectionId ID of collection884   * @example removeSponsor(aliceKeyring, 10)885   * @returns ```true``` if extrinsic success, otherwise ```false```886   */887  async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {888    const result = await this.helper.executeExtrinsic(889      signer,890      'api.tx.unique.removeCollectionSponsor', [collectionId],891      true,892    );893894    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');895  }896897  /**898   * Sets the limits of the collection. At least one limit must be specified for a correct call.899   *900   * @param signer keyring of signer901   * @param collectionId ID of collection902   * @param limits collection limits object903   * @example904   * await setLimits(905   *   aliceKeyring,906   *   10,907   *   {908   *     sponsorTransferTimeout: 0,909   *     ownerCanDestroy: false910   *   }911   * )912   * @returns ```true``` if extrinsic success, otherwise ```false```913   */914  async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {915    const result = await this.helper.executeExtrinsic(916      signer,917      'api.tx.unique.setCollectionLimits', [collectionId, limits],918      true,919    );920921    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');922  }923924  /**925   * Changes the owner of the collection to the new Substrate address.926   *927   * @param signer keyring of signer928   * @param collectionId ID of collection929   * @param ownerAddress substrate address of new owner930   * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")931   * @returns ```true``` if extrinsic success, otherwise ```false```932   */933  async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {934    const result = await this.helper.executeExtrinsic(935      signer,936      'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],937      true,938    );939940    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');941  }942943  /**944   * Adds a collection administrator.945   *946   * @param signer keyring of signer947   * @param collectionId ID of collection948   * @param adminAddressObj Administrator address (substrate or ethereum)949   * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})950   * @returns ```true``` if extrinsic success, otherwise ```false```951   */952  async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {953    const result = await this.helper.executeExtrinsic(954      signer,955      'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],956      true,957    );958959    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');960  }961962  /**963   * Removes a collection administrator.964   *965   * @param signer keyring of signer966   * @param collectionId ID of collection967   * @param adminAddressObj Administrator address (substrate or ethereum)968   * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})969   * @returns ```true``` if extrinsic success, otherwise ```false```970   */971  async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {972    const result = await this.helper.executeExtrinsic(973      signer,974      'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],975      true,976    );977978    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');979  }980981  /**982   * Check if user is in allow list.983   *984   * @param collectionId ID of collection985   * @param user Account to check986   * @example await getAdmins(1)987   * @returns is user in allow list988   */989  async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {990    return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();991  }992993  /**994   * Adds an address to allow list995   * @param signer keyring of signer996   * @param collectionId ID of collection997   * @param addressObj address to add to the allow list998   * @returns ```true``` if extrinsic success, otherwise ```false```999   */1000  async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1001    const result = await this.helper.executeExtrinsic(1002      signer,1003      'api.tx.unique.addToAllowList', [collectionId, addressObj],1004      true,1005    );10061007    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1008  }10091010  /**1011   * Removes an address from allow list1012   *1013   * @param signer keyring of signer1014   * @param collectionId ID of collection1015   * @param addressObj address to remove from the allow list1016   * @returns ```true``` if extrinsic success, otherwise ```false```1017   */1018  async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1019    const result = await this.helper.executeExtrinsic(1020      signer,1021      'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1022      true,1023    );10241025    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1026  }10271028  /**1029   * Sets onchain permissions for selected collection.1030   *1031   * @param signer keyring of signer1032   * @param collectionId ID of collection1033   * @param permissions collection permissions object1034   * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1035   * @returns ```true``` if extrinsic success, otherwise ```false```1036   */1037  async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1038    const result = await this.helper.executeExtrinsic(1039      signer,1040      'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1041      true,1042    );10431044    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1045  }10461047  /**1048   * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1049   *1050   * @param signer keyring of signer1051   * @param collectionId ID of collection1052   * @param permissions nesting permissions object1053   * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1054   * @returns ```true``` if extrinsic success, otherwise ```false```1055   */1056  async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1057    return await this.setPermissions(signer, collectionId, {nesting: permissions});1058  }10591060  /**1061   * Disables nesting for selected collection.1062   *1063   * @param signer keyring of signer1064   * @param collectionId ID of collection1065   * @example disableNesting(aliceKeyring, 10);1066   * @returns ```true``` if extrinsic success, otherwise ```false```1067   */1068  async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1069    return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1070  }10711072  /**1073   * Sets onchain properties to the collection.1074   *1075   * @param signer keyring of signer1076   * @param collectionId ID of collection1077   * @param properties array of property objects1078   * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1079   * @returns ```true``` if extrinsic success, otherwise ```false```1080   */1081  async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1082    const result = await this.helper.executeExtrinsic(1083      signer,1084      'api.tx.unique.setCollectionProperties', [collectionId, properties],1085      true,1086    );10871088    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1089  }10901091  /**1092   * Get collection properties.1093   *1094   * @param collectionId ID of collection1095   * @param propertyKeys optionally filter the returned properties to only these keys1096   * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1097   * @returns array of key-value pairs1098   */1099  async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1100    return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1101  }11021103  async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1104    const api = this.helper.getApi();1105    const props = (await api.query.common.collectionProperties(collectionId)).toJSON();11061107    return (props! as any).consumedSpace;1108  }11091110  async getCollectionOptions(collectionId: number) {1111    return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1112  }11131114  /**1115   * Deletes onchain properties from the collection.1116   *1117   * @param signer keyring of signer1118   * @param collectionId ID of collection1119   * @param propertyKeys array of property keys to delete1120   * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1121   * @returns ```true``` if extrinsic success, otherwise ```false```1122   */1123  async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1124    const result = await this.helper.executeExtrinsic(1125      signer,1126      'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1127      true,1128    );11291130    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1131  }11321133  /**1134   * Changes the owner of the token.1135   *1136   * @param signer keyring of signer1137   * @param collectionId ID of collection1138   * @param tokenId ID of token1139   * @param addressObj address of a new owner1140   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1141   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1142   * @returns true if the token success, otherwise false1143   */1144  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1145    const result = await this.helper.executeExtrinsic(1146      signer,1147      'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1148      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1149    );11501151    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1152  }11531154  /**1155   *1156   * Change ownership of a token(s) on behalf of the owner.1157   *1158   * @param signer keyring of signer1159   * @param collectionId ID of collection1160   * @param tokenId ID of token1161   * @param fromAddressObj address on behalf of which the token will be sent1162   * @param toAddressObj new token owner1163   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1164   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1165   * @returns true if the token success, otherwise false1166   */1167  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1168    const result = await this.helper.executeExtrinsic(1169      signer,1170      'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1171      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1172    );1173    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1174  }11751176  /**1177   *1178   * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1179   *1180   * @param signer keyring of signer1181   * @param collectionId ID of collection1182   * @param tokenId ID of token1183   * @param amount amount of tokens to be burned. For NFT must be set to 1n1184   * @example burnToken(aliceKeyring, 10, 5);1185   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1186   */1187  async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1188    const burnResult = await this.helper.executeExtrinsic(1189      signer,1190      'api.tx.unique.burnItem', [collectionId, tokenId, amount],1191      true, // `Unable to burn token for ${label}`,1192    );1193    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1194    if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1195    return burnedTokens.success;1196  }11971198  /**1199   * Destroys a concrete instance of NFT on behalf of the owner1200   *1201   * @param signer keyring of signer1202   * @param collectionId ID of collection1203   * @param tokenId ID of token1204   * @param fromAddressObj address on behalf of which the token will be burnt1205   * @param amount amount of tokens to be burned. For NFT must be set to 1n1206   * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1207   * @returns ```true``` if extrinsic success, otherwise ```false```1208   */1209  async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1210    const burnResult = await this.helper.executeExtrinsic(1211      signer,1212      'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1213      true, // `Unable to burn token from for ${label}`,1214    );1215    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1216    return burnedTokens.success && burnedTokens.tokens.length > 0;1217  }12181219  /**1220   * Set, change, or remove approved address to transfer the ownership of the NFT.1221   *1222   * @param signer keyring of signer1223   * @param collectionId ID of collection1224   * @param tokenId ID of token1225   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1226   * @param amount amount of token to be approved. For NFT must be set to 1n1227   * @returns ```true``` if extrinsic success, otherwise ```false```1228   */1229  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1230    const approveResult = await this.helper.executeExtrinsic(1231      signer,1232      'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1233      true, // `Unable to approve token for ${label}`,1234    );12351236    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1237  }12381239  /**1240   * Get the amount of token pieces approved to transfer or burn. Normally 0.1241   *1242   * @param collectionId ID of collection1243   * @param tokenId ID of token1244   * @param toAccountObj address which is approved to use token pieces1245   * @param fromAccountObj address which may have allowed the use of its owned tokens1246   * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1247   * @returns number of approved to transfer pieces1248   */1249  async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1250    return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1251  }12521253  /**1254   * Get the last created token ID in a collection1255   *1256   * @param collectionId ID of collection1257   * @example getLastTokenId(10);1258   * @returns id of the last created token1259   */1260  async getLastTokenId(collectionId: number): Promise<number> {1261    return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1262  }12631264  /**1265   * Check if token exists1266   *1267   * @param collectionId ID of collection1268   * @param tokenId ID of token1269   * @example doesTokenExist(10, 20);1270   * @returns true if the token exists, otherwise false1271   */1272  async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1273    return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1274  }1275}12761277class NFTnRFT extends CollectionGroup {1278  /**1279   * Get tokens owned by account1280   *1281   * @param collectionId ID of collection1282   * @param addressObj tokens owner1283   * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1284   * @returns array of token ids owned by account1285   */1286  async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1287    return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1288  }12891290  /**1291   * Get token data1292   *1293   * @param collectionId ID of collection1294   * @param tokenId ID of token1295   * @param propertyKeys optionally filter the token properties to only these keys1296   * @param blockHashAt optionally query the data at some block with this hash1297   * @example getToken(10, 5);1298   * @returns human readable token data1299   */1300  async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1301    properties: IProperty[];1302    owner: CrossAccountId;1303    normalizedOwner: CrossAccountId;1304  }| null> {1305    let tokenData;1306    if(typeof blockHashAt === 'undefined') {1307      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1308    }1309    else {1310      if(propertyKeys.length == 0) {1311        const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1312        if(!collection) return null;1313        propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1314      }1315      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1316    }1317    tokenData = tokenData.toHuman();1318    if (tokenData === null || tokenData.owner === null) return null;1319    const owner = {} as any;1320    for (const key of Object.keys(tokenData.owner)) {1321      owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1322        ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1323        : tokenData.owner[key];1324    }1325    tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1326    return tokenData;1327  }13281329  /**1330   * Set permissions to change token properties1331   *1332   * @param signer keyring of signer1333   * @param collectionId ID of collection1334   * @param permissions permissions to change a property by the collection admin or token owner1335   * @example setTokenPropertyPermissions(1336   *   aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1337   * )1338   * @returns true if extrinsic success otherwise false1339   */1340  async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1341    const result = await this.helper.executeExtrinsic(1342      signer,1343      'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1344      true,1345    );13461347    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1348  }13491350  /**1351   * Get token property permissions.1352   *1353   * @param collectionId ID of collection1354   * @param propertyKeys optionally filter the returned property permissions to only these keys1355   * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1356   * @returns array of key-permission pairs1357   */1358  async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1359    return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1360  }13611362  /**1363   * Set token properties1364   *1365   * @param signer keyring of signer1366   * @param collectionId ID of collection1367   * @param tokenId ID of token1368   * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1369   * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1370   * @returns ```true``` if extrinsic success, otherwise ```false```1371   */1372  async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1373    const result = await this.helper.executeExtrinsic(1374      signer,1375      'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1376      true,1377    );13781379    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1380  }13811382  /**1383   * Get properties, metadata assigned to a token.1384   *1385   * @param collectionId ID of collection1386   * @param tokenId ID of token1387   * @param propertyKeys optionally filter the returned properties to only these keys1388   * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1389   * @returns array of key-value pairs1390   */1391  async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1392    return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1393  }13941395  /**1396   * Delete the provided properties of a token1397   * @param signer keyring of signer1398   * @param collectionId ID of collection1399   * @param tokenId ID of token1400   * @param propertyKeys property keys to be deleted1401   * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1402   * @returns ```true``` if extrinsic success, otherwise ```false```1403   */1404  async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1405    const result = await this.helper.executeExtrinsic(1406      signer,1407      'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1408      true,1409    );14101411    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1412  }14131414  /**1415   * Mint new collection1416   *1417   * @param signer keyring of signer1418   * @param collectionOptions basic collection options and properties1419   * @param mode NFT or RFT type of a collection1420   * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1421   * @returns object of the created collection1422   */1423  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1424    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1425    collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1426    for (const key of ['name', 'description', 'tokenPrefix']) {1427      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);1428    }1429    const creationResult = await this.helper.executeExtrinsic(1430      signer,1431      'api.tx.unique.createCollectionEx', [collectionOptions],1432      true, // errorLabel,1433    );1434    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1435  }14361437  getCollectionObject(_collectionId: number): any {1438    return null;1439  }14401441  getTokenObject(_collectionId: number, _tokenId: number): any {1442    return null;1443  }14441445  /**1446   * Tells whether the given `owner` approves the `operator`.1447   * @param collectionId ID of collection1448   * @param owner owner address1449   * @param operator operator addrees1450   * @returns true if operator is enabled1451   */1452  async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1453    return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1454  }14551456  /** Sets or unsets the approval of a given operator.1457   *  The `operator` is allowed to transfer all tokens of the `caller` on their behalf.1458   *  @param operator Operator1459   *  @param approved Should operator status be granted or revoked?1460   *  @returns ```true``` if extrinsic success, otherwise ```false```1461   */1462  async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1463    const result = await this.helper.executeExtrinsic(1464      signer,1465      'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1466      true,1467    );1468    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1469  }1470}147114721473class NFTGroup extends NFTnRFT {1474  /**1475   * Get collection object1476   * @param collectionId ID of collection1477   * @example getCollectionObject(2);1478   * @returns instance of UniqueNFTCollection1479   */1480  getCollectionObject(collectionId: number): UniqueNFTCollection {1481    return new UniqueNFTCollection(collectionId, this.helper);1482  }14831484  /**1485   * Get token object1486   * @param collectionId ID of collection1487   * @param tokenId ID of token1488   * @example getTokenObject(10, 5);1489   * @returns instance of UniqueNFTToken1490   */1491  getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1492    return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1493  }14941495  /**1496   * Get token's owner1497   * @param collectionId ID of collection1498   * @param tokenId ID of token1499   * @param blockHashAt optionally query the data at the block with this hash1500   * @example getTokenOwner(10, 5);1501   * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1502   */1503  async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1504    let owner;1505    if (typeof blockHashAt === 'undefined') {1506      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1507    } else {1508      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1509    }1510    return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1511  }15121513  /**1514   * Is token approved to transfer1515   * @param collectionId ID of collection1516   * @param tokenId ID of token1517   * @param toAccountObj address to be approved1518   * @returns ```true``` if extrinsic success, otherwise ```false```1519   */1520  async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1521    return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1522  }15231524  /**1525   * Changes the owner of the token.1526   *1527   * @param signer keyring of signer1528   * @param collectionId ID of collection1529   * @param tokenId ID of token1530   * @param addressObj address of a new owner1531   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1532   * @returns ```true``` if extrinsic success, otherwise ```false```1533   */1534  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1535    return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1536  }15371538  /**1539   *1540   * Change ownership of a NFT on behalf of the owner.1541   *1542   * @param signer keyring of signer1543   * @param collectionId ID of collection1544   * @param tokenId ID of token1545   * @param fromAddressObj address on behalf of which the token will be sent1546   * @param toAddressObj new token owner1547   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1548   * @returns ```true``` if extrinsic success, otherwise ```false```1549   */1550  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1551    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1552  }15531554  /**1555   * Recursively find the address that owns the token1556   * @param collectionId ID of collection1557   * @param tokenId ID of token1558   * @param blockHashAt1559   * @example getTokenTopmostOwner(10, 5);1560   * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1561   */1562  async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1563    let owner;1564    if (typeof blockHashAt === 'undefined') {1565      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1566    } else {1567      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1568    }15691570    if (owner === null) return null;15711572    return owner.toHuman();1573  }15741575  /**1576   * Get tokens nested in the provided token1577   * @param collectionId ID of collection1578   * @param tokenId ID of token1579   * @param blockHashAt optionally query the data at the block with this hash1580   * @example getTokenChildren(10, 5);1581   * @returns tokens whose depth of nesting is <= 51582   */1583  async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1584    let children;1585    if(typeof blockHashAt === 'undefined') {1586      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1587    } else {1588      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1589    }15901591    return children.toJSON().map((x: any) => {1592      return {collectionId: x.collection, tokenId: x.token};1593    });1594  }15951596  /**1597   * Nest one token into another1598   * @param signer keyring of signer1599   * @param tokenObj token to be nested1600   * @param rootTokenObj token to be parent1601   * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1602   * @returns ```true``` if extrinsic success, otherwise ```false```1603   */1604  async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1605    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1606    const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1607    if(!result) {1608      throw Error('Unable to nest token!');1609    }1610    return result;1611  }16121613  /**1614   * Remove token from nested state1615   * @param signer keyring of signer1616   * @param tokenObj token to unnest1617   * @param rootTokenObj parent of a token1618   * @param toAddressObj address of a new token owner1619   * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1620   * @returns ```true``` if extrinsic success, otherwise ```false```1621   */1622  async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1623    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1624    const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1625    if(!result) {1626      throw Error('Unable to unnest token!');1627    }1628    return result;1629  }16301631  /**1632   * Mint new collection1633   * @param signer keyring of signer1634   * @param collectionOptions Collection options1635   * @example1636   * mintCollection(aliceKeyring, {1637   *   name: 'New',1638   *   description: 'New collection',1639   *   tokenPrefix: 'NEW',1640   * })1641   * @returns object of the created collection1642   */1643  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1644    return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1645  }16461647  /**1648   * Mint new token1649   * @param signer keyring of signer1650   * @param data token data1651   * @returns created token object1652   */1653  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1654    const creationResult = await this.helper.executeExtrinsic(1655      signer,1656      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1657        nft: {1658          properties: data.properties,1659        },1660      }],1661      true,1662    );1663    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1664    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1665    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1666    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1667  }16681669  /**1670   * Mint multiple NFT tokens1671   * @param signer keyring of signer1672   * @param collectionId ID of collection1673   * @param tokens array of tokens with owner and properties1674   * @example1675   * mintMultipleTokens(aliceKeyring, 10, [{1676   *     owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1677   *     properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1678   *   },{1679   *     owner: {Ethereum: "0x9F0583DbB855d..."},1680   *     properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1681   * }]);1682   * @returns ```true``` if extrinsic success, otherwise ```false```1683   */1684  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1685    const creationResult = await this.helper.executeExtrinsic(1686      signer,1687      'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1688      true,1689    );1690    const collection = this.getCollectionObject(collectionId);1691    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1692  }16931694  /**1695   * Mint multiple NFT tokens with one owner1696   * @param signer keyring of signer1697   * @param collectionId ID of collection1698   * @param owner tokens owner1699   * @param tokens array of tokens with owner and properties1700   * @example1701   * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1702   *   properties: [{1703   *   key: "gender",1704   *   value: "female",1705   *  },{1706   *   key: "age",1707   *   value: "33",1708   *  }],1709   * }]);1710   * @returns array of newly created tokens1711   */1712  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1713    const rawTokens = [];1714    for (const token of tokens) {1715      const raw = {NFT: {properties: token.properties}};1716      rawTokens.push(raw);1717    }1718    const creationResult = await this.helper.executeExtrinsic(1719      signer,1720      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1721      true,1722    );1723    const collection = this.getCollectionObject(collectionId);1724    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1725  }17261727  /**1728   * Set, change, or remove approved address to transfer the ownership of the NFT.1729   *1730   * @param signer keyring of signer1731   * @param collectionId ID of collection1732   * @param tokenId ID of token1733   * @param toAddressObj address to approve1734   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1735   * @returns ```true``` if extrinsic success, otherwise ```false```1736   */1737  approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1738    return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1739  }1740}174117421743class RFTGroup extends NFTnRFT {1744  /**1745   * Get collection object1746   * @param collectionId ID of collection1747   * @example getCollectionObject(2);1748   * @returns instance of UniqueRFTCollection1749   */1750  getCollectionObject(collectionId: number): UniqueRFTCollection {1751    return new UniqueRFTCollection(collectionId, this.helper);1752  }17531754  /**1755   * Get token object1756   * @param collectionId ID of collection1757   * @param tokenId ID of token1758   * @example getTokenObject(10, 5);1759   * @returns instance of UniqueNFTToken1760   */1761  getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1762    return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1763  }17641765  /**1766   * Get top 10 token owners with the largest number of pieces1767   * @param collectionId ID of collection1768   * @param tokenId ID of token1769   * @example getTokenTop10Owners(10, 5);1770   * @returns array of top 10 owners1771   */1772  async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1773    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1774  }17751776  /**1777   * Get number of pieces owned by address1778   * @param collectionId ID of collection1779   * @param tokenId ID of token1780   * @param addressObj address token owner1781   * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1782   * @returns number of pieces ownerd by address1783   */1784  async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1785    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1786  }17871788  /**1789   * Transfer pieces of token to another address1790   * @param signer keyring of signer1791   * @param collectionId ID of collection1792   * @param tokenId ID of token1793   * @param addressObj address of a new owner1794   * @param amount number of pieces to be transfered1795   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1796   * @returns ```true``` if extrinsic success, otherwise ```false```1797   */1798  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1799    return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1800  }18011802  /**1803   * Change ownership of some pieces of RFT on behalf of the owner.1804   * @param signer keyring of signer1805   * @param collectionId ID of collection1806   * @param tokenId ID of token1807   * @param fromAddressObj address on behalf of which the token will be sent1808   * @param toAddressObj new token owner1809   * @param amount number of pieces to be transfered1810   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1811   * @returns ```true``` if extrinsic success, otherwise ```false```1812   */1813  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1814    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1815  }18161817  /**1818   * Mint new collection1819   * @param signer keyring of signer1820   * @param collectionOptions Collection options1821   * @example1822   * mintCollection(aliceKeyring, {1823   *   name: 'New',1824   *   description: 'New collection',1825   *   tokenPrefix: 'NEW',1826   * })1827   * @returns object of the created collection1828   */1829  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1830    return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1831  }18321833  /**1834   * Mint new token1835   * @param signer keyring of signer1836   * @param data token data1837   * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1838   * @returns created token object1839   */1840  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1841    const creationResult = await this.helper.executeExtrinsic(1842      signer,1843      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1844        refungible: {1845          pieces: data.pieces,1846          properties: data.properties,1847        },1848      }],1849      true,1850    );1851    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1852    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1853    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1854    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1855  }18561857  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1858    throw Error('Not implemented');1859    const creationResult = await this.helper.executeExtrinsic(1860      signer,1861      'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1862      true, // `Unable to mint RFT tokens for ${label}`,1863    );1864    const collection = this.getCollectionObject(collectionId);1865    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1866  }18671868  /**1869   * Mint multiple RFT tokens with one owner1870   * @param signer keyring of signer1871   * @param collectionId ID of collection1872   * @param owner tokens owner1873   * @param tokens array of tokens with properties and pieces1874   * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1875   * @returns array of newly created RFT tokens1876   */1877  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1878    const rawTokens = [];1879    for (const token of tokens) {1880      const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1881      rawTokens.push(raw);1882    }1883    const creationResult = await this.helper.executeExtrinsic(1884      signer,1885      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1886      true,1887    );1888    const collection = this.getCollectionObject(collectionId);1889    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1890  }18911892  /**1893   * Destroys a concrete instance of RFT.1894   * @param signer keyring of signer1895   * @param collectionId ID of collection1896   * @param tokenId ID of token1897   * @param amount number of pieces to be burnt1898   * @example burnToken(aliceKeyring, 10, 5);1899   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1900   */1901  async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1902    return await super.burnToken(signer, collectionId, tokenId, amount);1903  }19041905  /**1906   * Destroys a concrete instance of RFT on behalf of the owner.1907   * @param signer keyring of signer1908   * @param collectionId ID of collection1909   * @param tokenId ID of token1910   * @param fromAddressObj address on behalf of which the token will be burnt1911   * @param amount number of pieces to be burnt1912   * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1913   * @returns ```true``` if extrinsic success, otherwise ```false```1914   */1915  async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1916    return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1917  }19181919  /**1920   * Set, change, or remove approved address to transfer the ownership of the RFT.1921   *1922   * @param signer keyring of signer1923   * @param collectionId ID of collection1924   * @param tokenId ID of token1925   * @param toAddressObj address to approve1926   * @param amount number of pieces to be approved1927   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1928   * @returns true if the token success, otherwise false1929   */1930  approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1931    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1932  }19331934  /**1935   * Get total number of pieces1936   * @param collectionId ID of collection1937   * @param tokenId ID of token1938   * @example getTokenTotalPieces(10, 5);1939   * @returns number of pieces1940   */1941  async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1942    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1943  }19441945  /**1946   * Change number of token pieces. Signer must be the owner of all token pieces.1947   * @param signer keyring of signer1948   * @param collectionId ID of collection1949   * @param tokenId ID of token1950   * @param amount new number of pieces1951   * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1952   * @returns true if the repartion was success, otherwise false1953   */1954  async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1955    const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1956    const repartitionResult = await this.helper.executeExtrinsic(1957      signer,1958      'api.tx.unique.repartition', [collectionId, tokenId, amount],1959      true,1960    );1961    if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1962    return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1963  }1964}196519661967class FTGroup extends CollectionGroup {1968  /**1969   * Get collection object1970   * @param collectionId ID of collection1971   * @example getCollectionObject(2);1972   * @returns instance of UniqueFTCollection1973   */1974  getCollectionObject(collectionId: number): UniqueFTCollection {1975    return new UniqueFTCollection(collectionId, this.helper);1976  }19771978  /**1979   * Mint new fungible collection1980   * @param signer keyring of signer1981   * @param collectionOptions Collection options1982   * @param decimalPoints number of token decimals1983   * @example1984   * mintCollection(aliceKeyring, {1985   *   name: 'New',1986   *   description: 'New collection',1987   *   tokenPrefix: 'NEW',1988   * }, 18)1989   * @returns newly created fungible collection1990   */1991  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1992    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1993    if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1994    collectionOptions.mode = {fungible: decimalPoints};1995    for (const key of ['name', 'description', 'tokenPrefix']) {1996      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);1997    }1998    const creationResult = await this.helper.executeExtrinsic(1999      signer,2000      'api.tx.unique.createCollectionEx', [collectionOptions],2001      true,2002    );2003    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2004  }20052006  /**2007   * Mint tokens2008   * @param signer keyring of signer2009   * @param collectionId ID of collection2010   * @param owner address owner of new tokens2011   * @param amount amount of tokens to be meanted2012   * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);2013   * @returns ```true``` if extrinsic success, otherwise ```false```2014   */2015  async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2016    const creationResult = await this.helper.executeExtrinsic(2017      signer,2018      'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2019        fungible: {2020          value: amount,2021        },2022      }],2023      true, // `Unable to mint fungible tokens for ${label}`,2024    );2025    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2026  }20272028  /**2029   * Mint multiple Fungible tokens with one owner2030   * @param signer keyring of signer2031   * @param collectionId ID of collection2032   * @param owner tokens owner2033   * @param tokens array of tokens with properties and pieces2034   * @returns ```true``` if extrinsic success, otherwise ```false```2035   */2036  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {2037    const rawTokens = [];2038    for (const token of tokens) {2039      const raw = {Fungible: {Value: token.value}};2040      rawTokens.push(raw);2041    }2042    const creationResult = await this.helper.executeExtrinsic(2043      signer,2044      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2045      true,2046    );2047    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2048  }20492050  /**2051   * Get the top 10 owners with the largest balance for the Fungible collection2052   * @param collectionId ID of collection2053   * @example getTop10Owners(10);2054   * @returns array of ```ICrossAccountId```2055   */2056  async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2057    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2058  }20592060  /**2061   * Get account balance2062   * @param collectionId ID of collection2063   * @param addressObj address of owner2064   * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2065   * @returns amount of fungible tokens owned by address2066   */2067  async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2068    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2069  }20702071  /**2072   * Transfer tokens to address2073   * @param signer keyring of signer2074   * @param collectionId ID of collection2075   * @param toAddressObj address recipient2076   * @param amount amount of tokens to be sent2077   * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2078   * @returns ```true``` if extrinsic success, otherwise ```false```2079   */2080  async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2081    return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2082  }20832084  /**2085   * Transfer some tokens on behalf of the owner.2086   * @param signer keyring of signer2087   * @param collectionId ID of collection2088   * @param fromAddressObj address on behalf of which tokens will be sent2089   * @param toAddressObj address where token to be sent2090   * @param amount number of tokens to be sent2091   * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2092   * @returns ```true``` if extrinsic success, otherwise ```false```2093   */2094  async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2095    return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2096  }20972098  /**2099   * Destroy some amount of tokens2100   * @param signer keyring of signer2101   * @param collectionId ID of collection2102   * @param amount amount of tokens to be destroyed2103   * @example burnTokens(aliceKeyring, 10, 1000n);2104   * @returns ```true``` if extrinsic success, otherwise ```false```2105   */2106  async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2107    return await super.burnToken(signer, collectionId, 0, amount);2108  }21092110  /**2111   * Burn some tokens on behalf of the owner.2112   * @param signer keyring of signer2113   * @param collectionId ID of collection2114   * @param fromAddressObj address on behalf of which tokens will be burnt2115   * @param amount amount of tokens to be burnt2116   * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2117   * @returns ```true``` if extrinsic success, otherwise ```false```2118   */2119  async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2120    return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2121  }21222123  /**2124   * Get total collection supply2125   * @param collectionId2126   * @returns2127   */2128  async getTotalPieces(collectionId: number): Promise<bigint> {2129    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2130  }21312132  /**2133   * Set, change, or remove approved address to transfer tokens.2134   *2135   * @param signer keyring of signer2136   * @param collectionId ID of collection2137   * @param toAddressObj address to be approved2138   * @param amount amount of tokens to be approved2139   * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2140   * @returns ```true``` if extrinsic success, otherwise ```false```2141   */2142  approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2143    return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2144  }21452146  /**2147   * Get amount of fungible tokens approved to transfer2148   * @param collectionId ID of collection2149   * @param fromAddressObj owner of tokens2150   * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2151   * @returns number of tokens approved for the transfer2152   */2153  getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2154    return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2155  }2156}215721582159class ChainGroup extends HelperGroup<ChainHelperBase> {2160  /**2161   * Get system properties of a chain2162   * @example getChainProperties();2163   * @returns ss58Format, token decimals, and token symbol2164   */2165  getChainProperties(): IChainProperties {2166    const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2167    return {2168      ss58Format: properties.ss58Format.toJSON(),2169      tokenDecimals: properties.tokenDecimals.toJSON(),2170      tokenSymbol: properties.tokenSymbol.toJSON(),2171    };2172  }21732174  /**2175   * Get chain header2176   * @example getLatestBlockNumber();2177   * @returns the number of the last block2178   */2179  async getLatestBlockNumber(): Promise<number> {2180    return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2181  }21822183  /**2184   * Get block hash by block number2185   * @param blockNumber number of block2186   * @example getBlockHashByNumber(12345);2187   * @returns hash of a block2188   */2189  async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2190    const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2191    if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2192    return blockHash;2193  }21942195  // TODO add docs2196  async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2197    const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2198    if (!blockHash) return null;2199    return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2200  }22012202  /**2203   * Get latest relay block2204   * @returns {number} relay block2205   */2206  async getRelayBlockNumber(): Promise<bigint> {2207    const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2208    return BigInt(blockNumber);2209  }22102211  /**2212   * Get account nonce2213   * @param address substrate address2214   * @example getNonce("5GrwvaEF5zXb26Fz...");2215   * @returns number, account's nonce2216   */2217  async getNonce(address: TSubstrateAccount): Promise<number> {2218    return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2219  }2220}22212222class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2223  /**2224 * Get substrate address balance2225 * @param address substrate address2226 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2227 * @returns amount of tokens on address2228 */2229  async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2230    return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2231  }22322233  /**2234   * Transfer tokens to substrate address2235   * @param signer keyring of signer2236   * @param address substrate address of a recipient2237   * @param amount amount of tokens to be transfered2238   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2239   * @returns ```true``` if extrinsic success, otherwise ```false```2240   */2241  async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2242    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}`*/);22432244    let transfer = {from: null, to: null, amount: 0n} as any;2245    result.result.events.forEach(({event: {data, method, section}}) => {2246      if ((section === 'balances') && (method === 'Transfer')) {2247        transfer = {2248          from: this.helper.address.normalizeSubstrate(data[0]),2249          to: this.helper.address.normalizeSubstrate(data[1]),2250          amount: BigInt(data[2]),2251        };2252      }2253    });2254    const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2255      && this.helper.address.normalizeSubstrate(address) === transfer.to2256      && BigInt(amount) === transfer.amount;2257    return isSuccess;2258  }22592260  /**2261   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2262   * @param address substrate address2263   * @returns2264   */2265  async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2266    const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2267    return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2268  }22692270  async getLocked(address: TSubstrateAccount): Promise<[{id: string, amount: bigint, reason: string}]> {2271    const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2272    return locks.map((lock: any) => {return {id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons};});2273  }2274}22752276class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2277  /**2278   * Get ethereum address balance2279   * @param address ethereum address2280   * @example getEthereum("0x9F0583DbB855d...")2281   * @returns amount of tokens on address2282   */2283  async getEthereum(address: TEthereumAccount): Promise<bigint> {2284    return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2285  }22862287  /**2288   * Transfer tokens to address2289   * @param signer keyring of signer2290   * @param address Ethereum address of a recipient2291   * @param amount amount of tokens to be transfered2292   * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2293   * @returns ```true``` if extrinsic success, otherwise ```false```2294   */2295  async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2296    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);22972298    let transfer = {from: null, to: null, amount: 0n} as any;2299    result.result.events.forEach(({event: {data, method, section}}) => {2300      if ((section === 'balances') && (method === 'Transfer')) {2301        transfer = {2302          from: data[0].toString(),2303          to: data[1].toString(),2304          amount: BigInt(data[2]),2305        };2306      }2307    });2308    const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2309      && address === transfer.to2310      && BigInt(amount) === transfer.amount;2311    return isSuccess;2312  }2313}23142315class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2316  subBalanceGroup: SubstrateBalanceGroup<T>;2317  ethBalanceGroup: EthereumBalanceGroup<T>;23182319  constructor(helper: T) {2320    super(helper);2321    this.subBalanceGroup = new SubstrateBalanceGroup(helper);2322    this.ethBalanceGroup = new EthereumBalanceGroup(helper);2323  }23242325  getCollectionCreationPrice(): bigint {2326    return 2n * this.getOneTokenNominal();2327  }2328  /**2329   * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2330   * @example getOneTokenNominal()2331   * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2332   */2333  getOneTokenNominal(): bigint {2334    const chainProperties = this.helper.chain.getChainProperties();2335    return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2336  }23372338  /**2339   * Get substrate address balance2340   * @param address substrate address2341   * @example getSubstrate("5GrwvaEF5zXb26Fz...")2342   * @returns amount of tokens on address2343   */2344  getSubstrate(address: TSubstrateAccount): Promise<bigint> {2345    return this.subBalanceGroup.getSubstrate(address);2346  }23472348  /**2349   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2350   * @param address substrate address2351   * @returns2352   */2353  getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2354    return this.subBalanceGroup.getSubstrateFull(address);2355  }23562357  /**2358   * Get locked balances2359   * @param address substrate address2360   * @returns locked balances with reason via api.query.balances.locks2361   */2362  getLocked(address: TSubstrateAccount) {2363    return this.subBalanceGroup.getLocked(address);2364  }23652366  /**2367   * Get ethereum address balance2368   * @param address ethereum address2369   * @example getEthereum("0x9F0583DbB855d...")2370   * @returns amount of tokens on address2371   */2372  getEthereum(address: TEthereumAccount): Promise<bigint> {2373    return this.ethBalanceGroup.getEthereum(address);2374  }23752376  /**2377   * Transfer tokens to substrate address2378   * @param signer keyring of signer2379   * @param address substrate address of a recipient2380   * @param amount amount of tokens to be transfered2381   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2382   * @returns ```true``` if extrinsic success, otherwise ```false```2383   */2384  transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2385    return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2386  }23872388  async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2389    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);23902391    let transfer = {from: null, to: null, amount: 0n} as any;2392    result.result.events.forEach(({event: {data, method, section}}) => {2393      if ((section === 'balances') && (method === 'Transfer')) {2394        transfer = {2395          from: this.helper.address.normalizeSubstrate(data[0]),2396          to: this.helper.address.normalizeSubstrate(data[1]),2397          amount: BigInt(data[2]),2398        };2399      }2400    });2401    let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2402    isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2403    isSuccess = isSuccess && BigInt(amount) === transfer.amount;2404    return isSuccess;2405  }24062407  /**2408   * Transfer tokens with the unlock period2409   * @param signer signers Keyring2410   * @param address Substrate address of recipient2411   * @param schedule Schedule params2412   * @example vestedTransfer(signer, recepient.address, 20000, 100, 10, 50 * nominal); // total amount of vested tokens will be 100 * 50 = 50002413   */2414  async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: {start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}): Promise<void> {2415    const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2416    const event = result.result.events2417      .find(e => e.event.section === 'vesting' &&2418            e.event.method === 'VestingScheduleAdded' &&2419            e.event.data[0].toHuman() === signer.address);2420    if (!event) throw Error('Cannot find transfer in events');2421  }24222423  /**2424   * Get schedule for recepient of vested transfer2425   * @param address Substrate address of recipient2426   * @returns2427   */2428  async getVestingSchedules(address: TSubstrateAccount): Promise<{start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}[]> {2429    const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2430    return schedule.map((schedule: any) => {2431      return {2432        start: BigInt(schedule.start),2433        period: BigInt(schedule.period),2434        periodCount: BigInt(schedule.periodCount),2435        perPeriod: BigInt(schedule.perPeriod),2436      };2437    });2438  }24392440  /**2441   * Claim vested tokens2442   * @param signer signers Keyring2443   */2444  async claim(signer: TSigner) {2445    const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2446    const event = result.result.events2447      .find(e => e.event.section === 'vesting' &&2448            e.event.method === 'Claimed' &&2449            e.event.data[0].toHuman() === signer.address);2450    if (!event) throw Error('Cannot find claim in events');2451  }2452}24532454class AddressGroup extends HelperGroup<ChainHelperBase> {2455  /**2456   * Normalizes the address to the specified ss58 format, by default ```42```.2457   * @param address substrate address2458   * @param ss58Format format for address conversion, by default ```42```2459   * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2460   * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2461   */2462  normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2463    return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2464  }24652466  /**2467   * Get address in the connected chain format2468   * @param address substrate address2469   * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2470   * @returns address in chain format2471   */2472  normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2473    return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2474  }24752476  /**2477   * Get substrate mirror of an ethereum address2478   * @param ethAddress ethereum address2479   * @param toChainFormat false for normalized account2480   * @example ethToSubstrate('0x9F0583DbB855d...')2481   * @returns substrate mirror of a provided ethereum address2482   */2483  ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2484    return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2485  }24862487  /**2488   * Get ethereum mirror of a substrate address2489   * @param subAddress substrate account2490   * @example substrateToEth("5DnSF6RRjwteE3BrC...")2491   * @returns ethereum mirror of a provided substrate address2492   */2493  substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2494    return CrossAccountId.translateSubToEth(subAddress);2495  }24962497  /**2498   * Encode key to substrate address2499   * @param key key for encoding address2500   * @param ss58Format prefix for encoding to the address of the corresponding network2501   * @returns encoded substrate address2502   */2503  encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2504    const u8a :Uint8Array = typeof key === 'string'2505      ? hexToU8a(key)2506      : typeof key === 'bigint'2507        ? hexToU8a(key.toString(16))2508        : key;25092510    if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2511      throw new Error(`ss58Format is not valid, received ${typeof ss58Format} "${ss58Format}"`);2512    }25132514    const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2515    if (!allowedDecodedLengths.includes(u8a.length)) {2516      throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2517    }25182519    const u8aPrefix = ss58Format < 642520      ? new Uint8Array([ss58Format])2521      : new Uint8Array([2522        ((ss58Format & 0xfc) >> 2) | 0x40,2523        (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2524      ]);25252526    const input = u8aConcat(u8aPrefix, u8a);25272528    return base58Encode(u8aConcat(2529      input,2530      blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2531    ));2532  }25332534  /**2535   * Restore substrate address from bigint representation2536   * @param number decimal representation of substrate address2537   * @returns substrate address2538   */2539  restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2540    if (this.helper.api === null) {2541      throw 'Not connected';2542    }2543    const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2544    if (res === undefined || res === null) {2545      throw 'Restore address error';2546    }2547    return res.toString();2548  }25492550  /**2551   * Convert etherium cross account id to substrate cross account id2552   * @param ethCrossAccount etherium cross account2553   * @returns substrate cross account id2554   */2555  convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2556    if (ethCrossAccount.sub === '0') {2557      return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2558    }25592560    const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2561    return {Substrate: ss58};2562  }25632564  paraSiblingSovereignAccount(paraid: number) {2565    // We are getting a *sibling* parachain sovereign account,2566    // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2567    const siblingPrefix = '0x7369626c';25682569    const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2570    const suffix = '000000000000000000000000000000000000000000000000';25712572    return siblingPrefix + encodedParaId + suffix;2573  }2574}25752576class StakingGroup extends HelperGroup<UniqueHelper> {2577  /**2578   * Stake tokens for App Promotion2579   * @param signer keyring of signer2580   * @param amountToStake amount of tokens to stake2581   * @param label extra label for log2582   * @returns2583   */2584  async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2585    if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2586    const _stakeResult = await this.helper.executeExtrinsic(2587      signer, 'api.tx.appPromotion.stake',2588      [amountToStake], true,2589    );2590    // TODO extract info from stakeResult2591    return true;2592  }25932594  /**2595   * Unstake tokens for App Promotion2596   * @param signer keyring of signer2597   * @param amountToUnstake amount of tokens to unstake2598   * @param label extra label for log2599   * @returns block number where balances will be unlocked2600   */2601  async unstake(signer: TSigner, label?: string): Promise<number> {2602    if(typeof label === 'undefined') label = `${signer.address}`;2603    const _unstakeResult = await this.helper.executeExtrinsic(2604      signer, 'api.tx.appPromotion.unstake',2605      [], true,2606    );2607    // TODO extract block number fron events2608    return 1;2609  }26102611  /**2612   * Get total staked amount for address2613   * @param address substrate or ethereum address2614   * @returns total staked amount2615   */2616  async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2617    if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2618    return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2619  }26202621  /**2622   * Get total staked per block2623   * @param address substrate or ethereum address2624   * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2625   */2626  async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2627    const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2628    return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2629      return {2630        block: block.toBigInt(),2631        amount: amount.toBigInt(),2632      };2633    });2634  }26352636  /**2637   * Get total pending unstake amount for address2638   * @param address substrate or ethereum address2639   * @returns total pending unstake amount2640   */2641  async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2642    return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2643  }26442645  /**2646   * Get pending unstake amount per block for address2647   * @param address substrate or ethereum address2648   * @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 block2649   */2650  async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2651    const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2652    const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2653      return {2654        block: block.toBigInt(),2655        amount: amount.toBigInt(),2656      };2657    });2658    return result;2659  }2660}26612662class SchedulerGroup extends HelperGroup<UniqueHelper> {2663  constructor(helper: UniqueHelper) {2664    super(helper);2665  }26662667  cancelScheduled(signer: TSigner, scheduledId: string) {2668    return this.helper.executeExtrinsic(2669      signer,2670      'api.tx.scheduler.cancelNamed',2671      [scheduledId],2672      true,2673    );2674  }26752676  changePriority(signer: TSigner, scheduledId: string, priority: number) {2677    return this.helper.executeExtrinsic(2678      signer,2679      'api.tx.scheduler.changeNamedPriority',2680      [scheduledId, priority],2681      true,2682    );2683  }26842685  scheduleAt<T extends UniqueHelper>(2686    executionBlockNumber: number,2687    options: ISchedulerOptions = {},2688  ) {2689    return this.schedule<T>('schedule', executionBlockNumber, options);2690  }26912692  scheduleAfter<T extends UniqueHelper>(2693    blocksBeforeExecution: number,2694    options: ISchedulerOptions = {},2695  ) {2696    return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2697  }26982699  schedule<T extends UniqueHelper>(2700    scheduleFn: 'schedule' | 'scheduleAfter',2701    blocksNum: number,2702    options: ISchedulerOptions = {},2703  ) {2704    // eslint-disable-next-line @typescript-eslint/naming-convention2705    const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2706    return this.helper.clone(ScheduledHelperType, {2707      scheduleFn,2708      blocksNum,2709      options,2710    }) as T;2711  }2712}27132714class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2715  async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2716    await this.helper.executeExtrinsic(2717      signer,2718      'api.tx.foreignAssets.registerForeignAsset',2719      [ownerAddress, location, metadata],2720      true,2721    );2722  }27232724  async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2725    await this.helper.executeExtrinsic(2726      signer,2727      'api.tx.foreignAssets.updateForeignAsset',2728      [foreignAssetId, location, metadata],2729      true,2730    );2731  }2732}27332734class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2735  palletName: string;27362737  constructor(helper: T, palletName: string) {2738    super(helper);27392740    this.palletName = palletName;2741  }27422743  async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {2744    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);2745  }27462747  async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {2748    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);2749  }27502751  async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint) {2752    const destination = {2753      V1: {2754        parents: 0,2755        interior: {2756          X1: {2757            Parachain: destinationParaId,2758          },2759        },2760      },2761    };27622763    const beneficiary = {2764      V1: {2765        parents: 0,2766        interior: {2767          X1: {2768            AccountId32: {2769              network: 'Any',2770              id: targetAccount,2771            },2772          },2773        },2774      },2775    };27762777    const assets = {2778      V1: [2779        {2780          id: {2781            Concrete: {2782              parents: 0,2783              interior: 'Here',2784            },2785          },2786          fun: {2787            Fungible: amount,2788          },2789        },2790      ],2791    };27922793    const feeAssetItem = 0;27942795    await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);2796  }2797}27982799class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2800  async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {2801    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2802  }28032804  async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {2805    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2806  }28072808  async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {2809    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2810  }2811}28122813class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2814  async accounts(address: string, currencyId: any) {2815    const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2816    return BigInt(free);2817  }2818}28192820class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2821  async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2822    await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2823  }28242825  async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2826    await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2827  }28282829  async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2830    await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2831  }28322833  async account(assetId: string | number, address: string) {2834    const accountAsset = (2835      await this.helper.callRpc('api.query.assets.account', [assetId, address])2836    ).toJSON()! as any;28372838    if (accountAsset !== null) {2839      return BigInt(accountAsset['balance']);2840    } else {2841      return null;2842    }2843  }2844}28452846class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2847  async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2848    await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2849  }2850}28512852class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2853  makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2854    const apiPrefix = 'api.tx.assetManager.';28552856    const registerTx = this.helper.constructApiCall(2857      apiPrefix + 'registerForeignAsset',2858      [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2859    );28602861    const setUnitsTx = this.helper.constructApiCall(2862      apiPrefix + 'setAssetUnitsPerSecond',2863      [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2864    );28652866    const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2867    const encodedProposal = batchCall?.method.toHex() || '';2868    return encodedProposal;2869  }28702871  async assetTypeId(location: any) {2872    return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2873  }2874}28752876class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2877  notePreimagePallet: string;28782879  constructor(helper: MoonbeamHelper, options: {[key: string]: any} = {}) {2880    super(helper);2881    this.notePreimagePallet = options.notePreimagePallet;2882  }28832884  async notePreimage(signer: TSigner, encodedProposal: string) {2885    await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);2886  }28872888  externalProposeMajority(proposal: any) {2889    return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);2890  }28912892  fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2893    return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2894  }28952896  async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2897    await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2898  }2899}29002901class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2902  collective: string;29032904  constructor(helper: MoonbeamHelper, collective: string) {2905    super(helper);29062907    this.collective = collective;2908  }29092910  async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2911    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2912  }29132914  async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2915    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2916  }29172918  async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {2919    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2920  }29212922  async proposalCount() {2923    return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2924  }2925}29262927export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2928export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;29292930export class UniqueHelper extends ChainHelperBase {2931  balance: BalanceGroup<UniqueHelper>;2932  collection: CollectionGroup;2933  nft: NFTGroup;2934  rft: RFTGroup;2935  ft: FTGroup;2936  staking: StakingGroup;2937  scheduler: SchedulerGroup;2938  foreignAssets: ForeignAssetsGroup;2939  xcm: XcmGroup<UniqueHelper>;2940  xTokens: XTokensGroup<UniqueHelper>;2941  tokens: TokensGroup<UniqueHelper>;29422943  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2944    super(logger, options.helperBase ?? UniqueHelper);29452946    this.balance = new BalanceGroup(this);2947    this.collection = new CollectionGroup(this);2948    this.nft = new NFTGroup(this);2949    this.rft = new RFTGroup(this);2950    this.ft = new FTGroup(this);2951    this.staking = new StakingGroup(this);2952    this.scheduler = new SchedulerGroup(this);2953    this.foreignAssets = new ForeignAssetsGroup(this);2954    this.xcm = new XcmGroup(this, 'polkadotXcm');2955    this.xTokens = new XTokensGroup(this);2956    this.tokens = new TokensGroup(this);2957  }29582959  getSudo<T extends UniqueHelper>() {2960    // eslint-disable-next-line @typescript-eslint/naming-convention2961    const SudoHelperType = SudoHelper(this.helperBase);2962    return this.clone(SudoHelperType) as T;2963  }2964}29652966export class XcmChainHelper extends ChainHelperBase {2967  async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2968    const wsProvider = new WsProvider(wsEndpoint);2969    this.api = new ApiPromise({2970      provider: wsProvider,2971    });2972    await this.api.isReadyOrError;2973    this.network = await UniqueHelper.detectNetwork(this.api);2974  }2975}29762977export class RelayHelper extends XcmChainHelper {2978  balance: SubstrateBalanceGroup<RelayHelper>;2979  xcm: XcmGroup<RelayHelper>;29802981  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2982    super(logger, options.helperBase ?? RelayHelper);29832984    this.balance = new SubstrateBalanceGroup(this);2985    this.xcm = new XcmGroup(this, 'xcmPallet');2986  }2987}29882989export class WestmintHelper extends XcmChainHelper {2990  balance: SubstrateBalanceGroup<WestmintHelper>;2991  xcm: XcmGroup<WestmintHelper>;2992  assets: AssetsGroup<WestmintHelper>;2993  xTokens: XTokensGroup<WestmintHelper>;29942995  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2996    super(logger, options.helperBase ?? WestmintHelper);29972998    this.balance = new SubstrateBalanceGroup(this);2999    this.xcm = new XcmGroup(this, 'polkadotXcm');3000    this.assets = new AssetsGroup(this);3001    this.xTokens = new XTokensGroup(this);3002  }3003}30043005export class MoonbeamHelper extends XcmChainHelper {3006  balance: EthereumBalanceGroup<MoonbeamHelper>;3007  assetManager: MoonbeamAssetManagerGroup;3008  assets: AssetsGroup<MoonbeamHelper>;3009  xTokens: XTokensGroup<MoonbeamHelper>;3010  democracy: MoonbeamDemocracyGroup;3011  collective: {3012    council: MoonbeamCollectiveGroup,3013    techCommittee: MoonbeamCollectiveGroup,3014  };30153016  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3017    super(logger, options.helperBase ?? MoonbeamHelper);30183019    this.balance = new EthereumBalanceGroup(this);3020    this.assetManager = new MoonbeamAssetManagerGroup(this);3021    this.assets = new AssetsGroup(this);3022    this.xTokens = new XTokensGroup(this);3023    this.democracy = new MoonbeamDemocracyGroup(this, options);3024    this.collective = {3025      council: new MoonbeamCollectiveGroup(this, 'councilCollective'),3026      techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),3027    };3028  }3029}30303031export class AcalaHelper extends XcmChainHelper {3032  balance: SubstrateBalanceGroup<AcalaHelper>;3033  assetRegistry: AcalaAssetRegistryGroup;3034  xTokens: XTokensGroup<AcalaHelper>;3035  tokens: TokensGroup<AcalaHelper>;30363037  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3038    super(logger, options.helperBase ?? AcalaHelper);30393040    this.balance = new SubstrateBalanceGroup(this);3041    this.assetRegistry = new AcalaAssetRegistryGroup(this);3042    this.xTokens = new XTokensGroup(this);3043    this.tokens = new TokensGroup(this);3044  }30453046  getSudo<T extends AcalaHelper>() {3047    // eslint-disable-next-line @typescript-eslint/naming-convention3048    const SudoHelperType = SudoHelper(this.helperBase);3049    return this.clone(SudoHelperType) as T;3050  }3051}30523053// eslint-disable-next-line @typescript-eslint/naming-convention3054function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3055  return class extends Base {3056    scheduleFn: 'schedule' | 'scheduleAfter';3057    blocksNum: number;3058    options: ISchedulerOptions;30593060    constructor(...args: any[]) {3061      const logger = args[0] as ILogger;3062      const options = args[1] as {3063        scheduleFn: 'schedule' | 'scheduleAfter',3064        blocksNum: number,3065        options: ISchedulerOptions3066      };30673068      super(logger);30693070      this.scheduleFn = options.scheduleFn;3071      this.blocksNum = options.blocksNum;3072      this.options = options.options;3073    }30743075    executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3076      const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);30773078      const mandatorySchedArgs = [3079        this.blocksNum,3080        this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3081        this.options.priority ?? null,3082        scheduledTx,3083      ];30843085      let schedArgs;3086      let scheduleFn;30873088      if (this.options.scheduledId) {3089        schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];30903091        if (this.scheduleFn == 'schedule') {3092          scheduleFn = 'scheduleNamed';3093        } else if (this.scheduleFn == 'scheduleAfter') {3094          scheduleFn = 'scheduleNamedAfter';3095        }3096      } else {3097        schedArgs = mandatorySchedArgs;3098        scheduleFn = this.scheduleFn;3099      }31003101      const extrinsic = 'api.tx.scheduler.' +  scheduleFn;31023103      return super.executeExtrinsic(3104        sender,3105        extrinsic,3106        schedArgs,3107        expectSuccess,3108      );3109    }3110  };3111}31123113// eslint-disable-next-line @typescript-eslint/naming-convention3114function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3115  return class extends Base {3116    constructor(...args: any[]) {3117      super(...args);3118    }31193120    executeExtrinsic (3121      sender: IKeyringPair,3122      extrinsic: string,3123      params: any[],3124      expectSuccess?: boolean,3125    ): Promise<ITransactionResult> {3126      const call = this.constructApiCall(extrinsic, params);3127      return super.executeExtrinsic(3128        sender,3129        'api.tx.sudo.sudo',3130        [call],3131        expectSuccess,3132      );3133    }3134  };3135}31363137export class UniqueBaseCollection {3138  helper: UniqueHelper;3139  collectionId: number;31403141  constructor(collectionId: number, uniqueHelper: UniqueHelper) {3142    this.collectionId = collectionId;3143    this.helper = uniqueHelper;3144  }31453146  async getData() {3147    return await this.helper.collection.getData(this.collectionId);3148  }31493150  async getLastTokenId() {3151    return await this.helper.collection.getLastTokenId(this.collectionId);3152  }31533154  async doesTokenExist(tokenId: number) {3155    return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3156  }31573158  async getAdmins() {3159    return await this.helper.collection.getAdmins(this.collectionId);3160  }31613162  async getAllowList() {3163    return await this.helper.collection.getAllowList(this.collectionId);3164  }31653166  async getEffectiveLimits() {3167    return await this.helper.collection.getEffectiveLimits(this.collectionId);3168  }31693170  async getProperties(propertyKeys?: string[] | null) {3171    return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3172  }31733174  async getPropertiesConsumedSpace() {3175    return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3176  }31773178  async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3179    return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3180  }31813182  async getOptions() {3183    return await this.helper.collection.getCollectionOptions(this.collectionId);3184  }31853186  async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3187    return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3188  }31893190  async confirmSponsorship(signer: TSigner) {3191    return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3192  }31933194  async removeSponsor(signer: TSigner) {3195    return await this.helper.collection.removeSponsor(signer, this.collectionId);3196  }31973198  async setLimits(signer: TSigner, limits: ICollectionLimits) {3199    return await this.helper.collection.setLimits(signer, this.collectionId, limits);3200  }32013202  async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3203    return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3204  }32053206  async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3207    return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3208  }32093210  async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3211    return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3212  }32133214  async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3215    return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3216  }32173218  async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3219    return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3220  }32213222  async setProperties(signer: TSigner, properties: IProperty[]) {3223    return await this.helper.collection.setProperties(signer, this.collectionId, properties);3224  }32253226  async deleteProperties(signer: TSigner, propertyKeys: string[]) {3227    return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3228  }32293230  async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3231    return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3232  }32333234  async enableNesting(signer: TSigner, permissions: INestingPermissions) {3235    return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3236  }32373238  async disableNesting(signer: TSigner) {3239    return await this.helper.collection.disableNesting(signer, this.collectionId);3240  }32413242  async burn(signer: TSigner) {3243    return await this.helper.collection.burn(signer, this.collectionId);3244  }32453246  scheduleAt<T extends UniqueHelper>(3247    executionBlockNumber: number,3248    options: ISchedulerOptions = {},3249  ) {3250    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3251    return new UniqueBaseCollection(this.collectionId, scheduledHelper);3252  }32533254  scheduleAfter<T extends UniqueHelper>(3255    blocksBeforeExecution: number,3256    options: ISchedulerOptions = {},3257  ) {3258    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3259    return new UniqueBaseCollection(this.collectionId, scheduledHelper);3260  }32613262  getSudo<T extends UniqueHelper>() {3263    return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3264  }3265}326632673268export class UniqueNFTCollection extends UniqueBaseCollection {3269  getTokenObject(tokenId: number) {3270    return new UniqueNFToken(tokenId, this);3271  }32723273  async getTokensByAddress(addressObj: ICrossAccountId) {3274    return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3275  }32763277  async getToken(tokenId: number, blockHashAt?: string) {3278    return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3279  }32803281  async getTokenOwner(tokenId: number, blockHashAt?: string) {3282    return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3283  }32843285  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3286    return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3287  }32883289  async getTokenChildren(tokenId: number, blockHashAt?: string) {3290    return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3291  }32923293  async getPropertyPermissions(propertyKeys: string[] | null = null) {3294    return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3295  }32963297  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3298    return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3299  }33003301  async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3302    const api = this.helper.getApi();3303    const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();33043305    return (props! as any).consumedSpace;3306  }33073308  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3309    return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3310  }33113312  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3313    return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3314  }33153316  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3317    return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3318  }33193320  async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3321    return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3322  }33233324  async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3325    return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3326  }33273328  async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3329    return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3330  }33313332  async burnToken(signer: TSigner, tokenId: number) {3333    return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3334  }33353336  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3337    return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3338  }33393340  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3341    return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3342  }33433344  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3345    return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3346  }33473348  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3349    return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3350  }33513352  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3353    return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3354  }33553356  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3357    return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3358  }33593360  scheduleAt<T extends UniqueHelper>(3361    executionBlockNumber: number,3362    options: ISchedulerOptions = {},3363  ) {3364    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3365    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3366  }33673368  scheduleAfter<T extends UniqueHelper>(3369    blocksBeforeExecution: number,3370    options: ISchedulerOptions = {},3371  ) {3372    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3373    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3374  }33753376  getSudo<T extends UniqueHelper>() {3377    return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3378  }3379}338033813382export class UniqueRFTCollection extends UniqueBaseCollection {3383  getTokenObject(tokenId: number) {3384    return new UniqueRFToken(tokenId, this);3385  }33863387  async getToken(tokenId: number, blockHashAt?: string) {3388    return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3389  }33903391  async getTokensByAddress(addressObj: ICrossAccountId) {3392    return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3393  }33943395  async getTop10TokenOwners(tokenId: number) {3396    return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3397  }33983399  async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3400    return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3401  }34023403  async getTokenTotalPieces(tokenId: number) {3404    return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3405  }34063407  async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3408    return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3409  }34103411  async getPropertyPermissions(propertyKeys: string[] | null = null) {3412    return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3413  }34143415  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3416    return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3417  }34183419  async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3420    const api = this.helper.getApi();3421    const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();34223423    return (props! as any).consumedSpace;3424  }34253426  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3427    return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3428  }34293430  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3431    return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3432  }34333434  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3435    return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3436  }34373438  async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3439    return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3440  }34413442  async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3443    return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3444  }34453446  async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3447    return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3448  }34493450  async burnToken(signer: TSigner, tokenId: number, amount=1n) {3451    return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3452  }34533454  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId,  amount=1n) {3455    return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3456  }34573458  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3459    return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3460  }34613462  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3463    return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3464  }34653466  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3467    return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3468  }34693470  scheduleAt<T extends UniqueHelper>(3471    executionBlockNumber: number,3472    options: ISchedulerOptions = {},3473  ) {3474    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3475    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3476  }34773478  scheduleAfter<T extends UniqueHelper>(3479    blocksBeforeExecution: number,3480    options: ISchedulerOptions = {},3481  ) {3482    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3483    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3484  }34853486  getSudo<T extends UniqueHelper>() {3487    return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3488  }3489}349034913492export class UniqueFTCollection extends UniqueBaseCollection {3493  async getBalance(addressObj: ICrossAccountId) {3494    return await this.helper.ft.getBalance(this.collectionId, addressObj);3495  }34963497  async getTotalPieces() {3498    return await this.helper.ft.getTotalPieces(this.collectionId);3499  }35003501  async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3502    return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3503  }35043505  async getTop10Owners() {3506    return await this.helper.ft.getTop10Owners(this.collectionId);3507  }35083509  async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3510    return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3511  }35123513  async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3514    return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3515  }35163517  async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3518    return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3519  }35203521  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3522    return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3523  }35243525  async burnTokens(signer: TSigner, amount=1n) {3526    return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3527  }35283529  async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3530    return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3531  }35323533  async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3534    return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3535  }35363537  scheduleAt<T extends UniqueHelper>(3538    executionBlockNumber: number,3539    options: ISchedulerOptions = {},3540  ) {3541    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3542    return new UniqueFTCollection(this.collectionId, scheduledHelper);3543  }35443545  scheduleAfter<T extends UniqueHelper>(3546    blocksBeforeExecution: number,3547    options: ISchedulerOptions = {},3548  ) {3549    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3550    return new UniqueFTCollection(this.collectionId, scheduledHelper);3551  }35523553  getSudo<T extends UniqueHelper>() {3554    return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3555  }3556}355735583559export class UniqueBaseToken {3560  collection: UniqueNFTCollection | UniqueRFTCollection;3561  collectionId: number;3562  tokenId: number;35633564  constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3565    this.collection = collection;3566    this.collectionId = collection.collectionId;3567    this.tokenId = tokenId;3568  }35693570  async getNextSponsored(addressObj: ICrossAccountId) {3571    return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3572  }35733574  async getProperties(propertyKeys?: string[] | null) {3575    return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3576  }35773578  async getTokenPropertiesConsumedSpace() {3579    return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3580  }35813582  async setProperties(signer: TSigner, properties: IProperty[]) {3583    return await this.collection.setTokenProperties(signer, this.tokenId, properties);3584  }35853586  async deleteProperties(signer: TSigner, propertyKeys: string[]) {3587    return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3588  }35893590  async doesExist() {3591    return await this.collection.doesTokenExist(this.tokenId);3592  }35933594  nestingAccount() {3595    return this.collection.helper.util.getTokenAccount(this);3596  }35973598  scheduleAt<T extends UniqueHelper>(3599    executionBlockNumber: number,3600    options: ISchedulerOptions = {},3601  ) {3602    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3603    return new UniqueBaseToken(this.tokenId, scheduledCollection);3604  }36053606  scheduleAfter<T extends UniqueHelper>(3607    blocksBeforeExecution: number,3608    options: ISchedulerOptions = {},3609  ) {3610    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3611    return new UniqueBaseToken(this.tokenId, scheduledCollection);3612  }36133614  getSudo<T extends UniqueHelper>() {3615    return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3616  }3617}361836193620export class UniqueNFToken extends UniqueBaseToken {3621  collection: UniqueNFTCollection;36223623  constructor(tokenId: number, collection: UniqueNFTCollection) {3624    super(tokenId, collection);3625    this.collection = collection;3626  }36273628  async getData(blockHashAt?: string) {3629    return await this.collection.getToken(this.tokenId, blockHashAt);3630  }36313632  async getOwner(blockHashAt?: string) {3633    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3634  }36353636  async getTopmostOwner(blockHashAt?: string) {3637    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3638  }36393640  async getChildren(blockHashAt?: string) {3641    return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3642  }36433644  async nest(signer: TSigner, toTokenObj: IToken) {3645    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3646  }36473648  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3649    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3650  }36513652  async transfer(signer: TSigner, addressObj: ICrossAccountId) {3653    return await this.collection.transferToken(signer, this.tokenId, addressObj);3654  }36553656  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3657    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3658  }36593660  async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3661    return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3662  }36633664  async isApproved(toAddressObj: ICrossAccountId) {3665    return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3666  }36673668  async burn(signer: TSigner) {3669    return await this.collection.burnToken(signer, this.tokenId);3670  }36713672  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3673    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3674  }36753676  scheduleAt<T extends UniqueHelper>(3677    executionBlockNumber: number,3678    options: ISchedulerOptions = {},3679  ) {3680    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3681    return new UniqueNFToken(this.tokenId, scheduledCollection);3682  }36833684  scheduleAfter<T extends UniqueHelper>(3685    blocksBeforeExecution: number,3686    options: ISchedulerOptions = {},3687  ) {3688    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3689    return new UniqueNFToken(this.tokenId, scheduledCollection);3690  }36913692  getSudo<T extends UniqueHelper>() {3693    return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3694  }3695}36963697export class UniqueRFToken extends UniqueBaseToken {3698  collection: UniqueRFTCollection;36993700  constructor(tokenId: number, collection: UniqueRFTCollection) {3701    super(tokenId, collection);3702    this.collection = collection;3703  }37043705  async getData(blockHashAt?: string) {3706    return await this.collection.getToken(this.tokenId, blockHashAt);3707  }37083709  async getTop10Owners() {3710    return await this.collection.getTop10TokenOwners(this.tokenId);3711  }37123713  async getBalance(addressObj: ICrossAccountId) {3714    return await this.collection.getTokenBalance(this.tokenId, addressObj);3715  }37163717  async getTotalPieces() {3718    return await this.collection.getTokenTotalPieces(this.tokenId);3719  }37203721  async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3722    return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3723  }37243725  async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3726    return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3727  }37283729  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3730    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3731  }37323733  async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3734    return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3735  }37363737  async repartition(signer: TSigner, amount: bigint) {3738    return await this.collection.repartitionToken(signer, this.tokenId, amount);3739  }37403741  async burn(signer: TSigner, amount=1n) {3742    return await this.collection.burnToken(signer, this.tokenId, amount);3743  }37443745  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3746    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3747  }37483749  scheduleAt<T extends UniqueHelper>(3750    executionBlockNumber: number,3751    options: ISchedulerOptions = {},3752  ) {3753    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3754    return new UniqueRFToken(this.tokenId, scheduledCollection);3755  }37563757  scheduleAfter<T extends UniqueHelper>(3758    blocksBeforeExecution: number,3759    options: ISchedulerOptions = {},3760  ) {3761    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3762    return new UniqueRFToken(this.tokenId, scheduledCollection);3763  }37643765  getSudo<T extends UniqueHelper>() {3766    return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3767  }3768}
after · tests/src/util/playgrounds/unique.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {hexToU8a} from '@polkadot/util/hex';13import {u8aConcat} from '@polkadot/util/u8a';14import {15  IApiListeners,16  IBlock,17  IEvent,18  IChainProperties,19  ICollectionCreationOptions,20  ICollectionLimits,21  ICollectionPermissions,22  ICrossAccountId,23  ICrossAccountIdLower,24  ILogger,25  INestingPermissions,26  IProperty,27  IStakingInfo,28  ISchedulerOptions,29  ISubstrateBalance,30  IToken,31  ITokenPropertyPermission,32  ITransactionResult,33  IUniqueHelperLog,34  TApiAllowedListeners,35  TEthereumAccount,36  TSigner,37  TSubstrateAccount,38  TNetworks,39  IForeignAssetMetadata,40  AcalaAssetMetadata,41  MoonbeamAssetInfo,42  DemocracyStandardAccountVote,43  IEthCrossAccountId,44} from './types';45import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';46import type {Vec} from '@polkadot/types-codec';47import {FrameSystemEventRecord} from '@polkadot/types/lookup';4849export class CrossAccountId implements ICrossAccountId {50  Substrate?: TSubstrateAccount;51  Ethereum?: TEthereumAccount;5253  constructor(account: ICrossAccountId) {54    if (account.Substrate) this.Substrate = account.Substrate;55    if (account.Ethereum) this.Ethereum = account.Ethereum;56  }5758  static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {59    switch (domain) {60      case 'Substrate': return new CrossAccountId({Substrate: account.address});61      case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();62    }63  }6465  static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {66    return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});67  }6869  static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {70    return encodeAddress(decodeAddress(address), ss58Format);71  }7273  static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {74    return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});75  }7677  withNormalizedSubstrate(ss58Format = 42): CrossAccountId {78    if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);79    return this;80  }8182  static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {83    return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));84  }8586  toEthereum(): CrossAccountId {87    if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});88    return this;89  }9091  static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {92    return evmToAddress(address, ss58Format);93  }9495  toSubstrate(ss58Format?: number): CrossAccountId {96    if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});97    return this;98  }99100  toLowerCase(): CrossAccountId {101    if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();102    if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();103    return this;104  }105}106107const nesting = {108  toChecksumAddress(address: string): string {109    if (typeof address === 'undefined') return '';110111    if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);112113    address = address.toLowerCase().replace(/^0x/i,'');114    const addressHash = keccakAsHex(address).replace(/^0x/i,'');115    const checksumAddress = ['0x'];116117    for (let i = 0; i < address.length; i++) {118      // If ith character is 8 to f then make it uppercase119      if (parseInt(addressHash[i], 16) > 7) {120        checksumAddress.push(address[i].toUpperCase());121      } else {122        checksumAddress.push(address[i]);123      }124    }125    return checksumAddress.join('');126  },127  tokenIdToAddress(collectionId: number, tokenId: number) {128    return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);129  },130};131132class UniqueUtil {133  static transactionStatus = {134    NOT_READY: 'NotReady',135    FAIL: 'Fail',136    SUCCESS: 'Success',137  };138139  static chainLogType = {140    EXTRINSIC: 'extrinsic',141    RPC: 'rpc',142  };143144  static getTokenAccount(token: IToken): CrossAccountId {145    return new CrossAccountId({Ethereum: this.getTokenAddress(token)});146  }147148  static getTokenAddress(token: IToken): string {149    return nesting.tokenIdToAddress(token.collectionId, token.tokenId);150  }151152  static getDefaultLogger(): ILogger {153    return {154      log(msg: any, level = 'INFO') {155        console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));156      },157      level: {158        ERROR: 'ERROR',159        WARNING: 'WARNING',160        INFO: 'INFO',161      },162    };163  }164165  static vec2str(arr: string[] | number[]) {166    return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');167  }168169  static str2vec(string: string) {170    if (typeof string !== 'string') return string;171    return Array.from(string).map(x => x.charCodeAt(0));172  }173174  static fromSeed(seed: string, ss58Format = 42) {175    const keyring = new Keyring({type: 'sr25519', ss58Format});176    return keyring.addFromUri(seed);177  }178179  static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {180    if (creationResult.status !== this.transactionStatus.SUCCESS) {181      throw Error('Unable to create collection!');182    }183184    let collectionId = null;185    creationResult.result.events.forEach(({event: {data, method, section}}) => {186      if ((section === 'common') && (method === 'CollectionCreated')) {187        collectionId = parseInt(data[0].toString(), 10);188      }189    });190191    if (collectionId === null) {192      throw Error('No CollectionCreated event was found!');193    }194195    return collectionId;196  }197198  static extractTokensFromCreationResult(creationResult: ITransactionResult): {199    success: boolean,200    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],201  } {202    if (creationResult.status !== this.transactionStatus.SUCCESS) {203      throw Error('Unable to create tokens!');204    }205    let success = false;206    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];207    creationResult.result.events.forEach(({event: {data, method, section}}) => {208      if (method === 'ExtrinsicSuccess') {209        success = true;210      } else if ((section === 'common') && (method === 'ItemCreated')) {211        tokens.push({212          collectionId: parseInt(data[0].toString(), 10),213          tokenId: parseInt(data[1].toString(), 10),214          owner: data[2].toHuman(),215          amount: data[3].toBigInt(),216        });217      }218    });219    return {success, tokens};220  }221222  static extractTokensFromBurnResult(burnResult: ITransactionResult): {223    success: boolean,224    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],225  } {226    if (burnResult.status !== this.transactionStatus.SUCCESS) {227      throw Error('Unable to burn tokens!');228    }229    let success = false;230    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];231    burnResult.result.events.forEach(({event: {data, method, section}}) => {232      if (method === 'ExtrinsicSuccess') {233        success = true;234      } else if ((section === 'common') && (method === 'ItemDestroyed')) {235        tokens.push({236          collectionId: parseInt(data[0].toString(), 10),237          tokenId: parseInt(data[1].toString(), 10),238          owner: data[2].toHuman(),239          amount: data[3].toBigInt(),240        });241      }242    });243    return {success, tokens};244  }245246  static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {247    let eventId = null;248    events.forEach(({event: {data, method, section}}) => {249      if ((section === expectedSection) && (method === expectedMethod)) {250        eventId = parseInt(data[0].toString(), 10);251      }252    });253254    if (eventId === null) {255      throw Error(`No ${expectedMethod} event was found!`);256    }257    return eventId === collectionId;258  }259260  static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {261    const normalizeAddress = (address: string | ICrossAccountId) => {262      if(typeof address === 'string') return address;263      const obj = {} as any;264      Object.keys(address).forEach(k => {265        obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];266      });267      if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);268      if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();269      return address;270    };271    let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;272    events.forEach(({event: {data, method, section}}) => {273      if ((section === 'common') && (method === 'Transfer')) {274        const hData = (data as any).toJSON();275        transfer = {276          collectionId: hData[0],277          tokenId: hData[1],278          from: normalizeAddress(hData[2]),279          to: normalizeAddress(hData[3]),280          amount: BigInt(hData[4]),281        };282      }283    });284    let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;285    isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);286    isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);287    isSuccess = isSuccess && amount === transfer.amount;288    return isSuccess;289  }290291  static bigIntToDecimals(number: bigint, decimals = 18) {292    const numberStr = number.toString();293    const dotPos = numberStr.length - decimals;294295    if (dotPos <= 0) {296      return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;297    } else {298      const intPart = numberStr.substring(0, dotPos);299      const fractPart = numberStr.substring(dotPos);300      return intPart + '.' + fractPart;301    }302  }303}304305class UniqueEventHelper {306  private static extractIndex(index: any): [number, number] | string {307    if(index.toRawType() === '[u8;2]') return [index[0], index[1]];308    return index.toJSON();309  }310311  private static extractSub(data: any, subTypes: any): {[key: string]: any} {312    let obj: any = {};313    let index = 0;314315    if (data.entries) {316      for(const [key, value] of data.entries()) {317        obj[key] = this.extractData(value, subTypes[index]);318        index++;319      }320    } else obj = data.toJSON();321322    return obj;323  }324325  private static toHuman(data: any) {326    return data && data.toHuman ? data.toHuman() : `${data}`;327  }328329  private static extractData(data: any, type: any): any {330    if(!type) return this.toHuman(data);331    if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();332    if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();333    if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);334    return this.toHuman(data);335  }336337  public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {338    const parsedEvents: IEvent[] = [];339340    events.forEach((record) => {341      const {event, phase} = record;342      const types = event.typeDef;343344      const eventData: IEvent = {345        section: event.section.toString(),346        method: event.method.toString(),347        index: this.extractIndex(event.index),348        data: [],349        phase: phase.toJSON(),350      };351352      event.data.forEach((val: any, index: number) => {353        eventData.data.push(this.extractData(val, types[index]));354      });355356      parsedEvents.push(eventData);357    });358359    return parsedEvents;360  }361}362363export class ChainHelperBase {364  helperBase: any;365366  transactionStatus = UniqueUtil.transactionStatus;367  chainLogType = UniqueUtil.chainLogType;368  util: typeof UniqueUtil;369  eventHelper: typeof UniqueEventHelper;370  logger: ILogger;371  api: ApiPromise | null;372  forcedNetwork: TNetworks | null;373  network: TNetworks | null;374  chainLog: IUniqueHelperLog[];375  children: ChainHelperBase[];376  address: AddressGroup;377  chain: ChainGroup;378379  constructor(logger?: ILogger, helperBase?: any) {380    this.helperBase = helperBase;381382    this.util = UniqueUtil;383    this.eventHelper = UniqueEventHelper;384    if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();385    this.logger = logger;386    this.api = null;387    this.forcedNetwork = null;388    this.network = null;389    this.chainLog = [];390    this.children = [];391    this.address = new AddressGroup(this);392    this.chain = new ChainGroup(this);393  }394395  clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {396    Object.setPrototypeOf(helperCls.prototype, this);397    const newHelper = new helperCls(this.logger, options);398399    newHelper.api = this.api;400    newHelper.network = this.network;401    newHelper.forceNetwork = this.forceNetwork;402403    this.children.push(newHelper);404405    return newHelper;406  }407408  getApi(): ApiPromise {409    if(this.api === null) throw Error('API not initialized');410    return this.api;411  }412413  async subscribeEvents(expectedEvents: {section: string, names: string[]}[]) {414    const collectedEvents: IEvent[] = [];415    const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {416      const ievents = this.eventHelper.extractEvents(events);417      ievents.forEach((event) => {418        expectedEvents.forEach((e => {419          if (event.section === e.section && e.names.includes(event.method)) {420            collectedEvents.push(event);421          }422        }));423      });424    });425    return {unsubscribe: unsubscribe as any, collectedEvents};426  }427428  clearChainLog(): void {429    this.chainLog = [];430  }431432  forceNetwork(value: TNetworks): void {433    this.forcedNetwork = value;434  }435436  async connect(wsEndpoint: string, listeners?: IApiListeners) {437    if (this.api !== null) throw Error('Already connected');438    const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);439    this.api = api;440    this.network = network;441  }442443  async disconnect() {444    for (const child of this.children) {445      child.clearApi();446    }447448    if (this.api === null) return;449    await this.api.disconnect();450    this.clearApi();451  }452453  clearApi() {454    this.api = null;455    this.network = null;456  }457458  static async detectNetwork(api: ApiPromise): Promise<TNetworks> {459    const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;460    const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];461462    if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;463464    if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;465    return 'opal';466  }467468  static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {469    const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});470    await api.isReady;471472    const network = await this.detectNetwork(api);473474    await api.disconnect();475476    return network;477  }478479  static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{480    api: ApiPromise;481    network: TNetworks;482  }> {483    if(typeof network === 'undefined' || network === null) network = 'opal';484    const supportedRPC = {485      opal: {486        unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,487      },488      quartz: {489        unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,490      },491      unique: {492        unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,493      },494      rococo: {},495      westend: {},496      moonbeam: {},497      moonriver: {},498      acala: {},499      karura: {},500      westmint: {},501    };502    if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);503    const rpc = supportedRPC[network];504505    // TODO: investigate how to replace rpc in runtime506    // api._rpcCore.addUserInterfaces(rpc);507508    const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});509510    await api.isReadyOrError;511512    if (typeof listeners === 'undefined') listeners = {};513    for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {514      if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;515      api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);516    }517518    return {api, network};519  }520521  getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {522    const {events, status} = data;523    if (status.isReady) {524      return this.transactionStatus.NOT_READY;525    }526    if (status.isBroadcast) {527      return this.transactionStatus.NOT_READY;528    }529    if (status.isInBlock || status.isFinalized) {530      const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');531      if (errors.length > 0) {532        return this.transactionStatus.FAIL;533      }534      if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {535        return this.transactionStatus.SUCCESS;536      }537    }538539    return this.transactionStatus.FAIL;540  }541542  signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {543    const sign = (callback: any) => {544      if(options !== null) return transaction.signAndSend(sender, options, callback);545      return transaction.signAndSend(sender, callback);546    };547    // eslint-disable-next-line no-async-promise-executor548    return new Promise(async (resolve, reject) => {549      try {550        const unsub = await sign((result: any) => {551          const status = this.getTransactionStatus(result);552553          if (status === this.transactionStatus.SUCCESS) {554            this.logger.log(`${label} successful`);555            unsub();556            resolve({result, status});557          } else if (status === this.transactionStatus.FAIL) {558            let moduleError = null;559560            if (result.hasOwnProperty('dispatchError')) {561              const dispatchError = result['dispatchError'];562563              if (dispatchError) {564                if (dispatchError.isModule) {565                  const modErr = dispatchError.asModule;566                  const errorMeta = dispatchError.registry.findMetaError(modErr);567568                  moduleError = `${errorMeta.section}.${errorMeta.name}`;569                } else {570                  moduleError = dispatchError.toHuman();571                }572              } else {573                this.logger.log(result, this.logger.level.ERROR);574              }575            }576577            this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);578            unsub();579            reject({status, moduleError, result});580          }581        });582      } catch (e) {583        this.logger.log(e, this.logger.level.ERROR);584        reject(e);585      }586    });587  }588589  async signTransactionWithoutSending(signer: TSigner, tx: any) {590    const api = this.getApi();591    const signingInfo = await api.derive.tx.signingInfo(signer.address);592593    tx.sign(signer, {594      blockHash: api.genesisHash,595      genesisHash: api.genesisHash,596      runtimeVersion: api.runtimeVersion,597      nonce: signingInfo.nonce,598    });599600    return tx.toHex();601  }602603  async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {604    const api = this.getApi();605    const signingInfo = await api.derive.tx.signingInfo(signer.address);606607    // We need to sign the tx because608    // unsigned transactions does not have an inclusion fee609    tx.sign(signer, {610      blockHash: api.genesisHash,611      genesisHash: api.genesisHash,612      runtimeVersion: api.runtimeVersion,613      nonce: signingInfo.nonce,614    });615616    if (len === null) {617      return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;618    } else {619      return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;620    }621  }622623  constructApiCall(apiCall: string, params: any[]) {624    if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);625    let call = this.getApi() as any;626    for(const part of apiCall.slice(4).split('.')) {627      call = call[part];628    }629    return call(...params);630  }631632  async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {633    if(this.api === null) throw Error('API not initialized');634    if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);635636    const startTime = (new Date()).getTime();637    let result: ITransactionResult;638    let events: IEvent[] = [];639    try {640      result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;641      events = this.eventHelper.extractEvents(result.result.events);642    }643    catch(e) {644      if(!(e as object).hasOwnProperty('status')) throw e;645      result = e as ITransactionResult;646    }647648    const endTime = (new Date()).getTime();649650    const log = {651      executedAt: endTime,652      executionTime: endTime - startTime,653      type: this.chainLogType.EXTRINSIC,654      status: result.status,655      call: extrinsic,656      signer: this.getSignerAddress(sender),657      params,658    } as IUniqueHelperLog;659660    if(result.status !== this.transactionStatus.SUCCESS) {661      if (result.moduleError) log.moduleError = result.moduleError;662      else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;663    }664    if(events.length > 0) log.events = events;665666    this.chainLog.push(log);667668    if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {669      if (result.moduleError) throw Error(`${result.moduleError}`);670      else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));671    }672    return result;673  }674675  async callRpc(rpc: string, params?: any[]) {676    if(typeof params === 'undefined') params = [];677    if(this.api === null) throw Error('API not initialized');678    if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);679680    const startTime = (new Date()).getTime();681    let result;682    let error = null;683    const log = {684      type: this.chainLogType.RPC,685      call: rpc,686      params,687    } as IUniqueHelperLog;688689    try {690      result = await this.constructApiCall(rpc, params);691    }692    catch(e) {693      error = e;694    }695696    const endTime = (new Date()).getTime();697698    log.executedAt = endTime;699    log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';700    log.executionTime = endTime - startTime;701702    this.chainLog.push(log);703704    if(error !== null) throw error;705706    return result;707  }708709  getSignerAddress(signer: IKeyringPair | string): string {710    if(typeof signer === 'string') return signer;711    return signer.address;712  }713714  fetchAllPalletNames(): string[] {715    if(this.api === null) throw Error('API not initialized');716    return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());717  }718719  fetchMissingPalletNames(requiredPallets: string[]): string[] {720    const palletNames = this.fetchAllPalletNames();721    return requiredPallets.filter(p => !palletNames.includes(p));722  }723}724725726class HelperGroup<T extends ChainHelperBase> {727  helper: T;728729  constructor(uniqueHelper: T) {730    this.helper = uniqueHelper;731  }732}733734735class CollectionGroup extends HelperGroup<UniqueHelper> {736  /**737 * Get number of blocks when sponsored transaction is available.738 *739 * @param collectionId ID of collection740 * @param tokenId ID of token741 * @param addressObj address for which the sponsorship is checked742 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});743 * @returns number of blocks or null if sponsorship hasn't been set744 */745  async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {746    return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();747  }748749  /**750   * Get the number of created collections.751   *752   * @returns number of created collections753   */754  async getTotalCount(): Promise<number> {755    return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();756  }757758  /**759   * Get information about the collection with additional data,760   * including the number of tokens it contains, its administrators,761   * the normalized address of the collection's owner, and decoded name and description.762   *763   * @param collectionId ID of collection764   * @example await getData(2)765   * @returns collection information object766   */767  async getData(collectionId: number): Promise<{768    id: number;769    name: string;770    description: string;771    tokensCount: number;772    admins: CrossAccountId[];773    normalizedOwner: TSubstrateAccount;774    raw: any775  } | null> {776    const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);777    const humanCollection = collection.toHuman(), collectionData = {778      id: collectionId, name: null, description: null, tokensCount: 0, admins: [],779      raw: humanCollection,780    } as any, jsonCollection = collection.toJSON();781    if (humanCollection === null) return null;782    collectionData.raw.limits = jsonCollection.limits;783    collectionData.raw.permissions = jsonCollection.permissions;784    collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);785    for (const key of ['name', 'description']) {786      collectionData[key] = this.helper.util.vec2str(humanCollection[key]);787    }788789    collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))790      ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)791      : 0;792    collectionData.admins = await this.getAdmins(collectionId);793794    return collectionData;795  }796797  /**798   * Get the addresses of the collection's administrators, optionally normalized.799   *800   * @param collectionId ID of collection801   * @param normalize whether to normalize the addresses to the default ss58 format802   * @example await getAdmins(1)803   * @returns array of administrators804   */805  async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {806    const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();807808    return normalize809      ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())810      : admins;811  }812813  /**814   * Get the addresses added to the collection allow-list, optionally normalized.815   * @param collectionId ID of collection816   * @param normalize whether to normalize the addresses to the default ss58 format817   * @example await getAllowList(1)818   * @returns array of allow-listed addresses819   */820  async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {821    const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();822    return normalize823      ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())824      : allowListed;825  }826827  /**828   * Get the effective limits of the collection instead of null for default values829   *830   * @param collectionId ID of collection831   * @example await getEffectiveLimits(2)832   * @returns object of collection limits833   */834  async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {835    return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();836  }837838  /**839   * Burns the collection if the signer has sufficient permissions and collection is empty.840   *841   * @param signer keyring of signer842   * @param collectionId ID of collection843   * @example await helper.collection.burn(aliceKeyring, 3);844   * @returns ```true``` if extrinsic success, otherwise ```false```845   */846  async burn(signer: TSigner, collectionId: number): Promise<boolean> {847    const result = await this.helper.executeExtrinsic(848      signer,849      'api.tx.unique.destroyCollection', [collectionId],850      true,851    );852853    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');854  }855856  /**857   * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.858   *859   * @param signer keyring of signer860   * @param collectionId ID of collection861   * @param sponsorAddress Sponsor substrate address862   * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")863   * @returns ```true``` if extrinsic success, otherwise ```false```864   */865  async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {866    const result = await this.helper.executeExtrinsic(867      signer,868      'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],869      true,870    );871872    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');873  }874875  /**876   * Confirms consent to sponsor the collection on behalf of the signer.877   *878   * @param signer keyring of signer879   * @param collectionId ID of collection880   * @example confirmSponsorship(aliceKeyring, 10)881   * @returns ```true``` if extrinsic success, otherwise ```false```882   */883  async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {884    const result = await this.helper.executeExtrinsic(885      signer,886      'api.tx.unique.confirmSponsorship', [collectionId],887      true,888    );889890    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');891  }892893  /**894   * Removes the sponsor of a collection, regardless if it consented or not.895   *896   * @param signer keyring of signer897   * @param collectionId ID of collection898   * @example removeSponsor(aliceKeyring, 10)899   * @returns ```true``` if extrinsic success, otherwise ```false```900   */901  async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {902    const result = await this.helper.executeExtrinsic(903      signer,904      'api.tx.unique.removeCollectionSponsor', [collectionId],905      true,906    );907908    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');909  }910911  /**912   * Sets the limits of the collection. At least one limit must be specified for a correct call.913   *914   * @param signer keyring of signer915   * @param collectionId ID of collection916   * @param limits collection limits object917   * @example918   * await setLimits(919   *   aliceKeyring,920   *   10,921   *   {922   *     sponsorTransferTimeout: 0,923   *     ownerCanDestroy: false924   *   }925   * )926   * @returns ```true``` if extrinsic success, otherwise ```false```927   */928  async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {929    const result = await this.helper.executeExtrinsic(930      signer,931      'api.tx.unique.setCollectionLimits', [collectionId, limits],932      true,933    );934935    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');936  }937938  /**939   * Changes the owner of the collection to the new Substrate address.940   *941   * @param signer keyring of signer942   * @param collectionId ID of collection943   * @param ownerAddress substrate address of new owner944   * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")945   * @returns ```true``` if extrinsic success, otherwise ```false```946   */947  async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {948    const result = await this.helper.executeExtrinsic(949      signer,950      'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],951      true,952    );953954    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');955  }956957  /**958   * Adds a collection administrator.959   *960   * @param signer keyring of signer961   * @param collectionId ID of collection962   * @param adminAddressObj Administrator address (substrate or ethereum)963   * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})964   * @returns ```true``` if extrinsic success, otherwise ```false```965   */966  async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {967    const result = await this.helper.executeExtrinsic(968      signer,969      'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],970      true,971    );972973    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');974  }975976  /**977   * Removes a collection administrator.978   *979   * @param signer keyring of signer980   * @param collectionId ID of collection981   * @param adminAddressObj Administrator address (substrate or ethereum)982   * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})983   * @returns ```true``` if extrinsic success, otherwise ```false```984   */985  async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {986    const result = await this.helper.executeExtrinsic(987      signer,988      'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],989      true,990    );991992    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');993  }994995  /**996   * Check if user is in allow list.997   *998   * @param collectionId ID of collection999   * @param user Account to check1000   * @example await getAdmins(1)1001   * @returns is user in allow list1002   */1003  async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {1004    return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();1005  }10061007  /**1008   * Adds an address to allow list1009   * @param signer keyring of signer1010   * @param collectionId ID of collection1011   * @param addressObj address to add to the allow list1012   * @returns ```true``` if extrinsic success, otherwise ```false```1013   */1014  async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1015    const result = await this.helper.executeExtrinsic(1016      signer,1017      'api.tx.unique.addToAllowList', [collectionId, addressObj],1018      true,1019    );10201021    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1022  }10231024  /**1025   * Removes an address from allow list1026   *1027   * @param signer keyring of signer1028   * @param collectionId ID of collection1029   * @param addressObj address to remove from the allow list1030   * @returns ```true``` if extrinsic success, otherwise ```false```1031   */1032  async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1033    const result = await this.helper.executeExtrinsic(1034      signer,1035      'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1036      true,1037    );10381039    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1040  }10411042  /**1043   * Sets onchain permissions for selected collection.1044   *1045   * @param signer keyring of signer1046   * @param collectionId ID of collection1047   * @param permissions collection permissions object1048   * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1049   * @returns ```true``` if extrinsic success, otherwise ```false```1050   */1051  async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1052    const result = await this.helper.executeExtrinsic(1053      signer,1054      'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1055      true,1056    );10571058    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1059  }10601061  /**1062   * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1063   *1064   * @param signer keyring of signer1065   * @param collectionId ID of collection1066   * @param permissions nesting permissions object1067   * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1068   * @returns ```true``` if extrinsic success, otherwise ```false```1069   */1070  async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1071    return await this.setPermissions(signer, collectionId, {nesting: permissions});1072  }10731074  /**1075   * Disables nesting for selected collection.1076   *1077   * @param signer keyring of signer1078   * @param collectionId ID of collection1079   * @example disableNesting(aliceKeyring, 10);1080   * @returns ```true``` if extrinsic success, otherwise ```false```1081   */1082  async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1083    return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1084  }10851086  /**1087   * Sets onchain properties to the collection.1088   *1089   * @param signer keyring of signer1090   * @param collectionId ID of collection1091   * @param properties array of property objects1092   * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1093   * @returns ```true``` if extrinsic success, otherwise ```false```1094   */1095  async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1096    const result = await this.helper.executeExtrinsic(1097      signer,1098      'api.tx.unique.setCollectionProperties', [collectionId, properties],1099      true,1100    );11011102    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1103  }11041105  /**1106   * Get collection properties.1107   *1108   * @param collectionId ID of collection1109   * @param propertyKeys optionally filter the returned properties to only these keys1110   * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1111   * @returns array of key-value pairs1112   */1113  async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1114    return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1115  }11161117  async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1118    const api = this.helper.getApi();1119    const props = (await api.query.common.collectionProperties(collectionId)).toJSON();11201121    return (props! as any).consumedSpace;1122  }11231124  async getCollectionOptions(collectionId: number) {1125    return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1126  }11271128  /**1129   * Deletes onchain properties from the collection.1130   *1131   * @param signer keyring of signer1132   * @param collectionId ID of collection1133   * @param propertyKeys array of property keys to delete1134   * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1135   * @returns ```true``` if extrinsic success, otherwise ```false```1136   */1137  async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1138    const result = await this.helper.executeExtrinsic(1139      signer,1140      'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1141      true,1142    );11431144    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1145  }11461147  /**1148   * Changes the owner of the token.1149   *1150   * @param signer keyring of signer1151   * @param collectionId ID of collection1152   * @param tokenId ID of token1153   * @param addressObj address of a new owner1154   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1155   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1156   * @returns true if the token success, otherwise false1157   */1158  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1159    const result = await this.helper.executeExtrinsic(1160      signer,1161      'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1162      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1163    );11641165    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1166  }11671168  /**1169   *1170   * Change ownership of a token(s) on behalf of the owner.1171   *1172   * @param signer keyring of signer1173   * @param collectionId ID of collection1174   * @param tokenId ID of token1175   * @param fromAddressObj address on behalf of which the token will be sent1176   * @param toAddressObj new token owner1177   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1178   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1179   * @returns true if the token success, otherwise false1180   */1181  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1182    const result = await this.helper.executeExtrinsic(1183      signer,1184      'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1185      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1186    );1187    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1188  }11891190  /**1191   *1192   * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1193   *1194   * @param signer keyring of signer1195   * @param collectionId ID of collection1196   * @param tokenId ID of token1197   * @param amount amount of tokens to be burned. For NFT must be set to 1n1198   * @example burnToken(aliceKeyring, 10, 5);1199   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1200   */1201  async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1202    const burnResult = await this.helper.executeExtrinsic(1203      signer,1204      'api.tx.unique.burnItem', [collectionId, tokenId, amount],1205      true, // `Unable to burn token for ${label}`,1206    );1207    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1208    if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1209    return burnedTokens.success;1210  }12111212  /**1213   * Destroys a concrete instance of NFT on behalf of the owner1214   *1215   * @param signer keyring of signer1216   * @param collectionId ID of collection1217   * @param tokenId ID of token1218   * @param fromAddressObj address on behalf of which the token will be burnt1219   * @param amount amount of tokens to be burned. For NFT must be set to 1n1220   * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1221   * @returns ```true``` if extrinsic success, otherwise ```false```1222   */1223  async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1224    const burnResult = await this.helper.executeExtrinsic(1225      signer,1226      'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1227      true, // `Unable to burn token from for ${label}`,1228    );1229    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1230    return burnedTokens.success && burnedTokens.tokens.length > 0;1231  }12321233  /**1234   * Set, change, or remove approved address to transfer the ownership of the NFT.1235   *1236   * @param signer keyring of signer1237   * @param collectionId ID of collection1238   * @param tokenId ID of token1239   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1240   * @param amount amount of token to be approved. For NFT must be set to 1n1241   * @returns ```true``` if extrinsic success, otherwise ```false```1242   */1243  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1244    const approveResult = await this.helper.executeExtrinsic(1245      signer,1246      'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1247      true, // `Unable to approve token for ${label}`,1248    );12491250    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1251  }12521253  /**1254   * Get the amount of token pieces approved to transfer or burn. Normally 0.1255   *1256   * @param collectionId ID of collection1257   * @param tokenId ID of token1258   * @param toAccountObj address which is approved to use token pieces1259   * @param fromAccountObj address which may have allowed the use of its owned tokens1260   * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1261   * @returns number of approved to transfer pieces1262   */1263  async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1264    return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1265  }12661267  /**1268   * Get the last created token ID in a collection1269   *1270   * @param collectionId ID of collection1271   * @example getLastTokenId(10);1272   * @returns id of the last created token1273   */1274  async getLastTokenId(collectionId: number): Promise<number> {1275    return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1276  }12771278  /**1279   * Check if token exists1280   *1281   * @param collectionId ID of collection1282   * @param tokenId ID of token1283   * @example doesTokenExist(10, 20);1284   * @returns true if the token exists, otherwise false1285   */1286  async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1287    return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1288  }1289}12901291class NFTnRFT extends CollectionGroup {1292  /**1293   * Get tokens owned by account1294   *1295   * @param collectionId ID of collection1296   * @param addressObj tokens owner1297   * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1298   * @returns array of token ids owned by account1299   */1300  async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1301    return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1302  }13031304  /**1305   * Get token data1306   *1307   * @param collectionId ID of collection1308   * @param tokenId ID of token1309   * @param propertyKeys optionally filter the token properties to only these keys1310   * @param blockHashAt optionally query the data at some block with this hash1311   * @example getToken(10, 5);1312   * @returns human readable token data1313   */1314  async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1315    properties: IProperty[];1316    owner: CrossAccountId;1317    normalizedOwner: CrossAccountId;1318  }| null> {1319    let tokenData;1320    if(typeof blockHashAt === 'undefined') {1321      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1322    }1323    else {1324      if(propertyKeys.length == 0) {1325        const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1326        if(!collection) return null;1327        propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1328      }1329      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1330    }1331    tokenData = tokenData.toHuman();1332    if (tokenData === null || tokenData.owner === null) return null;1333    const owner = {} as any;1334    for (const key of Object.keys(tokenData.owner)) {1335      owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1336        ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1337        : tokenData.owner[key];1338    }1339    tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1340    return tokenData;1341  }13421343  /**1344   * Set permissions to change token properties1345   *1346   * @param signer keyring of signer1347   * @param collectionId ID of collection1348   * @param permissions permissions to change a property by the collection admin or token owner1349   * @example setTokenPropertyPermissions(1350   *   aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1351   * )1352   * @returns true if extrinsic success otherwise false1353   */1354  async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1355    const result = await this.helper.executeExtrinsic(1356      signer,1357      'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1358      true,1359    );13601361    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1362  }13631364  /**1365   * Get token property permissions.1366   *1367   * @param collectionId ID of collection1368   * @param propertyKeys optionally filter the returned property permissions to only these keys1369   * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1370   * @returns array of key-permission pairs1371   */1372  async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1373    return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1374  }13751376  /**1377   * Set token properties1378   *1379   * @param signer keyring of signer1380   * @param collectionId ID of collection1381   * @param tokenId ID of token1382   * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1383   * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1384   * @returns ```true``` if extrinsic success, otherwise ```false```1385   */1386  async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1387    const result = await this.helper.executeExtrinsic(1388      signer,1389      'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1390      true,1391    );13921393    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1394  }13951396  /**1397   * Get properties, metadata assigned to a token.1398   *1399   * @param collectionId ID of collection1400   * @param tokenId ID of token1401   * @param propertyKeys optionally filter the returned properties to only these keys1402   * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1403   * @returns array of key-value pairs1404   */1405  async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1406    return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1407  }14081409  /**1410   * Delete the provided properties of a token1411   * @param signer keyring of signer1412   * @param collectionId ID of collection1413   * @param tokenId ID of token1414   * @param propertyKeys property keys to be deleted1415   * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1416   * @returns ```true``` if extrinsic success, otherwise ```false```1417   */1418  async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1419    const result = await this.helper.executeExtrinsic(1420      signer,1421      'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1422      true,1423    );14241425    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1426  }14271428  /**1429   * Mint new collection1430   *1431   * @param signer keyring of signer1432   * @param collectionOptions basic collection options and properties1433   * @param mode NFT or RFT type of a collection1434   * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1435   * @returns object of the created collection1436   */1437  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1438    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1439    collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1440    for (const key of ['name', 'description', 'tokenPrefix']) {1441      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);1442    }1443    const creationResult = await this.helper.executeExtrinsic(1444      signer,1445      'api.tx.unique.createCollectionEx', [collectionOptions],1446      true, // errorLabel,1447    );1448    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1449  }14501451  getCollectionObject(_collectionId: number): any {1452    return null;1453  }14541455  getTokenObject(_collectionId: number, _tokenId: number): any {1456    return null;1457  }14581459  /**1460   * Tells whether the given `owner` approves the `operator`.1461   * @param collectionId ID of collection1462   * @param owner owner address1463   * @param operator operator addrees1464   * @returns true if operator is enabled1465   */1466  async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1467    return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1468  }14691470  /** Sets or unsets the approval of a given operator.1471   *  The `operator` is allowed to transfer all tokens of the `caller` on their behalf.1472   *  @param operator Operator1473   *  @param approved Should operator status be granted or revoked?1474   *  @returns ```true``` if extrinsic success, otherwise ```false```1475   */1476  async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1477    const result = await this.helper.executeExtrinsic(1478      signer,1479      'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1480      true,1481    );1482    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1483  }1484}148514861487class NFTGroup extends NFTnRFT {1488  /**1489   * Get collection object1490   * @param collectionId ID of collection1491   * @example getCollectionObject(2);1492   * @returns instance of UniqueNFTCollection1493   */1494  getCollectionObject(collectionId: number): UniqueNFTCollection {1495    return new UniqueNFTCollection(collectionId, this.helper);1496  }14971498  /**1499   * Get token object1500   * @param collectionId ID of collection1501   * @param tokenId ID of token1502   * @example getTokenObject(10, 5);1503   * @returns instance of UniqueNFTToken1504   */1505  getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1506    return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1507  }15081509  /**1510   * Get token's owner1511   * @param collectionId ID of collection1512   * @param tokenId ID of token1513   * @param blockHashAt optionally query the data at the block with this hash1514   * @example getTokenOwner(10, 5);1515   * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1516   */1517  async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1518    let owner;1519    if (typeof blockHashAt === 'undefined') {1520      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1521    } else {1522      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1523    }1524    return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1525  }15261527  /**1528   * Is token approved to transfer1529   * @param collectionId ID of collection1530   * @param tokenId ID of token1531   * @param toAccountObj address to be approved1532   * @returns ```true``` if extrinsic success, otherwise ```false```1533   */1534  async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1535    return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1536  }15371538  /**1539   * Changes the owner of the token.1540   *1541   * @param signer keyring of signer1542   * @param collectionId ID of collection1543   * @param tokenId ID of token1544   * @param addressObj address of a new owner1545   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1546   * @returns ```true``` if extrinsic success, otherwise ```false```1547   */1548  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1549    return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1550  }15511552  /**1553   *1554   * Change ownership of a NFT on behalf of the owner.1555   *1556   * @param signer keyring of signer1557   * @param collectionId ID of collection1558   * @param tokenId ID of token1559   * @param fromAddressObj address on behalf of which the token will be sent1560   * @param toAddressObj new token owner1561   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1562   * @returns ```true``` if extrinsic success, otherwise ```false```1563   */1564  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1565    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1566  }15671568  /**1569   * Recursively find the address that owns the token1570   * @param collectionId ID of collection1571   * @param tokenId ID of token1572   * @param blockHashAt1573   * @example getTokenTopmostOwner(10, 5);1574   * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1575   */1576  async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1577    let owner;1578    if (typeof blockHashAt === 'undefined') {1579      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1580    } else {1581      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1582    }15831584    if (owner === null) return null;15851586    return owner.toHuman();1587  }15881589  /**1590   * Get tokens nested in the provided token1591   * @param collectionId ID of collection1592   * @param tokenId ID of token1593   * @param blockHashAt optionally query the data at the block with this hash1594   * @example getTokenChildren(10, 5);1595   * @returns tokens whose depth of nesting is <= 51596   */1597  async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1598    let children;1599    if(typeof blockHashAt === 'undefined') {1600      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1601    } else {1602      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1603    }16041605    return children.toJSON().map((x: any) => {1606      return {collectionId: x.collection, tokenId: x.token};1607    });1608  }16091610  /**1611   * Nest one token into another1612   * @param signer keyring of signer1613   * @param tokenObj token to be nested1614   * @param rootTokenObj token to be parent1615   * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1616   * @returns ```true``` if extrinsic success, otherwise ```false```1617   */1618  async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1619    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1620    const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1621    if(!result) {1622      throw Error('Unable to nest token!');1623    }1624    return result;1625  }16261627  /**1628   * Remove token from nested state1629   * @param signer keyring of signer1630   * @param tokenObj token to unnest1631   * @param rootTokenObj parent of a token1632   * @param toAddressObj address of a new token owner1633   * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1634   * @returns ```true``` if extrinsic success, otherwise ```false```1635   */1636  async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1637    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1638    const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1639    if(!result) {1640      throw Error('Unable to unnest token!');1641    }1642    return result;1643  }16441645  /**1646   * Mint new collection1647   * @param signer keyring of signer1648   * @param collectionOptions Collection options1649   * @example1650   * mintCollection(aliceKeyring, {1651   *   name: 'New',1652   *   description: 'New collection',1653   *   tokenPrefix: 'NEW',1654   * })1655   * @returns object of the created collection1656   */1657  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1658    return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1659  }16601661  /**1662   * Mint new token1663   * @param signer keyring of signer1664   * @param data token data1665   * @returns created token object1666   */1667  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1668    const creationResult = await this.helper.executeExtrinsic(1669      signer,1670      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1671        nft: {1672          properties: data.properties,1673        },1674      }],1675      true,1676    );1677    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1678    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1679    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1680    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1681  }16821683  /**1684   * Mint multiple NFT tokens1685   * @param signer keyring of signer1686   * @param collectionId ID of collection1687   * @param tokens array of tokens with owner and properties1688   * @example1689   * mintMultipleTokens(aliceKeyring, 10, [{1690   *     owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1691   *     properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1692   *   },{1693   *     owner: {Ethereum: "0x9F0583DbB855d..."},1694   *     properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1695   * }]);1696   * @returns ```true``` if extrinsic success, otherwise ```false```1697   */1698  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1699    const creationResult = await this.helper.executeExtrinsic(1700      signer,1701      'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1702      true,1703    );1704    const collection = this.getCollectionObject(collectionId);1705    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1706  }17071708  /**1709   * Mint multiple NFT tokens with one owner1710   * @param signer keyring of signer1711   * @param collectionId ID of collection1712   * @param owner tokens owner1713   * @param tokens array of tokens with owner and properties1714   * @example1715   * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1716   *   properties: [{1717   *   key: "gender",1718   *   value: "female",1719   *  },{1720   *   key: "age",1721   *   value: "33",1722   *  }],1723   * }]);1724   * @returns array of newly created tokens1725   */1726  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1727    const rawTokens = [];1728    for (const token of tokens) {1729      const raw = {NFT: {properties: token.properties}};1730      rawTokens.push(raw);1731    }1732    const creationResult = await this.helper.executeExtrinsic(1733      signer,1734      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1735      true,1736    );1737    const collection = this.getCollectionObject(collectionId);1738    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1739  }17401741  /**1742   * Set, change, or remove approved address to transfer the ownership of the NFT.1743   *1744   * @param signer keyring of signer1745   * @param collectionId ID of collection1746   * @param tokenId ID of token1747   * @param toAddressObj address to approve1748   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1749   * @returns ```true``` if extrinsic success, otherwise ```false```1750   */1751  approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1752    return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1753  }1754}175517561757class RFTGroup extends NFTnRFT {1758  /**1759   * Get collection object1760   * @param collectionId ID of collection1761   * @example getCollectionObject(2);1762   * @returns instance of UniqueRFTCollection1763   */1764  getCollectionObject(collectionId: number): UniqueRFTCollection {1765    return new UniqueRFTCollection(collectionId, this.helper);1766  }17671768  /**1769   * Get token object1770   * @param collectionId ID of collection1771   * @param tokenId ID of token1772   * @example getTokenObject(10, 5);1773   * @returns instance of UniqueNFTToken1774   */1775  getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1776    return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1777  }17781779  /**1780   * Get top 10 token owners with the largest number of pieces1781   * @param collectionId ID of collection1782   * @param tokenId ID of token1783   * @example getTokenTop10Owners(10, 5);1784   * @returns array of top 10 owners1785   */1786  async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1787    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1788  }17891790  /**1791   * Get number of pieces owned by address1792   * @param collectionId ID of collection1793   * @param tokenId ID of token1794   * @param addressObj address token owner1795   * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1796   * @returns number of pieces ownerd by address1797   */1798  async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1799    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1800  }18011802  /**1803   * Transfer pieces of token to another address1804   * @param signer keyring of signer1805   * @param collectionId ID of collection1806   * @param tokenId ID of token1807   * @param addressObj address of a new owner1808   * @param amount number of pieces to be transfered1809   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1810   * @returns ```true``` if extrinsic success, otherwise ```false```1811   */1812  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1813    return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1814  }18151816  /**1817   * Change ownership of some pieces of RFT on behalf of the owner.1818   * @param signer keyring of signer1819   * @param collectionId ID of collection1820   * @param tokenId ID of token1821   * @param fromAddressObj address on behalf of which the token will be sent1822   * @param toAddressObj new token owner1823   * @param amount number of pieces to be transfered1824   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1825   * @returns ```true``` if extrinsic success, otherwise ```false```1826   */1827  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1828    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1829  }18301831  /**1832   * Mint new collection1833   * @param signer keyring of signer1834   * @param collectionOptions Collection options1835   * @example1836   * mintCollection(aliceKeyring, {1837   *   name: 'New',1838   *   description: 'New collection',1839   *   tokenPrefix: 'NEW',1840   * })1841   * @returns object of the created collection1842   */1843  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1844    return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1845  }18461847  /**1848   * Mint new token1849   * @param signer keyring of signer1850   * @param data token data1851   * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1852   * @returns created token object1853   */1854  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1855    const creationResult = await this.helper.executeExtrinsic(1856      signer,1857      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1858        refungible: {1859          pieces: data.pieces,1860          properties: data.properties,1861        },1862      }],1863      true,1864    );1865    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1866    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1867    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1868    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1869  }18701871  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1872    throw Error('Not implemented');1873    const creationResult = await this.helper.executeExtrinsic(1874      signer,1875      'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1876      true, // `Unable to mint RFT tokens for ${label}`,1877    );1878    const collection = this.getCollectionObject(collectionId);1879    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1880  }18811882  /**1883   * Mint multiple RFT tokens with one owner1884   * @param signer keyring of signer1885   * @param collectionId ID of collection1886   * @param owner tokens owner1887   * @param tokens array of tokens with properties and pieces1888   * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1889   * @returns array of newly created RFT tokens1890   */1891  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1892    const rawTokens = [];1893    for (const token of tokens) {1894      const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1895      rawTokens.push(raw);1896    }1897    const creationResult = await this.helper.executeExtrinsic(1898      signer,1899      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1900      true,1901    );1902    const collection = this.getCollectionObject(collectionId);1903    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1904  }19051906  /**1907   * Destroys a concrete instance of RFT.1908   * @param signer keyring of signer1909   * @param collectionId ID of collection1910   * @param tokenId ID of token1911   * @param amount number of pieces to be burnt1912   * @example burnToken(aliceKeyring, 10, 5);1913   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1914   */1915  async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1916    return await super.burnToken(signer, collectionId, tokenId, amount);1917  }19181919  /**1920   * Destroys a concrete instance of RFT on behalf of the owner.1921   * @param signer keyring of signer1922   * @param collectionId ID of collection1923   * @param tokenId ID of token1924   * @param fromAddressObj address on behalf of which the token will be burnt1925   * @param amount number of pieces to be burnt1926   * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1927   * @returns ```true``` if extrinsic success, otherwise ```false```1928   */1929  async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1930    return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1931  }19321933  /**1934   * Set, change, or remove approved address to transfer the ownership of the RFT.1935   *1936   * @param signer keyring of signer1937   * @param collectionId ID of collection1938   * @param tokenId ID of token1939   * @param toAddressObj address to approve1940   * @param amount number of pieces to be approved1941   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1942   * @returns true if the token success, otherwise false1943   */1944  approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1945    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1946  }19471948  /**1949   * Get total number of pieces1950   * @param collectionId ID of collection1951   * @param tokenId ID of token1952   * @example getTokenTotalPieces(10, 5);1953   * @returns number of pieces1954   */1955  async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1956    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1957  }19581959  /**1960   * Change number of token pieces. Signer must be the owner of all token pieces.1961   * @param signer keyring of signer1962   * @param collectionId ID of collection1963   * @param tokenId ID of token1964   * @param amount new number of pieces1965   * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1966   * @returns true if the repartion was success, otherwise false1967   */1968  async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1969    const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1970    const repartitionResult = await this.helper.executeExtrinsic(1971      signer,1972      'api.tx.unique.repartition', [collectionId, tokenId, amount],1973      true,1974    );1975    if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1976    return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1977  }1978}197919801981class FTGroup extends CollectionGroup {1982  /**1983   * Get collection object1984   * @param collectionId ID of collection1985   * @example getCollectionObject(2);1986   * @returns instance of UniqueFTCollection1987   */1988  getCollectionObject(collectionId: number): UniqueFTCollection {1989    return new UniqueFTCollection(collectionId, this.helper);1990  }19911992  /**1993   * Mint new fungible collection1994   * @param signer keyring of signer1995   * @param collectionOptions Collection options1996   * @param decimalPoints number of token decimals1997   * @example1998   * mintCollection(aliceKeyring, {1999   *   name: 'New',2000   *   description: 'New collection',2001   *   tokenPrefix: 'NEW',2002   * }, 18)2003   * @returns newly created fungible collection2004   */2005  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {2006    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object2007    if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');2008    collectionOptions.mode = {fungible: decimalPoints};2009    for (const key of ['name', 'description', 'tokenPrefix']) {2010      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);2011    }2012    const creationResult = await this.helper.executeExtrinsic(2013      signer,2014      'api.tx.unique.createCollectionEx', [collectionOptions],2015      true,2016    );2017    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2018  }20192020  /**2021   * Mint tokens2022   * @param signer keyring of signer2023   * @param collectionId ID of collection2024   * @param owner address owner of new tokens2025   * @param amount amount of tokens to be meanted2026   * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);2027   * @returns ```true``` if extrinsic success, otherwise ```false```2028   */2029  async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2030    const creationResult = await this.helper.executeExtrinsic(2031      signer,2032      'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2033        fungible: {2034          value: amount,2035        },2036      }],2037      true, // `Unable to mint fungible tokens for ${label}`,2038    );2039    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2040  }20412042  /**2043   * Mint multiple Fungible tokens with one owner2044   * @param signer keyring of signer2045   * @param collectionId ID of collection2046   * @param owner tokens owner2047   * @param tokens array of tokens with properties and pieces2048   * @returns ```true``` if extrinsic success, otherwise ```false```2049   */2050  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {2051    const rawTokens = [];2052    for (const token of tokens) {2053      const raw = {Fungible: {Value: token.value}};2054      rawTokens.push(raw);2055    }2056    const creationResult = await this.helper.executeExtrinsic(2057      signer,2058      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2059      true,2060    );2061    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2062  }20632064  /**2065   * Get the top 10 owners with the largest balance for the Fungible collection2066   * @param collectionId ID of collection2067   * @example getTop10Owners(10);2068   * @returns array of ```ICrossAccountId```2069   */2070  async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2071    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2072  }20732074  /**2075   * Get account balance2076   * @param collectionId ID of collection2077   * @param addressObj address of owner2078   * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2079   * @returns amount of fungible tokens owned by address2080   */2081  async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2082    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2083  }20842085  /**2086   * Transfer tokens to address2087   * @param signer keyring of signer2088   * @param collectionId ID of collection2089   * @param toAddressObj address recipient2090   * @param amount amount of tokens to be sent2091   * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2092   * @returns ```true``` if extrinsic success, otherwise ```false```2093   */2094  async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2095    return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2096  }20972098  /**2099   * Transfer some tokens on behalf of the owner.2100   * @param signer keyring of signer2101   * @param collectionId ID of collection2102   * @param fromAddressObj address on behalf of which tokens will be sent2103   * @param toAddressObj address where token to be sent2104   * @param amount number of tokens to be sent2105   * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2106   * @returns ```true``` if extrinsic success, otherwise ```false```2107   */2108  async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2109    return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2110  }21112112  /**2113   * Destroy some amount of tokens2114   * @param signer keyring of signer2115   * @param collectionId ID of collection2116   * @param amount amount of tokens to be destroyed2117   * @example burnTokens(aliceKeyring, 10, 1000n);2118   * @returns ```true``` if extrinsic success, otherwise ```false```2119   */2120  async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2121    return await super.burnToken(signer, collectionId, 0, amount);2122  }21232124  /**2125   * Burn some tokens on behalf of the owner.2126   * @param signer keyring of signer2127   * @param collectionId ID of collection2128   * @param fromAddressObj address on behalf of which tokens will be burnt2129   * @param amount amount of tokens to be burnt2130   * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2131   * @returns ```true``` if extrinsic success, otherwise ```false```2132   */2133  async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2134    return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2135  }21362137  /**2138   * Get total collection supply2139   * @param collectionId2140   * @returns2141   */2142  async getTotalPieces(collectionId: number): Promise<bigint> {2143    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2144  }21452146  /**2147   * Set, change, or remove approved address to transfer tokens.2148   *2149   * @param signer keyring of signer2150   * @param collectionId ID of collection2151   * @param toAddressObj address to be approved2152   * @param amount amount of tokens to be approved2153   * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2154   * @returns ```true``` if extrinsic success, otherwise ```false```2155   */2156  approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2157    return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2158  }21592160  /**2161   * Get amount of fungible tokens approved to transfer2162   * @param collectionId ID of collection2163   * @param fromAddressObj owner of tokens2164   * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2165   * @returns number of tokens approved for the transfer2166   */2167  getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2168    return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2169  }2170}217121722173class ChainGroup extends HelperGroup<ChainHelperBase> {2174  /**2175   * Get system properties of a chain2176   * @example getChainProperties();2177   * @returns ss58Format, token decimals, and token symbol2178   */2179  getChainProperties(): IChainProperties {2180    const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2181    return {2182      ss58Format: properties.ss58Format.toJSON(),2183      tokenDecimals: properties.tokenDecimals.toJSON(),2184      tokenSymbol: properties.tokenSymbol.toJSON(),2185    };2186  }21872188  /**2189   * Get chain header2190   * @example getLatestBlockNumber();2191   * @returns the number of the last block2192   */2193  async getLatestBlockNumber(): Promise<number> {2194    return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2195  }21962197  /**2198   * Get block hash by block number2199   * @param blockNumber number of block2200   * @example getBlockHashByNumber(12345);2201   * @returns hash of a block2202   */2203  async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2204    const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2205    if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2206    return blockHash;2207  }22082209  // TODO add docs2210  async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2211    const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2212    if (!blockHash) return null;2213    return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2214  }22152216  /**2217   * Get latest relay block2218   * @returns {number} relay block2219   */2220  async getRelayBlockNumber(): Promise<bigint> {2221    const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2222    return BigInt(blockNumber);2223  }22242225  /**2226   * Get account nonce2227   * @param address substrate address2228   * @example getNonce("5GrwvaEF5zXb26Fz...");2229   * @returns number, account's nonce2230   */2231  async getNonce(address: TSubstrateAccount): Promise<number> {2232    return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2233  }2234}22352236class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2237  /**2238 * Get substrate address balance2239 * @param address substrate address2240 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2241 * @returns amount of tokens on address2242 */2243  async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2244    return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2245  }22462247  /**2248   * Transfer tokens to substrate address2249   * @param signer keyring of signer2250   * @param address substrate address of a recipient2251   * @param amount amount of tokens to be transfered2252   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2253   * @returns ```true``` if extrinsic success, otherwise ```false```2254   */2255  async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2256    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}`*/);22572258    let transfer = {from: null, to: null, amount: 0n} as any;2259    result.result.events.forEach(({event: {data, method, section}}) => {2260      if ((section === 'balances') && (method === 'Transfer')) {2261        transfer = {2262          from: this.helper.address.normalizeSubstrate(data[0]),2263          to: this.helper.address.normalizeSubstrate(data[1]),2264          amount: BigInt(data[2]),2265        };2266      }2267    });2268    const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2269      && this.helper.address.normalizeSubstrate(address) === transfer.to2270      && BigInt(amount) === transfer.amount;2271    return isSuccess;2272  }22732274  /**2275   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2276   * @param address substrate address2277   * @returns2278   */2279  async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2280    const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2281    return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2282  }22832284  async getLocked(address: TSubstrateAccount): Promise<[{id: string, amount: bigint, reason: string}]> {2285    const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2286    return locks.map((lock: any) => {return {id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons};});2287  }2288}22892290class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2291  /**2292   * Get ethereum address balance2293   * @param address ethereum address2294   * @example getEthereum("0x9F0583DbB855d...")2295   * @returns amount of tokens on address2296   */2297  async getEthereum(address: TEthereumAccount): Promise<bigint> {2298    return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2299  }23002301  /**2302   * Transfer tokens to address2303   * @param signer keyring of signer2304   * @param address Ethereum address of a recipient2305   * @param amount amount of tokens to be transfered2306   * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2307   * @returns ```true``` if extrinsic success, otherwise ```false```2308   */2309  async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2310    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);23112312    let transfer = {from: null, to: null, amount: 0n} as any;2313    result.result.events.forEach(({event: {data, method, section}}) => {2314      if ((section === 'balances') && (method === 'Transfer')) {2315        transfer = {2316          from: data[0].toString(),2317          to: data[1].toString(),2318          amount: BigInt(data[2]),2319        };2320      }2321    });2322    const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2323      && address === transfer.to2324      && BigInt(amount) === transfer.amount;2325    return isSuccess;2326  }2327}23282329class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2330  subBalanceGroup: SubstrateBalanceGroup<T>;2331  ethBalanceGroup: EthereumBalanceGroup<T>;23322333  constructor(helper: T) {2334    super(helper);2335    this.subBalanceGroup = new SubstrateBalanceGroup(helper);2336    this.ethBalanceGroup = new EthereumBalanceGroup(helper);2337  }23382339  getCollectionCreationPrice(): bigint {2340    return 2n * this.getOneTokenNominal();2341  }2342  /**2343   * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2344   * @example getOneTokenNominal()2345   * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2346   */2347  getOneTokenNominal(): bigint {2348    const chainProperties = this.helper.chain.getChainProperties();2349    return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2350  }23512352  /**2353   * Get substrate address balance2354   * @param address substrate address2355   * @example getSubstrate("5GrwvaEF5zXb26Fz...")2356   * @returns amount of tokens on address2357   */2358  getSubstrate(address: TSubstrateAccount): Promise<bigint> {2359    return this.subBalanceGroup.getSubstrate(address);2360  }23612362  /**2363   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2364   * @param address substrate address2365   * @returns2366   */2367  getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2368    return this.subBalanceGroup.getSubstrateFull(address);2369  }23702371  /**2372   * Get locked balances2373   * @param address substrate address2374   * @returns locked balances with reason via api.query.balances.locks2375   */2376  getLocked(address: TSubstrateAccount) {2377    return this.subBalanceGroup.getLocked(address);2378  }23792380  /**2381   * Get ethereum address balance2382   * @param address ethereum address2383   * @example getEthereum("0x9F0583DbB855d...")2384   * @returns amount of tokens on address2385   */2386  getEthereum(address: TEthereumAccount): Promise<bigint> {2387    return this.ethBalanceGroup.getEthereum(address);2388  }23892390  /**2391   * Transfer tokens to substrate address2392   * @param signer keyring of signer2393   * @param address substrate address of a recipient2394   * @param amount amount of tokens to be transfered2395   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2396   * @returns ```true``` if extrinsic success, otherwise ```false```2397   */2398  transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2399    return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2400  }24012402  async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2403    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);24042405    let transfer = {from: null, to: null, amount: 0n} as any;2406    result.result.events.forEach(({event: {data, method, section}}) => {2407      if ((section === 'balances') && (method === 'Transfer')) {2408        transfer = {2409          from: this.helper.address.normalizeSubstrate(data[0]),2410          to: this.helper.address.normalizeSubstrate(data[1]),2411          amount: BigInt(data[2]),2412        };2413      }2414    });2415    let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2416    isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2417    isSuccess = isSuccess && BigInt(amount) === transfer.amount;2418    return isSuccess;2419  }24202421  /**2422   * Transfer tokens with the unlock period2423   * @param signer signers Keyring2424   * @param address Substrate address of recipient2425   * @param schedule Schedule params2426   * @example vestedTransfer(signer, recepient.address, 20000, 100, 10, 50 * nominal); // total amount of vested tokens will be 100 * 50 = 50002427   */2428  async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: {start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}): Promise<void> {2429    const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2430    const event = result.result.events2431      .find(e => e.event.section === 'vesting' &&2432            e.event.method === 'VestingScheduleAdded' &&2433            e.event.data[0].toHuman() === signer.address);2434    if (!event) throw Error('Cannot find transfer in events');2435  }24362437  /**2438   * Get schedule for recepient of vested transfer2439   * @param address Substrate address of recipient2440   * @returns2441   */2442  async getVestingSchedules(address: TSubstrateAccount): Promise<{start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}[]> {2443    const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2444    return schedule.map((schedule: any) => {2445      return {2446        start: BigInt(schedule.start),2447        period: BigInt(schedule.period),2448        periodCount: BigInt(schedule.periodCount),2449        perPeriod: BigInt(schedule.perPeriod),2450      };2451    });2452  }24532454  /**2455   * Claim vested tokens2456   * @param signer signers Keyring2457   */2458  async claim(signer: TSigner) {2459    const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2460    const event = result.result.events2461      .find(e => e.event.section === 'vesting' &&2462            e.event.method === 'Claimed' &&2463            e.event.data[0].toHuman() === signer.address);2464    if (!event) throw Error('Cannot find claim in events');2465  }2466}24672468class AddressGroup extends HelperGroup<ChainHelperBase> {2469  /**2470   * Normalizes the address to the specified ss58 format, by default ```42```.2471   * @param address substrate address2472   * @param ss58Format format for address conversion, by default ```42```2473   * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2474   * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2475   */2476  normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2477    return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2478  }24792480  /**2481   * Get address in the connected chain format2482   * @param address substrate address2483   * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2484   * @returns address in chain format2485   */2486  normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2487    return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2488  }24892490  /**2491   * Get substrate mirror of an ethereum address2492   * @param ethAddress ethereum address2493   * @param toChainFormat false for normalized account2494   * @example ethToSubstrate('0x9F0583DbB855d...')2495   * @returns substrate mirror of a provided ethereum address2496   */2497  ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2498    return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2499  }25002501  /**2502   * Get ethereum mirror of a substrate address2503   * @param subAddress substrate account2504   * @example substrateToEth("5DnSF6RRjwteE3BrC...")2505   * @returns ethereum mirror of a provided substrate address2506   */2507  substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2508    return CrossAccountId.translateSubToEth(subAddress);2509  }25102511  /**2512   * Encode key to substrate address2513   * @param key key for encoding address2514   * @param ss58Format prefix for encoding to the address of the corresponding network2515   * @returns encoded substrate address2516   */2517  encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2518    const u8a :Uint8Array = typeof key === 'string'2519      ? hexToU8a(key)2520      : typeof key === 'bigint'2521        ? hexToU8a(key.toString(16))2522        : key;25232524    if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2525      throw new Error(`ss58Format is not valid, received ${typeof ss58Format} "${ss58Format}"`);2526    }25272528    const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2529    if (!allowedDecodedLengths.includes(u8a.length)) {2530      throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2531    }25322533    const u8aPrefix = ss58Format < 642534      ? new Uint8Array([ss58Format])2535      : new Uint8Array([2536        ((ss58Format & 0xfc) >> 2) | 0x40,2537        (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2538      ]);25392540    const input = u8aConcat(u8aPrefix, u8a);25412542    return base58Encode(u8aConcat(2543      input,2544      blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2545    ));2546  }25472548  /**2549   * Restore substrate address from bigint representation2550   * @param number decimal representation of substrate address2551   * @returns substrate address2552   */2553  restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2554    if (this.helper.api === null) {2555      throw 'Not connected';2556    }2557    const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2558    if (res === undefined || res === null) {2559      throw 'Restore address error';2560    }2561    return res.toString();2562  }25632564  /**2565   * Convert etherium cross account id to substrate cross account id2566   * @param ethCrossAccount etherium cross account2567   * @returns substrate cross account id2568   */2569  convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2570    if (ethCrossAccount.sub === '0') {2571      return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2572    }25732574    const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2575    return {Substrate: ss58};2576  }25772578  paraSiblingSovereignAccount(paraid: number) {2579    // We are getting a *sibling* parachain sovereign account,2580    // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2581    const siblingPrefix = '0x7369626c';25822583    const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2584    const suffix = '000000000000000000000000000000000000000000000000';25852586    return siblingPrefix + encodedParaId + suffix;2587  }2588}25892590class StakingGroup extends HelperGroup<UniqueHelper> {2591  /**2592   * Stake tokens for App Promotion2593   * @param signer keyring of signer2594   * @param amountToStake amount of tokens to stake2595   * @param label extra label for log2596   * @returns2597   */2598  async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2599    if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2600    const _stakeResult = await this.helper.executeExtrinsic(2601      signer, 'api.tx.appPromotion.stake',2602      [amountToStake], true,2603    );2604    // TODO extract info from stakeResult2605    return true;2606  }26072608  /**2609   * Unstake tokens for App Promotion2610   * @param signer keyring of signer2611   * @param amountToUnstake amount of tokens to unstake2612   * @param label extra label for log2613   * @returns block number where balances will be unlocked2614   */2615  async unstake(signer: TSigner, label?: string): Promise<number> {2616    if(typeof label === 'undefined') label = `${signer.address}`;2617    const _unstakeResult = await this.helper.executeExtrinsic(2618      signer, 'api.tx.appPromotion.unstake',2619      [], true,2620    );2621    // TODO extract block number fron events2622    return 1;2623  }26242625  /**2626   * Get total staked amount for address2627   * @param address substrate or ethereum address2628   * @returns total staked amount2629   */2630  async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2631    if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2632    return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2633  }26342635  /**2636   * Get total staked per block2637   * @param address substrate or ethereum address2638   * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2639   */2640  async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2641    const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2642    return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2643      return {2644        block: block.toBigInt(),2645        amount: amount.toBigInt(),2646      };2647    });2648  }26492650  /**2651   * Get total pending unstake amount for address2652   * @param address substrate or ethereum address2653   * @returns total pending unstake amount2654   */2655  async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2656    return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2657  }26582659  /**2660   * Get pending unstake amount per block for address2661   * @param address substrate or ethereum address2662   * @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 block2663   */2664  async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2665    const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2666    const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2667      return {2668        block: block.toBigInt(),2669        amount: amount.toBigInt(),2670      };2671    });2672    return result;2673  }2674}26752676class SchedulerGroup extends HelperGroup<UniqueHelper> {2677  constructor(helper: UniqueHelper) {2678    super(helper);2679  }26802681  cancelScheduled(signer: TSigner, scheduledId: string) {2682    return this.helper.executeExtrinsic(2683      signer,2684      'api.tx.scheduler.cancelNamed',2685      [scheduledId],2686      true,2687    );2688  }26892690  changePriority(signer: TSigner, scheduledId: string, priority: number) {2691    return this.helper.executeExtrinsic(2692      signer,2693      'api.tx.scheduler.changeNamedPriority',2694      [scheduledId, priority],2695      true,2696    );2697  }26982699  scheduleAt<T extends UniqueHelper>(2700    executionBlockNumber: number,2701    options: ISchedulerOptions = {},2702  ) {2703    return this.schedule<T>('schedule', executionBlockNumber, options);2704  }27052706  scheduleAfter<T extends UniqueHelper>(2707    blocksBeforeExecution: number,2708    options: ISchedulerOptions = {},2709  ) {2710    return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2711  }27122713  schedule<T extends UniqueHelper>(2714    scheduleFn: 'schedule' | 'scheduleAfter',2715    blocksNum: number,2716    options: ISchedulerOptions = {},2717  ) {2718    // eslint-disable-next-line @typescript-eslint/naming-convention2719    const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2720    return this.helper.clone(ScheduledHelperType, {2721      scheduleFn,2722      blocksNum,2723      options,2724    }) as T;2725  }2726}27272728class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2729  async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2730    await this.helper.executeExtrinsic(2731      signer,2732      'api.tx.foreignAssets.registerForeignAsset',2733      [ownerAddress, location, metadata],2734      true,2735    );2736  }27372738  async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2739    await this.helper.executeExtrinsic(2740      signer,2741      'api.tx.foreignAssets.updateForeignAsset',2742      [foreignAssetId, location, metadata],2743      true,2744    );2745  }2746}27472748class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2749  palletName: string;27502751  constructor(helper: T, palletName: string) {2752    super(helper);27532754    this.palletName = palletName;2755  }27562757  async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {2758    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);2759  }27602761  async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {2762    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);2763  }27642765  async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint) {2766    const destination = {2767      V1: {2768        parents: 0,2769        interior: {2770          X1: {2771            Parachain: destinationParaId,2772          },2773        },2774      },2775    };27762777    const beneficiary = {2778      V1: {2779        parents: 0,2780        interior: {2781          X1: {2782            AccountId32: {2783              network: 'Any',2784              id: targetAccount,2785            },2786          },2787        },2788      },2789    };27902791    const assets = {2792      V1: [2793        {2794          id: {2795            Concrete: {2796              parents: 0,2797              interior: 'Here',2798            },2799          },2800          fun: {2801            Fungible: amount,2802          },2803        },2804      ],2805    };28062807    const feeAssetItem = 0;28082809    await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);2810  }2811}28122813class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2814  async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {2815    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2816  }28172818  async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {2819    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2820  }28212822  async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {2823    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2824  }2825}28262827class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2828  async accounts(address: string, currencyId: any) {2829    const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2830    return BigInt(free);2831  }2832}28332834class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2835  async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2836    await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2837  }28382839  async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2840    await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2841  }28422843  async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2844    await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2845  }28462847  async account(assetId: string | number, address: string) {2848    const accountAsset = (2849      await this.helper.callRpc('api.query.assets.account', [assetId, address])2850    ).toJSON()! as any;28512852    if (accountAsset !== null) {2853      return BigInt(accountAsset['balance']);2854    } else {2855      return null;2856    }2857  }2858}28592860class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2861  async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2862    await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2863  }2864}28652866class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2867  makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2868    const apiPrefix = 'api.tx.assetManager.';28692870    const registerTx = this.helper.constructApiCall(2871      apiPrefix + 'registerForeignAsset',2872      [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2873    );28742875    const setUnitsTx = this.helper.constructApiCall(2876      apiPrefix + 'setAssetUnitsPerSecond',2877      [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2878    );28792880    const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2881    const encodedProposal = batchCall?.method.toHex() || '';2882    return encodedProposal;2883  }28842885  async assetTypeId(location: any) {2886    return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2887  }2888}28892890class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2891  notePreimagePallet: string;28922893  constructor(helper: MoonbeamHelper, options: {[key: string]: any} = {}) {2894    super(helper);2895    this.notePreimagePallet = options.notePreimagePallet;2896  }28972898  async notePreimage(signer: TSigner, encodedProposal: string) {2899    await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);2900  }29012902  externalProposeMajority(proposal: any) {2903    return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);2904  }29052906  fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2907    return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2908  }29092910  async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2911    await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2912  }2913}29142915class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2916  collective: string;29172918  constructor(helper: MoonbeamHelper, collective: string) {2919    super(helper);29202921    this.collective = collective;2922  }29232924  async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2925    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2926  }29272928  async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2929    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2930  }29312932  async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {2933    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2934  }29352936  async proposalCount() {2937    return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2938  }2939}29402941export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2942export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;29432944export class UniqueHelper extends ChainHelperBase {2945  balance: BalanceGroup<UniqueHelper>;2946  collection: CollectionGroup;2947  nft: NFTGroup;2948  rft: RFTGroup;2949  ft: FTGroup;2950  staking: StakingGroup;2951  scheduler: SchedulerGroup;2952  foreignAssets: ForeignAssetsGroup;2953  xcm: XcmGroup<UniqueHelper>;2954  xTokens: XTokensGroup<UniqueHelper>;2955  tokens: TokensGroup<UniqueHelper>;29562957  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2958    super(logger, options.helperBase ?? UniqueHelper);29592960    this.balance = new BalanceGroup(this);2961    this.collection = new CollectionGroup(this);2962    this.nft = new NFTGroup(this);2963    this.rft = new RFTGroup(this);2964    this.ft = new FTGroup(this);2965    this.staking = new StakingGroup(this);2966    this.scheduler = new SchedulerGroup(this);2967    this.foreignAssets = new ForeignAssetsGroup(this);2968    this.xcm = new XcmGroup(this, 'polkadotXcm');2969    this.xTokens = new XTokensGroup(this);2970    this.tokens = new TokensGroup(this);2971  }29722973  getSudo<T extends UniqueHelper>() {2974    // eslint-disable-next-line @typescript-eslint/naming-convention2975    const SudoHelperType = SudoHelper(this.helperBase);2976    return this.clone(SudoHelperType) as T;2977  }2978}29792980export class XcmChainHelper extends ChainHelperBase {2981  async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2982    const wsProvider = new WsProvider(wsEndpoint);2983    this.api = new ApiPromise({2984      provider: wsProvider,2985    });2986    await this.api.isReadyOrError;2987    this.network = await UniqueHelper.detectNetwork(this.api);2988  }2989}29902991export class RelayHelper extends XcmChainHelper {2992  balance: SubstrateBalanceGroup<RelayHelper>;2993  xcm: XcmGroup<RelayHelper>;29942995  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2996    super(logger, options.helperBase ?? RelayHelper);29972998    this.balance = new SubstrateBalanceGroup(this);2999    this.xcm = new XcmGroup(this, 'xcmPallet');3000  }3001}30023003export class WestmintHelper extends XcmChainHelper {3004  balance: SubstrateBalanceGroup<WestmintHelper>;3005  xcm: XcmGroup<WestmintHelper>;3006  assets: AssetsGroup<WestmintHelper>;3007  xTokens: XTokensGroup<WestmintHelper>;30083009  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3010    super(logger, options.helperBase ?? WestmintHelper);30113012    this.balance = new SubstrateBalanceGroup(this);3013    this.xcm = new XcmGroup(this, 'polkadotXcm');3014    this.assets = new AssetsGroup(this);3015    this.xTokens = new XTokensGroup(this);3016  }3017}30183019export class MoonbeamHelper extends XcmChainHelper {3020  balance: EthereumBalanceGroup<MoonbeamHelper>;3021  assetManager: MoonbeamAssetManagerGroup;3022  assets: AssetsGroup<MoonbeamHelper>;3023  xTokens: XTokensGroup<MoonbeamHelper>;3024  democracy: MoonbeamDemocracyGroup;3025  collective: {3026    council: MoonbeamCollectiveGroup,3027    techCommittee: MoonbeamCollectiveGroup,3028  };30293030  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3031    super(logger, options.helperBase ?? MoonbeamHelper);30323033    this.balance = new EthereumBalanceGroup(this);3034    this.assetManager = new MoonbeamAssetManagerGroup(this);3035    this.assets = new AssetsGroup(this);3036    this.xTokens = new XTokensGroup(this);3037    this.democracy = new MoonbeamDemocracyGroup(this, options);3038    this.collective = {3039      council: new MoonbeamCollectiveGroup(this, 'councilCollective'),3040      techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),3041    };3042  }3043}30443045export class AcalaHelper extends XcmChainHelper {3046  balance: SubstrateBalanceGroup<AcalaHelper>;3047  assetRegistry: AcalaAssetRegistryGroup;3048  xTokens: XTokensGroup<AcalaHelper>;3049  tokens: TokensGroup<AcalaHelper>;30503051  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3052    super(logger, options.helperBase ?? AcalaHelper);30533054    this.balance = new SubstrateBalanceGroup(this);3055    this.assetRegistry = new AcalaAssetRegistryGroup(this);3056    this.xTokens = new XTokensGroup(this);3057    this.tokens = new TokensGroup(this);3058  }30593060  getSudo<T extends AcalaHelper>() {3061    // eslint-disable-next-line @typescript-eslint/naming-convention3062    const SudoHelperType = SudoHelper(this.helperBase);3063    return this.clone(SudoHelperType) as T;3064  }3065}30663067// eslint-disable-next-line @typescript-eslint/naming-convention3068function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3069  return class extends Base {3070    scheduleFn: 'schedule' | 'scheduleAfter';3071    blocksNum: number;3072    options: ISchedulerOptions;30733074    constructor(...args: any[]) {3075      const logger = args[0] as ILogger;3076      const options = args[1] as {3077        scheduleFn: 'schedule' | 'scheduleAfter',3078        blocksNum: number,3079        options: ISchedulerOptions3080      };30813082      super(logger);30833084      this.scheduleFn = options.scheduleFn;3085      this.blocksNum = options.blocksNum;3086      this.options = options.options;3087    }30883089    executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3090      const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);30913092      const mandatorySchedArgs = [3093        this.blocksNum,3094        this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3095        this.options.priority ?? null,3096        scheduledTx,3097      ];30983099      let schedArgs;3100      let scheduleFn;31013102      if (this.options.scheduledId) {3103        schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];31043105        if (this.scheduleFn == 'schedule') {3106          scheduleFn = 'scheduleNamed';3107        } else if (this.scheduleFn == 'scheduleAfter') {3108          scheduleFn = 'scheduleNamedAfter';3109        }3110      } else {3111        schedArgs = mandatorySchedArgs;3112        scheduleFn = this.scheduleFn;3113      }31143115      const extrinsic = 'api.tx.scheduler.' +  scheduleFn;31163117      return super.executeExtrinsic(3118        sender,3119        extrinsic,3120        schedArgs,3121        expectSuccess,3122      );3123    }3124  };3125}31263127// eslint-disable-next-line @typescript-eslint/naming-convention3128function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3129  return class extends Base {3130    constructor(...args: any[]) {3131      super(...args);3132    }31333134    executeExtrinsic (3135      sender: IKeyringPair,3136      extrinsic: string,3137      params: any[],3138      expectSuccess?: boolean,3139    ): Promise<ITransactionResult> {3140      const call = this.constructApiCall(extrinsic, params);3141      return super.executeExtrinsic(3142        sender,3143        'api.tx.sudo.sudo',3144        [call],3145        expectSuccess,3146      );3147    }3148  };3149}31503151export class UniqueBaseCollection {3152  helper: UniqueHelper;3153  collectionId: number;31543155  constructor(collectionId: number, uniqueHelper: UniqueHelper) {3156    this.collectionId = collectionId;3157    this.helper = uniqueHelper;3158  }31593160  async getData() {3161    return await this.helper.collection.getData(this.collectionId);3162  }31633164  async getLastTokenId() {3165    return await this.helper.collection.getLastTokenId(this.collectionId);3166  }31673168  async doesTokenExist(tokenId: number) {3169    return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3170  }31713172  async getAdmins() {3173    return await this.helper.collection.getAdmins(this.collectionId);3174  }31753176  async getAllowList() {3177    return await this.helper.collection.getAllowList(this.collectionId);3178  }31793180  async getEffectiveLimits() {3181    return await this.helper.collection.getEffectiveLimits(this.collectionId);3182  }31833184  async getProperties(propertyKeys?: string[] | null) {3185    return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3186  }31873188  async getPropertiesConsumedSpace() {3189    return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3190  }31913192  async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3193    return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3194  }31953196  async getOptions() {3197    return await this.helper.collection.getCollectionOptions(this.collectionId);3198  }31993200  async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3201    return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3202  }32033204  async confirmSponsorship(signer: TSigner) {3205    return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3206  }32073208  async removeSponsor(signer: TSigner) {3209    return await this.helper.collection.removeSponsor(signer, this.collectionId);3210  }32113212  async setLimits(signer: TSigner, limits: ICollectionLimits) {3213    return await this.helper.collection.setLimits(signer, this.collectionId, limits);3214  }32153216  async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3217    return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3218  }32193220  async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3221    return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3222  }32233224  async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3225    return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3226  }32273228  async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3229    return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3230  }32313232  async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3233    return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3234  }32353236  async setProperties(signer: TSigner, properties: IProperty[]) {3237    return await this.helper.collection.setProperties(signer, this.collectionId, properties);3238  }32393240  async deleteProperties(signer: TSigner, propertyKeys: string[]) {3241    return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3242  }32433244  async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3245    return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3246  }32473248  async enableNesting(signer: TSigner, permissions: INestingPermissions) {3249    return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3250  }32513252  async disableNesting(signer: TSigner) {3253    return await this.helper.collection.disableNesting(signer, this.collectionId);3254  }32553256  async burn(signer: TSigner) {3257    return await this.helper.collection.burn(signer, this.collectionId);3258  }32593260  scheduleAt<T extends UniqueHelper>(3261    executionBlockNumber: number,3262    options: ISchedulerOptions = {},3263  ) {3264    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3265    return new UniqueBaseCollection(this.collectionId, scheduledHelper);3266  }32673268  scheduleAfter<T extends UniqueHelper>(3269    blocksBeforeExecution: number,3270    options: ISchedulerOptions = {},3271  ) {3272    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3273    return new UniqueBaseCollection(this.collectionId, scheduledHelper);3274  }32753276  getSudo<T extends UniqueHelper>() {3277    return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3278  }3279}328032813282export class UniqueNFTCollection extends UniqueBaseCollection {3283  getTokenObject(tokenId: number) {3284    return new UniqueNFToken(tokenId, this);3285  }32863287  async getTokensByAddress(addressObj: ICrossAccountId) {3288    return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3289  }32903291  async getToken(tokenId: number, blockHashAt?: string) {3292    return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3293  }32943295  async getTokenOwner(tokenId: number, blockHashAt?: string) {3296    return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3297  }32983299  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3300    return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3301  }33023303  async getTokenChildren(tokenId: number, blockHashAt?: string) {3304    return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3305  }33063307  async getPropertyPermissions(propertyKeys: string[] | null = null) {3308    return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3309  }33103311  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3312    return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3313  }33143315  async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3316    const api = this.helper.getApi();3317    const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();33183319    return (props! as any).consumedSpace;3320  }33213322  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3323    return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3324  }33253326  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3327    return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3328  }33293330  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3331    return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3332  }33333334  async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3335    return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3336  }33373338  async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3339    return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3340  }33413342  async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3343    return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3344  }33453346  async burnToken(signer: TSigner, tokenId: number) {3347    return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3348  }33493350  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3351    return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3352  }33533354  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3355    return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3356  }33573358  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3359    return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3360  }33613362  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3363    return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3364  }33653366  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3367    return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3368  }33693370  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3371    return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3372  }33733374  scheduleAt<T extends UniqueHelper>(3375    executionBlockNumber: number,3376    options: ISchedulerOptions = {},3377  ) {3378    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3379    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3380  }33813382  scheduleAfter<T extends UniqueHelper>(3383    blocksBeforeExecution: number,3384    options: ISchedulerOptions = {},3385  ) {3386    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3387    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3388  }33893390  getSudo<T extends UniqueHelper>() {3391    return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3392  }3393}339433953396export class UniqueRFTCollection extends UniqueBaseCollection {3397  getTokenObject(tokenId: number) {3398    return new UniqueRFToken(tokenId, this);3399  }34003401  async getToken(tokenId: number, blockHashAt?: string) {3402    return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3403  }34043405  async getTokensByAddress(addressObj: ICrossAccountId) {3406    return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3407  }34083409  async getTop10TokenOwners(tokenId: number) {3410    return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3411  }34123413  async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3414    return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3415  }34163417  async getTokenTotalPieces(tokenId: number) {3418    return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3419  }34203421  async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3422    return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3423  }34243425  async getPropertyPermissions(propertyKeys: string[] | null = null) {3426    return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3427  }34283429  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3430    return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3431  }34323433  async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3434    const api = this.helper.getApi();3435    const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();34363437    return (props! as any).consumedSpace;3438  }34393440  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3441    return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3442  }34433444  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3445    return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3446  }34473448  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3449    return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3450  }34513452  async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3453    return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3454  }34553456  async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3457    return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3458  }34593460  async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3461    return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3462  }34633464  async burnToken(signer: TSigner, tokenId: number, amount=1n) {3465    return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3466  }34673468  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId,  amount=1n) {3469    return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3470  }34713472  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3473    return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3474  }34753476  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3477    return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3478  }34793480  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3481    return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3482  }34833484  scheduleAt<T extends UniqueHelper>(3485    executionBlockNumber: number,3486    options: ISchedulerOptions = {},3487  ) {3488    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3489    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3490  }34913492  scheduleAfter<T extends UniqueHelper>(3493    blocksBeforeExecution: number,3494    options: ISchedulerOptions = {},3495  ) {3496    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3497    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3498  }34993500  getSudo<T extends UniqueHelper>() {3501    return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3502  }3503}350435053506export class UniqueFTCollection extends UniqueBaseCollection {3507  async getBalance(addressObj: ICrossAccountId) {3508    return await this.helper.ft.getBalance(this.collectionId, addressObj);3509  }35103511  async getTotalPieces() {3512    return await this.helper.ft.getTotalPieces(this.collectionId);3513  }35143515  async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3516    return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3517  }35183519  async getTop10Owners() {3520    return await this.helper.ft.getTop10Owners(this.collectionId);3521  }35223523  async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3524    return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3525  }35263527  async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3528    return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3529  }35303531  async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3532    return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3533  }35343535  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3536    return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3537  }35383539  async burnTokens(signer: TSigner, amount=1n) {3540    return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3541  }35423543  async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3544    return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3545  }35463547  async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3548    return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3549  }35503551  scheduleAt<T extends UniqueHelper>(3552    executionBlockNumber: number,3553    options: ISchedulerOptions = {},3554  ) {3555    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3556    return new UniqueFTCollection(this.collectionId, scheduledHelper);3557  }35583559  scheduleAfter<T extends UniqueHelper>(3560    blocksBeforeExecution: number,3561    options: ISchedulerOptions = {},3562  ) {3563    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3564    return new UniqueFTCollection(this.collectionId, scheduledHelper);3565  }35663567  getSudo<T extends UniqueHelper>() {3568    return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3569  }3570}357135723573export class UniqueBaseToken {3574  collection: UniqueNFTCollection | UniqueRFTCollection;3575  collectionId: number;3576  tokenId: number;35773578  constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3579    this.collection = collection;3580    this.collectionId = collection.collectionId;3581    this.tokenId = tokenId;3582  }35833584  async getNextSponsored(addressObj: ICrossAccountId) {3585    return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3586  }35873588  async getProperties(propertyKeys?: string[] | null) {3589    return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3590  }35913592  async getTokenPropertiesConsumedSpace() {3593    return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3594  }35953596  async setProperties(signer: TSigner, properties: IProperty[]) {3597    return await this.collection.setTokenProperties(signer, this.tokenId, properties);3598  }35993600  async deleteProperties(signer: TSigner, propertyKeys: string[]) {3601    return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3602  }36033604  async doesExist() {3605    return await this.collection.doesTokenExist(this.tokenId);3606  }36073608  nestingAccount() {3609    return this.collection.helper.util.getTokenAccount(this);3610  }36113612  scheduleAt<T extends UniqueHelper>(3613    executionBlockNumber: number,3614    options: ISchedulerOptions = {},3615  ) {3616    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3617    return new UniqueBaseToken(this.tokenId, scheduledCollection);3618  }36193620  scheduleAfter<T extends UniqueHelper>(3621    blocksBeforeExecution: number,3622    options: ISchedulerOptions = {},3623  ) {3624    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3625    return new UniqueBaseToken(this.tokenId, scheduledCollection);3626  }36273628  getSudo<T extends UniqueHelper>() {3629    return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3630  }3631}363236333634export class UniqueNFToken extends UniqueBaseToken {3635  collection: UniqueNFTCollection;36363637  constructor(tokenId: number, collection: UniqueNFTCollection) {3638    super(tokenId, collection);3639    this.collection = collection;3640  }36413642  async getData(blockHashAt?: string) {3643    return await this.collection.getToken(this.tokenId, blockHashAt);3644  }36453646  async getOwner(blockHashAt?: string) {3647    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3648  }36493650  async getTopmostOwner(blockHashAt?: string) {3651    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3652  }36533654  async getChildren(blockHashAt?: string) {3655    return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3656  }36573658  async nest(signer: TSigner, toTokenObj: IToken) {3659    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3660  }36613662  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3663    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3664  }36653666  async transfer(signer: TSigner, addressObj: ICrossAccountId) {3667    return await this.collection.transferToken(signer, this.tokenId, addressObj);3668  }36693670  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3671    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3672  }36733674  async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3675    return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3676  }36773678  async isApproved(toAddressObj: ICrossAccountId) {3679    return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3680  }36813682  async burn(signer: TSigner) {3683    return await this.collection.burnToken(signer, this.tokenId);3684  }36853686  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3687    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3688  }36893690  scheduleAt<T extends UniqueHelper>(3691    executionBlockNumber: number,3692    options: ISchedulerOptions = {},3693  ) {3694    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3695    return new UniqueNFToken(this.tokenId, scheduledCollection);3696  }36973698  scheduleAfter<T extends UniqueHelper>(3699    blocksBeforeExecution: number,3700    options: ISchedulerOptions = {},3701  ) {3702    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3703    return new UniqueNFToken(this.tokenId, scheduledCollection);3704  }37053706  getSudo<T extends UniqueHelper>() {3707    return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3708  }3709}37103711export class UniqueRFToken extends UniqueBaseToken {3712  collection: UniqueRFTCollection;37133714  constructor(tokenId: number, collection: UniqueRFTCollection) {3715    super(tokenId, collection);3716    this.collection = collection;3717  }37183719  async getData(blockHashAt?: string) {3720    return await this.collection.getToken(this.tokenId, blockHashAt);3721  }37223723  async getTop10Owners() {3724    return await this.collection.getTop10TokenOwners(this.tokenId);3725  }37263727  async getBalance(addressObj: ICrossAccountId) {3728    return await this.collection.getTokenBalance(this.tokenId, addressObj);3729  }37303731  async getTotalPieces() {3732    return await this.collection.getTokenTotalPieces(this.tokenId);3733  }37343735  async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3736    return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3737  }37383739  async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3740    return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3741  }37423743  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3744    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3745  }37463747  async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3748    return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3749  }37503751  async repartition(signer: TSigner, amount: bigint) {3752    return await this.collection.repartitionToken(signer, this.tokenId, amount);3753  }37543755  async burn(signer: TSigner, amount=1n) {3756    return await this.collection.burnToken(signer, this.tokenId, amount);3757  }37583759  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3760    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3761  }37623763  scheduleAt<T extends UniqueHelper>(3764    executionBlockNumber: number,3765    options: ISchedulerOptions = {},3766  ) {3767    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3768    return new UniqueRFToken(this.tokenId, scheduledCollection);3769  }37703771  scheduleAfter<T extends UniqueHelper>(3772    blocksBeforeExecution: number,3773    options: ISchedulerOptions = {},3774  ) {3775    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3776    return new UniqueRFToken(this.tokenId, scheduledCollection);3777  }37783779  getSudo<T extends UniqueHelper>() {3780    return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3781  }3782}