git.delta.rocks / unique-network / refs/commits / 2fcc0ad3d6a7

difftreelog

test forbid creating ApiPromise without set endpoint

Yaroslav Bolyukin2023-09-11parent: #348c8c0.patch.diff
in: master

4 files changed

modifiedtests/src/.outdated/substrate/substrate-api.tsdiffbeforeafterboth
--- a/tests/src/.outdated/substrate/substrate-api.ts
+++ b/tests/src/.outdated/substrate/substrate-api.ts
@@ -71,6 +71,7 @@
 
 export async function getApiConnection(settings: ApiOptions | undefined = undefined): Promise<ApiPromise> {
   settings = settings || defaultApiOptions();
+  if(!settings.provider) throw new Error('provider was not set');
   const api = new ApiPromise(settings);
 
   if (api) {
modifiedtests/src/eth/createCollection.test.tsdiffbeforeafterboth
--- a/tests/src/eth/createCollection.test.ts
+++ b/tests/src/eth/createCollection.test.ts
@@ -217,7 +217,8 @@
       const collection = helper.nft.getCollectionObject(collectionId);
       const data = (await collection.getData())!;
 
-      expect(collectionCountAfter - collectionCountBefore).to.be.eq(1);
+      // Parallel test safety
+      expect(collectionCountAfter - collectionCountBefore).to.be.gte(1);
       expect(collectionId).to.be.eq(collectionCountAfter);
       expect(data.name).to.be.eq(name);
       expect(data.description).to.be.eq(description);
modifiedtests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -278,6 +278,7 @@
   }
 
   async connect(wsEndpoint: string, _listeners?: any): Promise<void> {
+    if(!wsEndpoint) throw new Error('wsEndpoint was not set');
     const wsProvider = new WsProvider(wsEndpoint);
     this.api = new ApiPromise({
       provider: wsProvider,
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 {SignerOptions} from '@polkadot/api/types/submittable';10import '../../interfaces/augment-api';11import {AugmentedSubmittables} from '@polkadot/api-base/types/submittable';12import {ApiInterfaceEvents} from '@polkadot/api/types';13import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a, blake2AsHex} from '@polkadot/util-crypto';14import {IKeyringPair} from '@polkadot/types/types';15import {hexToU8a} from '@polkadot/util/hex';16import {u8aConcat} from '@polkadot/util/u8a';17import {18  IApiListeners,19  IBlock,20  IEvent,21  IChainProperties,22  ICollectionCreationOptions,23  ICollectionLimits,24  ICollectionPermissions,25  ICrossAccountId,26  ICrossAccountIdLower,27  ILogger,28  INestingPermissions,29  IProperty,30  IStakingInfo,31  ISchedulerOptions,32  ISubstrateBalance,33  IToken,34  ITokenPropertyPermission,35  ITransactionResult,36  IUniqueHelperLog,37  TApiAllowedListeners,38  TEthereumAccount,39  TSigner,40  TSubstrateAccount,41  TNetworks,42  IForeignAssetMetadata,43  AcalaAssetMetadata,44  MoonbeamAssetInfo,45  DemocracyStandardAccountVote,46  IEthCrossAccountId,47  IPhasicEvent,48} from './types';49import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';50import type {Vec} from '@polkadot/types-codec';51import {FrameSystemEventRecord, PalletDemocracyConviction} from '@polkadot/types/lookup';5253export class CrossAccountId {54  Substrate!: TSubstrateAccount;55  Ethereum!: TEthereumAccount;5657  constructor(account: ICrossAccountId) {58    if('Substrate' in account) this.Substrate = account.Substrate;59    else this.Ethereum = account.Ethereum;60  }6162  static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {63    switch (domain) {64      case 'Substrate': return new CrossAccountId({Substrate: account.address});65      case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();66    }67  }6869  static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {70    if('substrate' in address) return new CrossAccountId({Substrate: address.substrate});71    else return new CrossAccountId({Ethereum: address.ethereum});72  }7374  static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {75    return encodeAddress(decodeAddress(address), ss58Format);76  }7778  static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {79    return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});80  }8182  withNormalizedSubstrate(ss58Format = 42): CrossAccountId {83    if(this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);84    return this;85  }8687  static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {88    return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));89  }9091  toEthereum(): CrossAccountId {92    if(this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});93    return this;94  }9596  static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {97    return evmToAddress(address, ss58Format);98  }99100  toSubstrate(ss58Format?: number): CrossAccountId {101    if(this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});102    return this;103  }104105  toLowerCase(): CrossAccountId {106    if(this.Substrate) this.Substrate = this.Substrate.toLowerCase();107    if(this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();108    return this;109  }110}111112const nesting = {113  toChecksumAddress(address: string): string {114    if(typeof address === 'undefined') return '';115116    if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);117118    address = address.toLowerCase().replace(/^0x/i, '');119    const addressHash = keccakAsHex(address).replace(/^0x/i, '');120    const checksumAddress = ['0x'];121122    for(let i = 0; i < address.length; i++) {123      // If ith character is 8 to f then make it uppercase124      if(parseInt(addressHash[i], 16) > 7) {125        checksumAddress.push(address[i].toUpperCase());126      } else {127        checksumAddress.push(address[i]);128      }129    }130    return checksumAddress.join('');131  },132  tokenIdToAddress(collectionId: number, tokenId: number) {133    return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);134  },135};136137class UniqueUtil {138  static transactionStatus = {139    NOT_READY: 'NotReady',140    FAIL: 'Fail',141    SUCCESS: 'Success',142  };143144  static chainLogType = {145    EXTRINSIC: 'extrinsic',146    RPC: 'rpc',147  };148149  static getTokenAccount(token: IToken): CrossAccountId {150    return new CrossAccountId({Ethereum: this.getTokenAddress(token)});151  }152153  static getTokenAddress(token: IToken): string {154    return nesting.tokenIdToAddress(token.collectionId, token.tokenId);155  }156157  static getDefaultLogger(): ILogger {158    return {159      log(msg: any, level = 'INFO') {160        console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));161      },162      level: {163        ERROR: 'ERROR',164        WARNING: 'WARNING',165        INFO: 'INFO',166      },167    };168  }169170  static vec2str(arr: string[] | number[]) {171    return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');172  }173174  static str2vec(string: string) {175    if(typeof string !== 'string') return string;176    return Array.from(string).map(x => x.charCodeAt(0));177  }178179  static fromSeed(seed: string, ss58Format = 42) {180    const keyring = new Keyring({type: 'sr25519', ss58Format});181    return keyring.addFromUri(seed);182  }183184  static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {185    if(creationResult.status !== this.transactionStatus.SUCCESS) {186      throw Error('Unable to create collection!');187    }188189    let collectionId = null;190    creationResult.result.events.forEach(({event: {data, method, section}}) => {191      if((section === 'common') && (method === 'CollectionCreated')) {192        collectionId = parseInt(data[0].toString(), 10);193      }194    });195196    if(collectionId === null) {197      throw Error('No CollectionCreated event was found!');198    }199200    return collectionId;201  }202203  static extractTokensFromCreationResult(creationResult: ITransactionResult): {204    success: boolean,205    tokens: { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[],206  } {207    if(creationResult.status !== this.transactionStatus.SUCCESS) {208      throw Error('Unable to create tokens!');209    }210    let success = false;211    const tokens = [] as { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[];212    creationResult.result.events.forEach(({event: {data, method, section}}) => {213      if(method === 'ExtrinsicSuccess') {214        success = true;215      } else if((section === 'common') && (method === 'ItemCreated')) {216        tokens.push({217          collectionId: parseInt(data[0].toString(), 10),218          tokenId: parseInt(data[1].toString(), 10),219          owner: data[2].toHuman(),220          amount: data[3].toBigInt(),221        });222      }223    });224    return {success, tokens};225  }226227  static extractTokensFromBurnResult(burnResult: ITransactionResult): {228    success: boolean,229    tokens: { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[],230  } {231    if(burnResult.status !== this.transactionStatus.SUCCESS) {232      throw Error('Unable to burn tokens!');233    }234    let success = false;235    const tokens = [] as { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[];236    burnResult.result.events.forEach(({event: {data, method, section}}) => {237      if(method === 'ExtrinsicSuccess') {238        success = true;239      } else if((section === 'common') && (method === 'ItemDestroyed')) {240        tokens.push({241          collectionId: parseInt(data[0].toString(), 10),242          tokenId: parseInt(data[1].toString(), 10),243          owner: data[2].toHuman(),244          amount: data[3].toBigInt(),245        });246      }247    });248    return {success, tokens};249  }250251  static findCollectionInEvents(events: { event: IEvent }[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {252    let eventId = null;253    events.forEach(({event: {data, method, section}}) => {254      if((section === expectedSection) && (method === expectedMethod)) {255        eventId = parseInt(data[0].toString(), 10);256      }257    });258259    if(eventId === null) {260      throw Error(`No ${expectedMethod} event was found!`);261    }262    return eventId === collectionId;263  }264265  static isTokenTransferSuccess(events: { event: IEvent }[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {266    const normalizeAddress = (address: string | ICrossAccountId) => {267      if(typeof address === 'string') return address;268      const obj = {} as any;269      Object.keys(address).forEach(k => {270        obj[k.toLocaleLowerCase()] = (address as any)[k];271      });272      if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);273      if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();274      return address;275    };276    let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;277    events.forEach(({event: {data, method, section}}) => {278      if((section === 'common') && (method === 'Transfer')) {279        const hData = (data as any).toJSON();280        transfer = {281          collectionId: hData[0],282          tokenId: hData[1],283          from: normalizeAddress(hData[2]),284          to: normalizeAddress(hData[3]),285          amount: BigInt(hData[4]),286        };287      }288    });289    let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;290    isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);291    isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);292    isSuccess = isSuccess && amount === transfer.amount;293    return isSuccess;294  }295296  static bigIntToDecimals(number: bigint, decimals = 18) {297    const numberStr = number.toString();298    const dotPos = numberStr.length - decimals;299300    if(dotPos <= 0) {301      return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;302    } else {303      const intPart = numberStr.substring(0, dotPos);304      const fractPart = numberStr.substring(dotPos);305      return intPart + '.' + fractPart;306    }307  }308}309310class UniqueEventHelper {311  private static extractIndex(index: any): [number, number] | string {312    if(index.toRawType() === '[u8;2]') return [index[0], index[1]];313    return index.toJSON();314  }315316  private static extractSub(data: any, subTypes: any): { [key: string]: any } {317    let obj: any = {};318    let index = 0;319320    if(data.entries) {321      for(const [key, value] of data.entries()) {322        obj[key] = this.extractData(value, subTypes[index]);323        index++;324      }325    } else obj = data.toJSON();326327    return obj;328  }329330  private static toHuman(data: any) {331    return data && data.toHuman ? data.toHuman() : `${data}`;332  }333334  private static extractData(data: any, type: any): any {335    if(!type) return this.toHuman(data);336    if(['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();337    if(['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();338    if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);339    return this.toHuman(data);340  }341342  public static extractEvents(events: { event: any, phase: any }[]): IEvent[] {343    const parsedEvents: IEvent[] = [];344345    events.forEach((record) => {346      const {event, phase} = record;347      const types = event.typeDef;348349      const eventData: IEvent = {350        section: event.section.toString(),351        method: event.method.toString(),352        index: this.extractIndex(event.index),353        data: [],354        phase: phase.toJSON(),355      };356357      event.data.forEach((val: any, index: number) => {358        eventData.data.push(this.extractData(val, types[index]));359      });360361      parsedEvents.push(eventData);362    });363364    return parsedEvents;365  }366}367const InvalidTypeSymbol = Symbol('Invalid type');368// eslint-disable-next-line @typescript-eslint/no-unused-vars369export type Invalid<ErrorMessage> =370  | ((371    invalidType: typeof InvalidTypeSymbol,372    ..._: typeof InvalidTypeSymbol[]373  ) => typeof InvalidTypeSymbol)374  | null375  | undefined;376// Has slightly better error messages than Get377type Get2<T, P extends string, E> =378  P extends `${infer Key}.${infer Key2}` ? Key extends keyof T ? Key2 extends keyof T[Key] ? T[Key][Key2] : E : E : E;379type ForceFunction<T> = T extends (...args: any) => any ? T : (...args: any) => Invalid<'not a function'>;380381export class ChainHelperBase {382  helperBase: any;383384  transactionStatus = UniqueUtil.transactionStatus;385  chainLogType = UniqueUtil.chainLogType;386  util: typeof UniqueUtil;387  eventHelper: typeof UniqueEventHelper;388  logger: ILogger;389  api: ApiPromise | null;390  forcedNetwork: TNetworks | null;391  network: TNetworks | null;392  wsEndpoint: string | null;393  chainLog: IUniqueHelperLog[];394  children: ChainHelperBase[];395  address: AddressGroup;396  chain: ChainGroup;397398  constructor(logger?: ILogger, helperBase?: any) {399    this.helperBase = helperBase;400401    this.util = UniqueUtil;402    this.eventHelper = UniqueEventHelper;403    if(typeof logger == 'undefined') logger = this.util.getDefaultLogger();404    this.logger = logger;405    this.api = null;406    this.forcedNetwork = null;407    this.network = null;408    this.wsEndpoint = null;409    this.chainLog = [];410    this.children = [];411    this.address = new AddressGroup(this);412    this.chain = new ChainGroup(this);413  }414415  clone(helperCls: ChainHelperBaseConstructor, options: { [key: string]: any } = {}) {416    Object.setPrototypeOf(helperCls.prototype, this);417    const newHelper = new helperCls(this.logger, options);418419    newHelper.api = this.api;420    newHelper.network = this.network;421    newHelper.forceNetwork = this.forceNetwork;422423    this.children.push(newHelper);424425    return newHelper;426  }427428  getEndpoint(): string {429    if(this.wsEndpoint === null) throw Error('No connection was established');430    return this.wsEndpoint;431  }432433  getApi(): ApiPromise {434    if(this.api === null) throw Error('API not initialized');435    return this.api;436  }437438  async subscribeEvents(expectedEvents: { section: string, names: string[] }[]) {439    const collectedEvents: IEvent[] = [];440    const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {441      const ievents = this.eventHelper.extractEvents(events);442      ievents.forEach((event) => {443        expectedEvents.forEach((e => {444          if(event.section === e.section && e.names.includes(event.method)) {445            collectedEvents.push(event);446          }447        }));448      });449    });450    return {unsubscribe: unsubscribe as any, collectedEvents};451  }452453  clearChainLog(): void {454    this.chainLog = [];455  }456457  forceNetwork(value: TNetworks): void {458    this.forcedNetwork = value;459  }460461  async connect(wsEndpoint: string, listeners?: IApiListeners) {462    if(this.api !== null) throw Error('Already connected');463    const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);464    this.wsEndpoint = wsEndpoint;465    this.api = api;466    this.network = network;467  }468469  async disconnect() {470    for(const child of this.children) {471      child.clearApi();472    }473474    if(this.api === null) return;475    await this.api.disconnect();476    this.clearApi();477  }478479  clearApi() {480    this.api = null;481    this.network = null;482  }483484  static async detectNetwork(api: ApiPromise): Promise<TNetworks> {485    const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;486    const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];487488    if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;489490    if(['quartz', 'unique', 'sapphire'].indexOf(spec.specName) > -1) return spec.specName;491    return 'opal';492  }493494  static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {495    const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});496    await api.isReady;497498    const network = await this.detectNetwork(api);499500    await api.disconnect();501502    return network;503  }504505  static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{506    api: ApiPromise;507    network: TNetworks;508  }> {509    if(typeof network === 'undefined' || network === null) network = 'opal';510    const supportedRPC = {511      opal: {512        unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,513      },514      quartz: {515        unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,516      },517      unique: {518        unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,519      },520      rococo: {},521      westend: {},522      moonbeam: {},523      moonriver: {},524      acala: {},525      karura: {},526      westmint: {},527    };528    if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);529    const rpc = supportedRPC[network];530531    // TODO: investigate how to replace rpc in runtime532    // api._rpcCore.addUserInterfaces(rpc);533534    const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});535536    await api.isReadyOrError;537538    if(typeof listeners === 'undefined') listeners = {};539    for(const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {540      if(!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;541      api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);542    }543544    return {api, network};545  }546547  getTransactionStatus(data: { events: { event: IEvent }[], status: any }) {548    const {events, status} = data;549    if(status.isReady) {550      return this.transactionStatus.NOT_READY;551    }552    if(status.isBroadcast) {553      return this.transactionStatus.NOT_READY;554    }555    if(status.isInBlock || status.isFinalized) {556      const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');557      if(errors.length > 0) {558        return this.transactionStatus.FAIL;559      }560      if(events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {561        return this.transactionStatus.SUCCESS;562      }563    }564565    return this.transactionStatus.FAIL;566  }567568  signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {569    const sign = (callback: any) => {570      if(options !== null) return transaction.signAndSend(sender, options, callback);571      return transaction.signAndSend(sender, callback);572    };573    // eslint-disable-next-line no-async-promise-executor574    return new Promise(async (resolve, reject) => {575      try {576        const unsub = await sign((result: any) => {577          const status = this.getTransactionStatus(result);578579          if(status === this.transactionStatus.SUCCESS) {580            this.logger.log(`${label} successful`);581            unsub();582            resolve({result, status, blockHash: result.status.asInBlock.toHuman()});583          } else if(status === this.transactionStatus.FAIL) {584            let moduleError = null;585586            if(result.hasOwnProperty('dispatchError')) {587              const dispatchError = result['dispatchError'];588589              if(dispatchError) {590                if(dispatchError.isModule) {591                  const modErr = dispatchError.asModule;592                  const errorMeta = dispatchError.registry.findMetaError(modErr);593594                  moduleError = `${errorMeta.section}.${errorMeta.name}`;595                } else if(dispatchError.isToken) {596                  moduleError = `Token: ${dispatchError.asToken}`;597                } else {598                  // May be [object Object] in case of unhandled non-unit enum599                  moduleError = `Misc: ${dispatchError.toHuman()}`;600                }601              } else {602                this.logger.log(result, this.logger.level.ERROR);603              }604            }605606            this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);607            unsub();608            reject({status, moduleError, result});609          }610        });611      } catch (e) {612        this.logger.log(e, this.logger.level.ERROR);613        reject(e);614      }615    });616  }617618  async signTransactionWithoutSending(signer: TSigner, tx: any) {619    const api = this.getApi();620    const signingInfo = await api.derive.tx.signingInfo(signer.address);621622    tx.sign(signer, {623      blockHash: api.genesisHash,624      genesisHash: api.genesisHash,625      runtimeVersion: api.runtimeVersion,626      nonce: signingInfo.nonce,627    });628629    return tx.toHex();630  }631632  async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {633    const api = this.getApi();634    const signingInfo = await api.derive.tx.signingInfo(signer.address);635636    // We need to sign the tx because637    // unsigned transactions does not have an inclusion fee638    tx.sign(signer, {639      blockHash: api.genesisHash,640      genesisHash: api.genesisHash,641      runtimeVersion: api.runtimeVersion,642      nonce: signingInfo.nonce,643    });644645    if(len === null) {646      return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;647    } else {648      return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;649    }650  }651652  constructApiCall(apiCall: string, params: any[]) {653    if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);654    let call = this.getApi() as any;655    for(const part of apiCall.slice(4).split('.')) {656      call = call[part];657      if(!call) {658        const advice = part.includes('_') ? ' Looks like it needs to be converted to camel case.' : '';659        throw Error(`Function ${part} of api call ${apiCall} not found.${advice}`);660      }661    }662    return call(...params);663  }664665  encodeApiCall(apiCall: string, params: any[]) {666    return this.constructApiCall(apiCall, params).method.toHex();667  }668669  async executeExtrinsic<670    E extends string,671    V extends (672      ...args: any) => any = ForceFunction<673        Get2<674          AugmentedSubmittables<'promise'>,675          E, (...args: any) => Invalid<'not found'>676        >677      >678  >(679    sender: TSigner,680    extrinsic: `api.tx.${E}`,681    params: Parameters<V>,682    expectSuccess = true,683    options: Partial<SignerOptions> | null = null,/*, failureMessage='expected success'*/684  ): Promise<ITransactionResult> {685    if(this.api === null) throw Error('API not initialized');686687    const startTime = (new Date()).getTime();688    let result: ITransactionResult;689    let events: IEvent[] = [];690    try {691      result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;692      events = this.eventHelper.extractEvents(result.result.events);693      const errorEvent = events.find((event) => event.method == 'ExecutedFailed' || event.method == 'CreatedFailed');694      if(errorEvent)695        throw Error(errorEvent.method + ': ' + extrinsic);696    }697    catch (e) {698      if(!(e as object).hasOwnProperty('status')) throw e;699      result = e as ITransactionResult;700    }701702    const endTime = (new Date()).getTime();703704    const log = {705      executedAt: endTime,706      executionTime: endTime - startTime,707      type: this.chainLogType.EXTRINSIC,708      status: result.status,709      call: extrinsic,710      signer: this.getSignerAddress(sender),711      params,712    } as IUniqueHelperLog;713714    let errorMessage = '';715716    if(result.status !== this.transactionStatus.SUCCESS) {717      if(result.moduleError) {718        errorMessage = typeof result.moduleError === 'string'719          ? result.moduleError720          : `${Object.keys(result.moduleError)[0]}: ${Object.values(result.moduleError)[0]}`;721        log.moduleError = errorMessage;722      }723      else if(result.result.dispatchError) log.dispatchError = result.result.dispatchError;724    }725    if(events.length > 0) log.events = events;726727    this.chainLog.push(log);728729    if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {730      if(result.moduleError) throw Error(`${errorMessage}`);731      else if(result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));732    }733    return result as any;734  }735  executeExtrinsicUncheckedWeight<736      E extends string,737      V extends (738         ...args: any) => any = ForceFunction<739            Get2<740               AugmentedSubmittables<'promise'>,741               E, (...args: any) => Invalid<'not found'>742            >743         >744   >(745    sender: TSigner,746    extrinsic: `api.tx.${E}`,747    params: Parameters<V>,748    expectSuccess = true,749    options: Partial<SignerOptions> | null = null,/*, failureMessage='expected success'*/750  ): Promise<ITransactionResult> {751    throw new Error('executeExtrinsicUncheckedWeight only supported in sudo');752  }753754  async callRpc755  // TODO: make it strongly typed, or use api.query/api.rpc directly756  // <757  // K extends 'rpc' | 'query',758  // E extends string,759  // V extends (...args: any) => any = ForceFunction<760  //   Get2<761  //     K extends 'rpc' ? DecoratedRpc<'promise', RpcInterface> : QueryableStorage<'promise'>,762  //     E, (...args: any) => Invalid<'not found'>763  //   >764  // >,765  // P = Parameters<V>,766  // >767  (rpc: string, params?: any[]): Promise<any> {768769    if(typeof params === 'undefined') params = [] as any;770    if(this.api === null) throw Error('API not initialized');771    if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);772773    const startTime = (new Date()).getTime();774    let result;775    let error = null;776    const log = {777      type: this.chainLogType.RPC,778      call: rpc,779      params,780    } as any as IUniqueHelperLog;781782    try {783      result = await this.constructApiCall(rpc, params as any);784    }785    catch (e) {786      error = e;787    }788789    const endTime = (new Date()).getTime();790791    log.executedAt = endTime;792    log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';793    log.executionTime = endTime - startTime;794795    this.chainLog.push(log);796797    if(error !== null) throw error;798799    return result;800  }801802  getSignerAddress(signer: IKeyringPair | string): string {803    if(typeof signer === 'string') return signer;804    return signer.address;805  }806807  fetchAllPalletNames(): string[] {808    if(this.api === null) throw Error('API not initialized');809    return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase()).sort();810  }811812  fetchMissingPalletNames(requiredPallets: readonly string[]): string[] {813    const palletNames = this.fetchAllPalletNames();814    return requiredPallets.filter(p => !palletNames.includes(p));815  }816}817818819class HelperGroup<T extends ChainHelperBase> {820  helper: T;821822  constructor(uniqueHelper: T) {823    this.helper = uniqueHelper;824  }825}826827828class CollectionGroup extends HelperGroup<UniqueHelper> {829  /**830 * Get number of blocks when sponsored transaction is available.831 *832 * @param collectionId ID of collection833 * @param tokenId ID of token834 * @param addressObj address for which the sponsorship is checked835 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});836 * @returns number of blocks or null if sponsorship hasn't been set837 */838  async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {839    return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();840  }841842  /**843   * Get the number of created collections.844   *845   * @returns number of created collections846   */847  async getTotalCount(): Promise<number> {848    return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();849  }850851  /**852   * Get information about the collection with additional data,853   * including the number of tokens it contains, its administrators,854   * the normalized address of the collection's owner, and decoded name and description.855   *856   * @param collectionId ID of collection857   * @example await getData(2)858   * @returns collection information object859   */860  async getData(collectionId: number): Promise<{861    id: number;862    name: string;863    description: string;864    tokensCount: number;865    admins: CrossAccountId[];866    normalizedOwner: TSubstrateAccount;867    raw: any868  } | null> {869    const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);870    const humanCollection = collection.toHuman(), collectionData = {871      id: collectionId, name: null, description: null, tokensCount: 0, admins: [],872      raw: humanCollection,873    } as any, jsonCollection = collection.toJSON();874    if(humanCollection === null) return null;875    collectionData.raw.limits = jsonCollection.limits;876    collectionData.raw.permissions = jsonCollection.permissions;877    collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);878    for(const key of ['name', 'description']) {879      collectionData[key] = this.helper.util.vec2str(humanCollection[key]);880    }881882    collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))883      ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)884      : 0;885    collectionData.admins = await this.getAdmins(collectionId);886887    return collectionData;888  }889890  /**891   * Get the addresses of the collection's administrators, optionally normalized.892   *893   * @param collectionId ID of collection894   * @param normalize whether to normalize the addresses to the default ss58 format895   * @example await getAdmins(1)896   * @returns array of administrators897   */898  async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {899    const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();900901    return normalize902      ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())903      : admins;904  }905906  /**907   * Get the addresses added to the collection allow-list, optionally normalized.908   * @param collectionId ID of collection909   * @param normalize whether to normalize the addresses to the default ss58 format910   * @example await getAllowList(1)911   * @returns array of allow-listed addresses912   */913  async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {914    const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();915    return normalize916      ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())917      : allowListed;918  }919920  /**921   * Get the effective limits of the collection instead of null for default values922   *923   * @param collectionId ID of collection924   * @example await getEffectiveLimits(2)925   * @returns object of collection limits926   */927  async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {928    return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();929  }930931  /**932   * Burns the collection if the signer has sufficient permissions and collection is empty.933   *934   * @param signer keyring of signer935   * @param collectionId ID of collection936   * @example await helper.collection.burn(aliceKeyring, 3);937   * @returns ```true``` if extrinsic success, otherwise ```false```938   */939  async burn(signer: TSigner, collectionId: number): Promise<boolean> {940    const result = await this.helper.executeExtrinsic(941      signer,942      'api.tx.unique.destroyCollection', [collectionId],943      true,944    );945946    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');947  }948949  /**950   * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.951   *952   * @param signer keyring of signer953   * @param collectionId ID of collection954   * @param sponsorAddress Sponsor substrate address955   * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")956   * @returns ```true``` if extrinsic success, otherwise ```false```957   */958  async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {959    const result = await this.helper.executeExtrinsic(960      signer,961      'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],962      true,963    );964965    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');966  }967968  /**969   * Confirms consent to sponsor the collection on behalf of the signer.970   *971   * @param signer keyring of signer972   * @param collectionId ID of collection973   * @example confirmSponsorship(aliceKeyring, 10)974   * @returns ```true``` if extrinsic success, otherwise ```false```975   */976  async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {977    const result = await this.helper.executeExtrinsic(978      signer,979      'api.tx.unique.confirmSponsorship', [collectionId],980      true,981    );982983    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');984  }985986  /**987   * Removes the sponsor of a collection, regardless if it consented or not.988   *989   * @param signer keyring of signer990   * @param collectionId ID of collection991   * @example removeSponsor(aliceKeyring, 10)992   * @returns ```true``` if extrinsic success, otherwise ```false```993   */994  async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {995    const result = await this.helper.executeExtrinsic(996      signer,997      'api.tx.unique.removeCollectionSponsor', [collectionId],998      true,999    );10001001    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');1002  }10031004  /**1005   * Sets the limits of the collection. At least one limit must be specified for a correct call.1006   *1007   * @param signer keyring of signer1008   * @param collectionId ID of collection1009   * @param limits collection limits object1010   * @example1011   * await setLimits(1012   *   aliceKeyring,1013   *   10,1014   *   {1015   *     sponsorTransferTimeout: 0,1016   *     ownerCanDestroy: false1017   *   }1018   * )1019   * @returns ```true``` if extrinsic success, otherwise ```false```1020   */1021  async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {1022    const result = await this.helper.executeExtrinsic(1023      signer,1024      'api.tx.unique.setCollectionLimits', [collectionId, limits],1025      true,1026    );10271028    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');1029  }10301031  /**1032   * Changes the owner of the collection to the new Substrate address.1033   *1034   * @param signer keyring of signer1035   * @param collectionId ID of collection1036   * @param ownerAddress substrate address of new owner1037   * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")1038   * @returns ```true``` if extrinsic success, otherwise ```false```1039   */1040  async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {1041    const result = await this.helper.executeExtrinsic(1042      signer,1043      'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],1044      true,1045    );10461047    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');1048  }10491050  /**1051   * Adds a collection administrator.1052   *1053   * @param signer keyring of signer1054   * @param collectionId ID of collection1055   * @param adminAddressObj Administrator address (substrate or ethereum)1056   * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})1057   * @returns ```true``` if extrinsic success, otherwise ```false```1058   */1059  async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1060    const result = await this.helper.executeExtrinsic(1061      signer,1062      'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],1063      true,1064    );10651066    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');1067  }10681069  /**1070   * Removes a collection administrator.1071   *1072   * @param signer keyring of signer1073   * @param collectionId ID of collection1074   * @param adminAddressObj Administrator address (substrate or ethereum)1075   * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})1076   * @returns ```true``` if extrinsic success, otherwise ```false```1077   */1078  async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1079    const result = await this.helper.executeExtrinsic(1080      signer,1081      'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],1082      true,1083    );10841085    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');1086  }10871088  /**1089   * Check if user is in allow list.1090   *1091   * @param collectionId ID of collection1092   * @param user Account to check1093   * @example await getAdmins(1)1094   * @returns is user in allow list1095   */1096  async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {1097    return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();1098  }10991100  /**1101   * Adds an address to allow list1102   * @param signer keyring of signer1103   * @param collectionId ID of collection1104   * @param addressObj address to add to the allow list1105   * @returns ```true``` if extrinsic success, otherwise ```false```1106   */1107  async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1108    const result = await this.helper.executeExtrinsic(1109      signer,1110      'api.tx.unique.addToAllowList', [collectionId, addressObj],1111      true,1112    );11131114    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1115  }11161117  /**1118   * Removes an address from allow list1119   *1120   * @param signer keyring of signer1121   * @param collectionId ID of collection1122   * @param addressObj address to remove from the allow list1123   * @returns ```true``` if extrinsic success, otherwise ```false```1124   */1125  async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1126    const result = await this.helper.executeExtrinsic(1127      signer,1128      'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1129      true,1130    );11311132    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1133  }11341135  /**1136   * Sets onchain permissions for selected collection.1137   *1138   * @param signer keyring of signer1139   * @param collectionId ID of collection1140   * @param permissions collection permissions object1141   * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1142   * @returns ```true``` if extrinsic success, otherwise ```false```1143   */1144  async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1145    const result = await this.helper.executeExtrinsic(1146      signer,1147      'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1148      true,1149    );11501151    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1152  }11531154  /**1155   * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1156   *1157   * @param signer keyring of signer1158   * @param collectionId ID of collection1159   * @param permissions nesting permissions object1160   * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1161   * @returns ```true``` if extrinsic success, otherwise ```false```1162   */1163  async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1164    return await this.setPermissions(signer, collectionId, {nesting: permissions});1165  }11661167  /**1168   * Disables nesting for selected collection.1169   *1170   * @param signer keyring of signer1171   * @param collectionId ID of collection1172   * @example disableNesting(aliceKeyring, 10);1173   * @returns ```true``` if extrinsic success, otherwise ```false```1174   */1175  async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1176    return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1177  }11781179  /**1180   * Sets onchain properties to the collection.1181   *1182   * @param signer keyring of signer1183   * @param collectionId ID of collection1184   * @param properties array of property objects1185   * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1186   * @returns ```true``` if extrinsic success, otherwise ```false```1187   */1188  async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1189    const result = await this.helper.executeExtrinsic(1190      signer,1191      'api.tx.unique.setCollectionProperties', [collectionId, properties],1192      true,1193    );11941195    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1196  }11971198  /**1199   * Get collection properties.1200   *1201   * @param collectionId ID of collection1202   * @param propertyKeys optionally filter the returned properties to only these keys1203   * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1204   * @returns array of key-value pairs1205   */1206  async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1207    return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1208  }12091210  async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1211    const api = this.helper.getApi();1212    const props = (await api.query.common.collectionProperties(collectionId)).toJSON();12131214    return (props! as any).consumedSpace;1215  }12161217  async getCollectionOptions(collectionId: number) {1218    return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1219  }12201221  /**1222   * Deletes onchain properties from the collection.1223   *1224   * @param signer keyring of signer1225   * @param collectionId ID of collection1226   * @param propertyKeys array of property keys to delete1227   * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1228   * @returns ```true``` if extrinsic success, otherwise ```false```1229   */1230  async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1231    const result = await this.helper.executeExtrinsic(1232      signer,1233      'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1234      true,1235    );12361237    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1238  }12391240  /**1241   * Changes the owner of the token.1242   *1243   * @param signer keyring of signer1244   * @param collectionId ID of collection1245   * @param tokenId ID of token1246   * @param addressObj address of a new owner1247   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1248   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1249   * @returns true if the token success, otherwise false1250   */1251  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1252    const result = await this.helper.executeExtrinsic(1253      signer,1254      'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1255      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1256    );12571258    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1259  }12601261  /**1262   *1263   * Change ownership of a token(s) on behalf of the owner.1264   *1265   * @param signer keyring of signer1266   * @param collectionId ID of collection1267   * @param tokenId ID of token1268   * @param fromAddressObj address on behalf of which the token will be sent1269   * @param toAddressObj new token owner1270   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1271   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1272   * @returns true if the token success, otherwise false1273   */1274  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1275    const result = await this.helper.executeExtrinsic(1276      signer,1277      'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1278      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1279    );1280    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1281  }12821283  /**1284   *1285   * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1286   *1287   * @param signer keyring of signer1288   * @param collectionId ID of collection1289   * @param tokenId ID of token1290   * @param amount amount of tokens to be burned. For NFT must be set to 1n1291   * @example burnToken(aliceKeyring, 10, 5);1292   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1293   */1294  async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount = 1n): Promise<boolean> {1295    const burnResult = await this.helper.executeExtrinsic(1296      signer,1297      'api.tx.unique.burnItem', [collectionId, tokenId, amount],1298      true, // `Unable to burn token for ${label}`,1299    );1300    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1301    if(burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1302    return burnedTokens.success;1303  }13041305  /**1306   * Destroys a concrete instance of NFT on behalf of the owner1307   *1308   * @param signer keyring of signer1309   * @param collectionId ID of collection1310   * @param tokenId ID of token1311   * @param fromAddressObj address on behalf of which the token will be burnt1312   * @param amount amount of tokens to be burned. For NFT must be set to 1n1313   * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1314   * @returns ```true``` if extrinsic success, otherwise ```false```1315   */1316  async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1317    const burnResult = await this.helper.executeExtrinsic(1318      signer,1319      'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1320      true, // `Unable to burn token from for ${label}`,1321    );1322    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1323    return burnedTokens.success && burnedTokens.tokens.length > 0;1324  }13251326  /**1327   * Set, change, or remove approved address to transfer the ownership of the NFT.1328   *1329   * @param signer keyring of signer1330   * @param collectionId ID of collection1331   * @param tokenId ID of token1332   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1333   * @param amount amount of token to be approved. For NFT must be set to 1n1334   * @returns ```true``` if extrinsic success, otherwise ```false```1335   */1336  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1337    const approveResult = await this.helper.executeExtrinsic(1338      signer,1339      'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1340      true, // `Unable to approve token for ${label}`,1341    );13421343    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1344  }13451346  /**1347   * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1348   *1349   * @param signer keyring of signer1350   * @param collectionId ID of collection1351   * @param tokenId ID of token1352   * @param fromAddressObj Signer's Ethereum address containing her tokens1353   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1354   * @param amount amount of token to be approved. For NFT must be set to 1n1355   * @returns ```true``` if extrinsic success, otherwise ```false```1356   */1357  async approveTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {1358    const approveResult = await this.helper.executeExtrinsic(1359      signer,1360      'api.tx.unique.approveFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1361      true, // `Unable to approve token for ${label}`,1362    );13631364    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1365  }13661367  /**1368   * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1369   *1370   * @param signer keyring of signer1371   * @param collectionId ID of collection1372   * @param tokenId ID of token1373   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1374   * @param amount amount of token to be approved. For NFT must be set to 1n1375   * @returns ```true``` if extrinsic success, otherwise ```false```1376   */1377  async approveTokenFromEth(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1378    const ethMirror = CrossAccountId.fromKeyring(signer).toEthereum();1379    return await this.approveTokenFrom(signer, collectionId, tokenId, ethMirror, toAddressObj, amount);1380  }13811382  /**1383   * Get the amount of token pieces approved to transfer or burn. Normally 0.1384   *1385   * @param collectionId ID of collection1386   * @param tokenId ID of token1387   * @param toAccountObj address which is approved to use token pieces1388   * @param fromAccountObj address which may have allowed the use of its owned tokens1389   * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1390   * @returns number of approved to transfer pieces1391   */1392  async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1393    return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1394  }13951396  /**1397   * Get the last created token ID in a collection1398   *1399   * @param collectionId ID of collection1400   * @example getLastTokenId(10);1401   * @returns id of the last created token1402   */1403  async getLastTokenId(collectionId: number): Promise<number> {1404    return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1405  }14061407  /**1408   * Check if token exists1409   *1410   * @param collectionId ID of collection1411   * @param tokenId ID of token1412   * @example doesTokenExist(10, 20);1413   * @returns true if the token exists, otherwise false1414   */1415  async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1416    return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1417  }1418}14191420class NFTnRFT extends CollectionGroup {1421  /**1422   * Get tokens owned by account1423   *1424   * @param collectionId ID of collection1425   * @param addressObj tokens owner1426   * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1427   * @returns array of token ids owned by account1428   */1429  async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1430    return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1431  }14321433  /**1434   * Get token data1435   *1436   * @param collectionId ID of collection1437   * @param tokenId ID of token1438   * @param propertyKeys optionally filter the token properties to only these keys1439   * @param blockHashAt optionally query the data at some block with this hash1440   * @example getToken(10, 5);1441   * @returns human readable token data1442   */1443  async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1444    properties: IProperty[];1445    owner: CrossAccountId;1446    normalizedOwner: CrossAccountId;1447  } | null> {1448    let tokenData;1449    if(typeof blockHashAt === 'undefined') {1450      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1451    }1452    else {1453      if(propertyKeys.length == 0) {1454        const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1455        if(!collection) return null;1456        propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1457      }1458      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1459    }1460    tokenData = tokenData.toHuman();1461    if(tokenData === null || tokenData.owner === null) return null;1462    const owner = {} as any;1463    for(const key of Object.keys(tokenData.owner)) {1464      owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1465        ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1466        : tokenData.owner[key];1467    }1468    tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1469    return tokenData;1470  }14711472  /**1473   * Get token's owner1474   * @param collectionId ID of collection1475   * @param tokenId ID of token1476   * @param blockHashAt optionally query the data at the block with this hash1477   * @example getTokenOwner(10, 5);1478   * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1479   */1480  async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1481    let owner;1482    if(typeof blockHashAt === 'undefined') {1483      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1484    } else {1485      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1486    }1487    return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1488  }14891490  /**1491   * Recursively find the address that owns the token1492   * @param collectionId ID of collection1493   * @param tokenId ID of token1494   * @param blockHashAt1495   * @example getTokenTopmostOwner(10, 5);1496   * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1497   */1498  async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1499    let owner;1500    if(typeof blockHashAt === 'undefined') {1501      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1502    } else {1503      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1504    }15051506    if(owner === null) return null;15071508    return owner.toHuman();1509  }15101511  /**1512   * Nest one token into another1513   * @param signer keyring of signer1514   * @param tokenObj token to be nested1515   * @param rootTokenObj token to be parent1516   * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1517   * @returns ```true``` if extrinsic success, otherwise ```false```1518   */1519  async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1520    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1521    const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1522    if(!result) {1523      throw Error('Unable to nest token!');1524    }1525    return result;1526  }15271528  /**1529     * Remove token from nested state1530     * @param signer keyring of signer1531     * @param tokenObj token to unnest1532     * @param rootTokenObj parent of a token1533     * @param toAddressObj address of a new token owner1534     * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1535     * @returns ```true``` if extrinsic success, otherwise ```false```1536     */1537  async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1538    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1539    const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1540    if(!result) {1541      throw Error('Unable to unnest token!');1542    }1543    return result;1544  }15451546  /**1547   * Set permissions to change token properties1548   *1549   * @param signer keyring of signer1550   * @param collectionId ID of collection1551   * @param permissions permissions to change a property by the collection admin or token owner1552   * @example setTokenPropertyPermissions(1553   *   aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1554   * )1555   * @returns true if extrinsic success otherwise false1556   */1557  async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1558    const result = await this.helper.executeExtrinsic(1559      signer,1560      'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1561      true,1562    );15631564    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1565  }15661567  /**1568   * Get token property permissions.1569   *1570   * @param collectionId ID of collection1571   * @param propertyKeys optionally filter the returned property permissions to only these keys1572   * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1573   * @returns array of key-permission pairs1574   */1575  async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1576    return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1577  }15781579  /**1580   * Set token properties1581   *1582   * @param signer keyring of signer1583   * @param collectionId ID of collection1584   * @param tokenId ID of token1585   * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1586   * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1587   * @returns ```true``` if extrinsic success, otherwise ```false```1588   */1589  async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1590    const result = await this.helper.executeExtrinsic(1591      signer,1592      'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1593      true,1594    );15951596    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1597  }15981599  /**1600   * Get properties, metadata assigned to a token.1601   *1602   * @param collectionId ID of collection1603   * @param tokenId ID of token1604   * @param propertyKeys optionally filter the returned properties to only these keys1605   * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1606   * @returns array of key-value pairs1607   */1608  async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1609    return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1610  }16111612  /**1613   * Delete the provided properties of a token1614   * @param signer keyring of signer1615   * @param collectionId ID of collection1616   * @param tokenId ID of token1617   * @param propertyKeys property keys to be deleted1618   * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1619   * @returns ```true``` if extrinsic success, otherwise ```false```1620   */1621  async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1622    const result = await this.helper.executeExtrinsic(1623      signer,1624      'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1625      true,1626    );16271628    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1629  }16301631  /**1632   * Mint new collection1633   *1634   * @param signer keyring of signer1635   * @param collectionOptions basic collection options and properties1636   * @param mode NFT or RFT type of a collection1637   * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1638   * @returns object of the created collection1639   */1640  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1641    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1642    collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1643    for(const key of ['name', 'description', 'tokenPrefix']) {1644      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);1645    }16461647    let flags = 0;1648    // convert CollectionFlags to number and join them in one number1649    if(collectionOptions.flags) {1650      for(let i = 0; i < collectionOptions.flags.length; i++){1651        const flag = collectionOptions.flags[i];1652        flags = flags | flag;1653      }1654    }1655    collectionOptions.flags = [flags];16561657    const creationResult = await this.helper.executeExtrinsic(1658      signer,1659      'api.tx.unique.createCollectionEx', [collectionOptions],1660      true, // errorLabel,1661    );1662    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1663  }16641665  getCollectionObject(_collectionId: number): any {1666    return null;1667  }16681669  getTokenObject(_collectionId: number, _tokenId: number): any {1670    return null;1671  }16721673  /**1674   * Tells whether the given `owner` approves the `operator`.1675   * @param collectionId ID of collection1676   * @param owner owner address1677   * @param operator operator addrees1678   * @returns true if operator is enabled1679   */1680  async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1681    return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1682  }16831684  /** Sets or unsets the approval of a given operator.1685   *  The `operator` is allowed to transfer all tokens of the `caller` on their behalf.1686   *  @param operator Operator1687   *  @param approved Should operator status be granted or revoked?1688   *  @returns ```true``` if extrinsic success, otherwise ```false```1689   */1690  async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1691    const result = await this.helper.executeExtrinsic(1692      signer,1693      'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1694      true,1695    );1696    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1697  }1698}169917001701class NFTGroup extends NFTnRFT {1702  /**1703   * Get collection object1704   * @param collectionId ID of collection1705   * @example getCollectionObject(2);1706   * @returns instance of UniqueNFTCollection1707   */1708  getCollectionObject(collectionId: number): UniqueNFTCollection {1709    return new UniqueNFTCollection(collectionId, this.helper);1710  }17111712  /**1713   * Get token object1714   * @param collectionId ID of collection1715   * @param tokenId ID of token1716   * @example getTokenObject(10, 5);1717   * @returns instance of UniqueNFTToken1718   */1719  getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1720    return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1721  }17221723  /**1724   * Is token approved to transfer1725   * @param collectionId ID of collection1726   * @param tokenId ID of token1727   * @param toAccountObj address to be approved1728   * @returns ```true``` if extrinsic success, otherwise ```false```1729   */1730  async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1731    return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1732  }17331734  /**1735   * Changes the owner of the token.1736   *1737   * @param signer keyring of signer1738   * @param collectionId ID of collection1739   * @param tokenId ID of token1740   * @param addressObj address of a new owner1741   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1742   * @returns ```true``` if extrinsic success, otherwise ```false```1743   */1744  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1745    return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1746  }17471748  /**1749   *1750   * Change ownership of a NFT on behalf of the owner.1751   *1752   * @param signer keyring of signer1753   * @param collectionId ID of collection1754   * @param tokenId ID of token1755   * @param fromAddressObj address on behalf of which the token will be sent1756   * @param toAddressObj new token owner1757   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1758   * @returns ```true``` if extrinsic success, otherwise ```false```1759   */1760  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1761    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1762  }17631764  /**1765   * Get tokens nested in the provided token1766   * @param collectionId ID of collection1767   * @param tokenId ID of token1768   * @param blockHashAt optionally query the data at the block with this hash1769   * @example getTokenChildren(10, 5);1770   * @returns tokens whose depth of nesting is <= 51771   */1772  async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1773    let children;1774    if(typeof blockHashAt === 'undefined') {1775      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1776    } else {1777      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1778    }17791780    return children.toJSON().map((x: any) => ({collectionId: x.collection, tokenId: x.token}));1781  }17821783  /**1784   * Mint new collection1785   * @param signer keyring of signer1786   * @param collectionOptions Collection options1787   * @example1788   * mintCollection(aliceKeyring, {1789   *   name: 'New',1790   *   description: 'New collection',1791   *   tokenPrefix: 'NEW',1792   * })1793   * @returns object of the created collection1794   */1795  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1796    return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1797  }17981799  /**1800   * Mint new token1801   * @param signer keyring of signer1802   * @param data token data1803   * @returns created token object1804   */1805  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1806    const creationResult = await this.helper.executeExtrinsic(1807      signer,1808      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1809        NFT: {1810          properties: data.properties,1811        },1812      }],1813      true,1814    );1815    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1816    if(createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1817    if(createdTokens.tokens.length < 1) throw Error('No tokens minted');1818    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1819  }18201821  /**1822   * Mint multiple NFT tokens1823   * @param signer keyring of signer1824   * @param collectionId ID of collection1825   * @param tokens array of tokens with owner and properties1826   * @example1827   * mintMultipleTokens(aliceKeyring, 10, [{1828   *     owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1829   *     properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1830   *   },{1831   *     owner: {Ethereum: "0x9F0583DbB855d..."},1832   *     properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1833   * }]);1834   * @returns ```true``` if extrinsic success, otherwise ```false```1835   */1836  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: { owner: ICrossAccountId, properties?: IProperty[] }[]): Promise<UniqueNFToken[]> {1837    const creationResult = await this.helper.executeExtrinsic(1838      signer,1839      'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1840      true,1841    );1842    const collection = this.getCollectionObject(collectionId);1843    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1844  }18451846  /**1847   * Mint multiple NFT tokens with one owner1848   * @param signer keyring of signer1849   * @param collectionId ID of collection1850   * @param owner tokens owner1851   * @param tokens array of tokens with owner and properties1852   * @example1853   * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1854   *   properties: [{1855   *   key: "gender",1856   *   value: "female",1857   *  },{1858   *   key: "age",1859   *   value: "33",1860   *  }],1861   * }]);1862   * @returns array of newly created tokens1863   */1864  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: { properties?: IProperty[] }[]): Promise<UniqueNFToken[]> {1865    const rawTokens = [];1866    for(const token of tokens) {1867      const raw = {NFT: {properties: token.properties}};1868      rawTokens.push(raw);1869    }1870    const creationResult = await this.helper.executeExtrinsic(1871      signer,1872      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1873      true,1874    );1875    const collection = this.getCollectionObject(collectionId);1876    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1877  }18781879  /**1880   * Set, change, or remove approved address to transfer the ownership of the NFT.1881   *1882   * @param signer keyring of signer1883   * @param collectionId ID of collection1884   * @param tokenId ID of token1885   * @param toAddressObj address to approve1886   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1887   * @returns ```true``` if extrinsic success, otherwise ```false```1888   */1889  approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1890    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1891  }1892}189318941895class RFTGroup extends NFTnRFT {1896  /**1897   * Get collection object1898   * @param collectionId ID of collection1899   * @example getCollectionObject(2);1900   * @returns instance of UniqueRFTCollection1901   */1902  getCollectionObject(collectionId: number): UniqueRFTCollection {1903    return new UniqueRFTCollection(collectionId, this.helper);1904  }19051906  /**1907   * Get token object1908   * @param collectionId ID of collection1909   * @param tokenId ID of token1910   * @example getTokenObject(10, 5);1911   * @returns instance of UniqueNFTToken1912   */1913  getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1914    return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1915  }19161917  /**1918   * Get top 10 token owners with the largest number of pieces1919   * @param collectionId ID of collection1920   * @param tokenId ID of token1921   * @example getTokenTop10Owners(10, 5);1922   * @returns array of top 10 owners1923   */1924  async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1925    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1926  }19271928  /**1929   * Get number of pieces owned by address1930   * @param collectionId ID of collection1931   * @param tokenId ID of token1932   * @param addressObj address token owner1933   * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1934   * @returns number of pieces ownerd by address1935   */1936  async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1937    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1938  }19391940  /**1941   * Transfer pieces of token to another address1942   * @param signer keyring of signer1943   * @param collectionId ID of collection1944   * @param tokenId ID of token1945   * @param addressObj address of a new owner1946   * @param amount number of pieces to be transfered1947   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1948   * @returns ```true``` if extrinsic success, otherwise ```false```1949   */1950  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1951    return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1952  }19531954  /**1955   * Change ownership of some pieces of RFT on behalf of the owner.1956   * @param signer keyring of signer1957   * @param collectionId ID of collection1958   * @param tokenId ID of token1959   * @param fromAddressObj address on behalf of which the token will be sent1960   * @param toAddressObj new token owner1961   * @param amount number of pieces to be transfered1962   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1963   * @returns ```true``` if extrinsic success, otherwise ```false```1964   */1965  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1966    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1967  }19681969  /**1970   * Mint new collection1971   * @param signer keyring of signer1972   * @param collectionOptions Collection options1973   * @example1974   * mintCollection(aliceKeyring, {1975   *   name: 'New',1976   *   description: 'New collection',1977   *   tokenPrefix: 'NEW',1978   * })1979   * @returns object of the created collection1980   */1981  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1982    return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1983  }19841985  /**1986   * Mint new token1987   * @param signer keyring of signer1988   * @param data token data1989   * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1990   * @returns created token object1991   */1992  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1993    const creationResult = await this.helper.executeExtrinsic(1994      signer,1995      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1996        ReFungible: {1997          pieces: data.pieces,1998          properties: data.properties,1999        },2000      }],2001      true,2002    );2003    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);2004    if(createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');2005    if(createdTokens.tokens.length < 1) throw Error('No tokens minted');2006    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);2007  }20082009  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: { owner: ICrossAccountId, pieces: bigint, properties?: IProperty[] }[]): Promise<UniqueRFToken[]> {2010    throw Error('Not implemented');2011    const creationResult = await this.helper.executeExtrinsic(2012      signer,2013      'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],2014      true, // `Unable to mint RFT tokens for ${label}`,2015    );2016    const collection = this.getCollectionObject(collectionId);2017    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));2018  }20192020  /**2021   * Mint multiple RFT tokens with one owner2022   * @param signer keyring of signer2023   * @param collectionId ID of collection2024   * @param owner tokens owner2025   * @param tokens array of tokens with properties and pieces2026   * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);2027   * @returns array of newly created RFT tokens2028   */2029  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: { pieces: bigint, properties?: IProperty[] }[]): Promise<UniqueRFToken[]> {2030    const rawTokens = [];2031    for(const token of tokens) {2032      const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};2033      rawTokens.push(raw);2034    }2035    const creationResult = await this.helper.executeExtrinsic(2036      signer,2037      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2038      true,2039    );2040    const collection = this.getCollectionObject(collectionId);2041    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));2042  }20432044  /**2045   * Destroys a concrete instance of RFT.2046   * @param signer keyring of signer2047   * @param collectionId ID of collection2048   * @param tokenId ID of token2049   * @param amount number of pieces to be burnt2050   * @example burnToken(aliceKeyring, 10, 5);2051   * @returns ```true``` if the extrinsic is successful, otherwise ```false```2052   */2053  async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount = 1n): Promise<boolean> {2054    return await super.burnToken(signer, collectionId, tokenId, amount);2055  }20562057  /**2058   * Destroys a concrete instance of RFT on behalf of the owner.2059   * @param signer keyring of signer2060   * @param collectionId ID of collection2061   * @param tokenId ID of token2062   * @param fromAddressObj address on behalf of which the token will be burnt2063   * @param amount number of pieces to be burnt2064   * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)2065   * @returns ```true``` if extrinsic success, otherwise ```false```2066   */2067  async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {2068    return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);2069  }20702071  /**2072   * Set, change, or remove approved address to transfer the ownership of the RFT.2073   *2074   * @param signer keyring of signer2075   * @param collectionId ID of collection2076   * @param tokenId ID of token2077   * @param toAddressObj address to approve2078   * @param amount number of pieces to be approved2079   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);2080   * @returns true if the token success, otherwise false2081   */2082  approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {2083    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);2084  }20852086  /**2087   * Get total number of pieces2088   * @param collectionId ID of collection2089   * @param tokenId ID of token2090   * @example getTokenTotalPieces(10, 5);2091   * @returns number of pieces2092   */2093  async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {2094    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();2095  }20962097  /**2098   * Change number of token pieces. Signer must be the owner of all token pieces.2099   * @param signer keyring of signer2100   * @param collectionId ID of collection2101   * @param tokenId ID of token2102   * @param amount new number of pieces2103   * @example repartitionToken(aliceKeyring, 10, 5, 12345n);2104   * @returns true if the repartion was success, otherwise false2105   */2106  async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {2107    const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);2108    const repartitionResult = await this.helper.executeExtrinsic(2109      signer,2110      'api.tx.unique.repartition', [collectionId, tokenId, amount],2111      true,2112    );2113    if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');2114    return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');2115  }2116}211721182119class FTGroup extends CollectionGroup {2120  /**2121   * Get collection object2122   * @param collectionId ID of collection2123   * @example getCollectionObject(2);2124   * @returns instance of UniqueFTCollection2125   */2126  getCollectionObject(collectionId: number): UniqueFTCollection {2127    return new UniqueFTCollection(collectionId, this.helper);2128  }21292130  /**2131   * Mint new fungible collection2132   * @param signer keyring of signer2133   * @param collectionOptions Collection options2134   * @param decimalPoints number of token decimals2135   * @example2136   * mintCollection(aliceKeyring, {2137   *   name: 'New',2138   *   description: 'New collection',2139   *   tokenPrefix: 'NEW',2140   * }, 18)2141   * @returns newly created fungible collection2142   */2143  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {2144    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object2145    if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');2146    collectionOptions.mode = {fungible: decimalPoints};2147    for(const key of ['name', 'description', 'tokenPrefix']) {2148      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);2149    }2150    const creationResult = await this.helper.executeExtrinsic(2151      signer,2152      'api.tx.unique.createCollectionEx', [collectionOptions],2153      true,2154    );2155    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2156  }21572158  /**2159   * Mint tokens2160   * @param signer keyring of signer2161   * @param collectionId ID of collection2162   * @param owner address owner of new tokens2163   * @param amount amount of tokens to be meanted2164   * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);2165   * @returns ```true``` if extrinsic success, otherwise ```false```2166   */2167  async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2168    const creationResult = await this.helper.executeExtrinsic(2169      signer,2170      'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2171        Fungible: {2172          value: amount,2173        },2174      }],2175      true, // `Unable to mint fungible tokens for ${label}`,2176    );2177    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2178  }21792180  /**2181   * Mint multiple Fungible tokens with one owner2182   * @param signer keyring of signer2183   * @param collectionId ID of collection2184   * @param owner tokens owner2185   * @param tokens array of tokens with properties and pieces2186   * @returns ```true``` if extrinsic success, otherwise ```false```2187   */2188  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: { value: bigint }[], owner: ICrossAccountId): Promise<boolean> {2189    const rawTokens = [];2190    for(const token of tokens) {2191      const raw = {Fungible: {Value: token.value}};2192      rawTokens.push(raw);2193    }2194    const creationResult = await this.helper.executeExtrinsic(2195      signer,2196      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2197      true,2198    );2199    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2200  }22012202  /**2203   * Get the top 10 owners with the largest balance for the Fungible collection2204   * @param collectionId ID of collection2205   * @example getTop10Owners(10);2206   * @returns array of ```ICrossAccountId```2207   */2208  async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2209    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2210  }22112212  /**2213   * Get account balance2214   * @param collectionId ID of collection2215   * @param addressObj address of owner2216   * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2217   * @returns amount of fungible tokens owned by address2218   */2219  async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2220    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2221  }22222223  /**2224   * Transfer tokens to address2225   * @param signer keyring of signer2226   * @param collectionId ID of collection2227   * @param toAddressObj address recipient2228   * @param amount amount of tokens to be sent2229   * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2230   * @returns ```true``` if extrinsic success, otherwise ```false```2231   */2232  async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount = 1n) {2233    return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2234  }22352236  /**2237   * Transfer some tokens on behalf of the owner.2238   * @param signer keyring of signer2239   * @param collectionId ID of collection2240   * @param fromAddressObj address on behalf of which tokens will be sent2241   * @param toAddressObj address where token to be sent2242   * @param amount number of tokens to be sent2243   * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2244   * @returns ```true``` if extrinsic success, otherwise ```false```2245   */2246  async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {2247    return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2248  }22492250  /**2251   * Destroy some amount of tokens2252   * @param signer keyring of signer2253   * @param collectionId ID of collection2254   * @param amount amount of tokens to be destroyed2255   * @example burnTokens(aliceKeyring, 10, 1000n);2256   * @returns ```true``` if extrinsic success, otherwise ```false```2257   */2258  async burnTokens(signer: IKeyringPair, collectionId: number, amount = 1n): Promise<boolean> {2259    return await super.burnToken(signer, collectionId, 0, amount);2260  }22612262  /**2263   * Burn some tokens on behalf of the owner.2264   * @param signer keyring of signer2265   * @param collectionId ID of collection2266   * @param fromAddressObj address on behalf of which tokens will be burnt2267   * @param amount amount of tokens to be burnt2268   * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2269   * @returns ```true``` if extrinsic success, otherwise ```false```2270   */2271  async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {2272    return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2273  }22742275  /**2276   * Get total collection supply2277   * @param collectionId2278   * @returns2279   */2280  async getTotalPieces(collectionId: number): Promise<bigint> {2281    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2282  }22832284  /**2285   * Set, change, or remove approved address to transfer tokens.2286   *2287   * @param signer keyring of signer2288   * @param collectionId ID of collection2289   * @param toAddressObj address to be approved2290   * @param amount amount of tokens to be approved2291   * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2292   * @returns ```true``` if extrinsic success, otherwise ```false```2293   */2294  approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount = 1n) {2295    return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2296  }22972298  /**2299   * Get amount of fungible tokens approved to transfer2300   * @param collectionId ID of collection2301   * @param fromAddressObj owner of tokens2302   * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2303   * @returns number of tokens approved for the transfer2304   */2305  getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2306    return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2307  }2308}230923102311class ChainGroup extends HelperGroup<ChainHelperBase> {2312  /**2313   * Get system properties of a chain2314   * @example getChainProperties();2315   * @returns ss58Format, token decimals, and token symbol2316   */2317  getChainProperties(): IChainProperties {2318    const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2319    return {2320      ss58Format: properties.ss58Format.toJSON(),2321      tokenDecimals: properties.tokenDecimals.toJSON(),2322      tokenSymbol: properties.tokenSymbol.toJSON(),2323    };2324  }23252326  /**2327   * Get chain header2328   * @example getLatestBlockNumber();2329   * @returns the number of the last block2330   */2331  async getLatestBlockNumber(): Promise<number> {2332    return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2333  }23342335  /**2336   * Get block hash by block number2337   * @param blockNumber number of block2338   * @example getBlockHashByNumber(12345);2339   * @returns hash of a block2340   */2341  async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2342    const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2343    if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2344    return blockHash;2345  }23462347  // TODO add docs2348  async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2349    const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2350    if(!blockHash) return null;2351    return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2352  }23532354  /**2355   * Get latest relay block2356   * @returns {number} relay block2357   */2358  async getRelayBlockNumber(): Promise<bigint> {2359    const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2360    return BigInt(blockNumber);2361  }23622363  /**2364   * Get account nonce2365   * @param address substrate address2366   * @example getNonce("5GrwvaEF5zXb26Fz...");2367   * @returns number, account's nonce2368   */2369  async getNonce(address: TSubstrateAccount): Promise<number> {2370    return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2371  }2372}23732374class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2375  /**2376 * Get substrate address balance2377 * @param address substrate address2378 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2379 * @returns amount of tokens on address2380 */2381  async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2382    return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2383  }23842385  /**2386   * Transfer tokens to substrate address2387   * @param signer keyring of signer2388   * @param address substrate address of a recipient2389   * @param amount amount of tokens to be transfered2390   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2391   * @returns ```true``` if extrinsic success, otherwise ```false```2392   */2393  async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2394    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}`*/);23952396    let transfer = {from: null, to: null, amount: 0n} as any;2397    result.result.events.forEach(({event: {data, method, section}}) => {2398      if((section === 'balances') && (method === 'Transfer')) {2399        transfer = {2400          from: this.helper.address.normalizeSubstrate(data[0]),2401          to: this.helper.address.normalizeSubstrate(data[1]),2402          amount: BigInt(data[2]),2403        };2404      }2405    });2406    const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2407      && this.helper.address.normalizeSubstrate(address) === transfer.to2408      && BigInt(amount) === transfer.amount;2409    return isSuccess;2410  }24112412  /**2413   * Get full substrate balance including free, frozen, and reserved2414   * @param address substrate address2415   * @returns2416   */2417  async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2418    const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2419    return {free: accountInfo.free.toBigInt(), frozen: accountInfo.frozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2420  }24212422  /**2423   * Get total issuance2424   * @returns2425   */2426  async getTotalIssuance(): Promise<bigint> {2427    const total = (await this.helper.callRpc('api.query.balances.totalIssuance', []));2428    return total.toBigInt();2429  }24302431  async getLocked(address: TSubstrateAccount): Promise<{ id: string, amount: bigint, reason: string }[]> {2432    const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2433    return locks.map((lock: any) => ({id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons}));2434  }2435  async getFrozen(address: TSubstrateAccount): Promise<{ id: string, amount: bigint }[]> {2436    const locks = (await this.helper.api!.query.balances.freezes(address)) as unknown as Array<any>;2437    return locks.map(lock => ({id: lock.id.toUtf8(), amount: lock.amount.toBigInt()}));2438  }2439}24402441class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2442  /**2443   * Get ethereum address balance2444   * @param address ethereum address2445   * @example getEthereum("0x9F0583DbB855d...")2446   * @returns amount of tokens on address2447   */2448  async getEthereum(address: TEthereumAccount): Promise<bigint> {2449    return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2450  }24512452  /**2453   * Transfer tokens to address2454   * @param signer keyring of signer2455   * @param address Ethereum address of a recipient2456   * @param amount amount of tokens to be transfered2457   * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2458   * @returns ```true``` if extrinsic success, otherwise ```false```2459   */2460  async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2461    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);24622463    let transfer = {from: null, to: null, amount: 0n} as any;2464    result.result.events.forEach(({event: {data, method, section}}) => {2465      if((section === 'balances') && (method === 'Transfer')) {2466        transfer = {2467          from: data[0].toString(),2468          to: data[1].toString(),2469          amount: BigInt(data[2]),2470        };2471      }2472    });2473    const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2474      && address === transfer.to2475      && BigInt(amount) === transfer.amount;2476    return isSuccess;2477  }2478}24792480class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2481  subBalanceGroup: SubstrateBalanceGroup<T>;2482  ethBalanceGroup: EthereumBalanceGroup<T>;24832484  constructor(helper: T) {2485    super(helper);2486    this.subBalanceGroup = new SubstrateBalanceGroup(helper);2487    this.ethBalanceGroup = new EthereumBalanceGroup(helper);2488  }24892490  getCollectionCreationPrice(): bigint {2491    return 2n * this.getOneTokenNominal();2492  }2493  /**2494   * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2495   * @example getOneTokenNominal()2496   * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2497   */2498  getOneTokenNominal(): bigint {2499    const chainProperties = this.helper.chain.getChainProperties();2500    return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2501  }25022503  /**2504   * Get substrate address balance2505   * @param address substrate address2506   * @example getSubstrate("5GrwvaEF5zXb26Fz...")2507   * @returns amount of tokens on address2508   */2509  getSubstrate(address: TSubstrateAccount): Promise<bigint> {2510    return this.subBalanceGroup.getSubstrate(address);2511  }25122513  /**2514   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2515   * @param address substrate address2516   * @returns2517   */2518  getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2519    return this.subBalanceGroup.getSubstrateFull(address);2520  }25212522  /**2523   * Get total issuance2524   * @returns2525   */2526  getTotalIssuance(): Promise<bigint> {2527    return this.subBalanceGroup.getTotalIssuance();2528  }25292530  /**2531   * Get locked balances2532   * @param address substrate address2533   * @returns locked balances with reason via api.query.balances.locks2534   * @deprecated all the methods should switch to getFrozen2535   */2536  getLocked(address: TSubstrateAccount) {2537    return this.subBalanceGroup.getLocked(address);2538  }25392540  /**2541   * Get frozen balances2542   * @param address substrate address2543   * @returns frozen balances with id via api.query.balances.freezes2544   */2545  getFrozen(address: TSubstrateAccount) {2546    return this.subBalanceGroup.getFrozen(address);2547  }25482549  /**2550   * Get ethereum address balance2551   * @param address ethereum address2552   * @example getEthereum("0x9F0583DbB855d...")2553   * @returns amount of tokens on address2554   */2555  getEthereum(address: TEthereumAccount): Promise<bigint> {2556    return this.ethBalanceGroup.getEthereum(address);2557  }25582559  async setBalanceSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint) {2560    await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceSetBalance', [address, amount], true);2561  }25622563  /**2564   * Transfer tokens to substrate address2565   * @param signer keyring of signer2566   * @param address substrate address of a recipient2567   * @param amount amount of tokens to be transfered2568   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2569   * @returns ```true``` if extrinsic success, otherwise ```false```2570   */2571  transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2572    return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2573  }25742575  async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2576    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);25772578    let transfer = {from: null, to: null, amount: 0n} as any;2579    result.result.events.forEach(({event: {data, method, section}}) => {2580      if((section === 'balances') && (method === 'Transfer')) {2581        transfer = {2582          from: this.helper.address.normalizeSubstrate(data[0]),2583          to: this.helper.address.normalizeSubstrate(data[1]),2584          amount: BigInt(data[2]),2585        };2586      }2587    });2588    let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2589    isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2590    isSuccess = isSuccess && BigInt(amount) === transfer.amount;2591    return isSuccess;2592  }25932594  /**2595   * Transfer tokens with the unlock period2596   * @param signer signers Keyring2597   * @param address Substrate address of recipient2598   * @param schedule Schedule params2599   * @example vestedTransfer(signer, recepient.address, 20000, 100, 10, 50 * nominal); // total amount of vested tokens will be 100 * 50 = 50002600   */2601  async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: { start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint }): Promise<void> {2602    const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2603    const event = result.result.events2604      .find(e => e.event.section === 'vesting' &&2605        e.event.method === 'VestingScheduleAdded' &&2606        e.event.data[0].toHuman() === signer.address);2607    if(!event) throw Error('Cannot find transfer in events');2608  }26092610  /**2611   * Get schedule for recepient of vested transfer2612   * @param address Substrate address of recipient2613   * @returns2614   */2615  async getVestingSchedules(address: TSubstrateAccount): Promise<{ start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint }[]> {2616    const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2617    return schedule.map((schedule: any) => ({2618      start: BigInt(schedule.start),2619      period: BigInt(schedule.period),2620      periodCount: BigInt(schedule.periodCount),2621      perPeriod: BigInt(schedule.perPeriod),2622    }));2623  }26242625  /**2626   * Claim vested tokens2627   * @param signer signers Keyring2628   */2629  async claim(signer: TSigner) {2630    const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2631    const event = result.result.events2632      .find(e => e.event.section === 'vesting' &&2633        e.event.method === 'Claimed' &&2634        e.event.data[0].toHuman() === signer.address);2635    if(!event) throw Error('Cannot find claim in events');2636  }2637}26382639class AddressGroup extends HelperGroup<ChainHelperBase> {2640  /**2641   * Normalizes the address to the specified ss58 format, by default ```42```.2642   * @param address substrate address2643   * @param ss58Format format for address conversion, by default ```42```2644   * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2645   * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2646   */2647  normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2648    return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2649  }26502651  /**2652   * Get address in the connected chain format2653   * @param address substrate address2654   * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2655   * @returns address in chain format2656   */2657  normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2658    return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2659  }26602661  /**2662   * Get substrate mirror of an ethereum address2663   * @param ethAddress ethereum address2664   * @param toChainFormat false for normalized account2665   * @example ethToSubstrate('0x9F0583DbB855d...')2666   * @returns substrate mirror of a provided ethereum address2667   */2668  ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat = false): TSubstrateAccount {2669    return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2670  }26712672  /**2673   * Get ethereum mirror of a substrate address2674   * @param subAddress substrate account2675   * @example substrateToEth("5DnSF6RRjwteE3BrC...")2676   * @returns ethereum mirror of a provided substrate address2677   */2678  substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2679    return CrossAccountId.translateSubToEth(subAddress);2680  }26812682  /**2683   * Encode key to substrate address2684   * @param key key for encoding address2685   * @param ss58Format prefix for encoding to the address of the corresponding network2686   * @returns encoded substrate address2687   */2688  encodeSubstrateAddress(key: Uint8Array | string | bigint, ss58Format = 42): string {2689    const u8a: Uint8Array = typeof key === 'string'2690      ? hexToU8a(key)2691      : typeof key === 'bigint'2692        ? hexToU8a(key.toString(16))2693        : key;26942695    if(ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2696      throw new Error(`ss58Format is not valid, received ${typeof ss58Format} "${ss58Format}"`);2697    }26982699    const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2700    if(!allowedDecodedLengths.includes(u8a.length)) {2701      throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2702    }27032704    const u8aPrefix = ss58Format < 642705      ? new Uint8Array([ss58Format])2706      : new Uint8Array([2707        ((ss58Format & 0xfc) >> 2) | 0x40,2708        (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2709      ]);27102711    const input = u8aConcat(u8aPrefix, u8a);27122713    return base58Encode(u8aConcat(2714      input,2715      blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2716    ));2717  }27182719  /**2720   * Restore substrate address from bigint representation2721   * @param number decimal representation of substrate address2722   * @returns substrate address2723   */2724  restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2725    if(this.helper.api === null) {2726      throw 'Not connected';2727    }2728    const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2729    if(res === undefined || res === null) {2730      throw 'Restore address error';2731    }2732    return res.toString();2733  }27342735  /**2736   * Convert etherium cross account id to substrate cross account id2737   * @param ethCrossAccount etherium cross account2738   * @returns substrate cross account id2739   */2740  convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2741    if(ethCrossAccount.sub === '0') {2742      return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2743    }27442745    const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2746    return {Substrate: ss58};2747  }27482749  paraSiblingSovereignAccount(paraid: number) {2750    // We are getting a *sibling* parachain sovereign account,2751    // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2752    const siblingPrefix = '0x7369626c';27532754    const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2755    const suffix = '000000000000000000000000000000000000000000000000';27562757    return siblingPrefix + encodedParaId + suffix;2758  }2759}27602761class StakingGroup extends HelperGroup<UniqueHelper> {2762  /**2763   * Stake tokens for App Promotion2764   * @param signer keyring of signer2765   * @param amountToStake amount of tokens to stake2766   * @param label extra label for log2767   * @returns2768   */2769  async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2770    if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2771    const _stakeResult = await this.helper.executeExtrinsic(2772      signer, 'api.tx.appPromotion.stake',2773      [amountToStake], true,2774    );2775    // TODO extract info from stakeResult2776    return true;2777  }27782779  /**2780   * Unstake all staked tokens2781   * @param signer keyring of signer2782   * @param amountToUnstake amount of tokens to unstake2783   * @param label extra label for log2784   * @returns block hash where unstake happened2785   */2786  async unstakeAll(signer: TSigner, label?: string): Promise<string> {2787    if(typeof label === 'undefined') label = `${signer.address}`;2788    const unstakeResult = await this.helper.executeExtrinsic(2789      signer, 'api.tx.appPromotion.unstakeAll',2790      [], true,2791    );2792    return unstakeResult.blockHash;2793  }27942795  /**2796   * Unstake the part of a staked tokens2797   * @param signer keyring of signer2798   * @param amount amount of tokens to unstake2799   * @param label extra label for log2800   * @returns block hash where unstake happened2801   */2802  async unstakePartial(signer: TSigner, amount: bigint, label?: string): Promise<string> {2803    if(typeof label === 'undefined') label = `${signer.address}`;2804    const unstakeResult = await this.helper.executeExtrinsic(2805      signer, 'api.tx.appPromotion.unstakePartial',2806      [amount], true,2807    );2808    return unstakeResult.blockHash;2809  }28102811  /**2812   * Get total number of active stakes2813   * @param address substrate address2814   * @returns {number}2815   */2816  async getStakesNumber(address: ICrossAccountId): Promise<number> {2817    if('Ethereum' in address) throw Error('only substrate address');2818    return (await this.helper.callRpc('api.query.appPromotion.stakesPerAccount', [address.Substrate])).toNumber();2819  }28202821  /**2822   * Get total staked amount for address2823   * @param address substrate or ethereum address2824   * @returns total staked amount2825   */2826  async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2827    if(address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2828    return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2829  }28302831  /**2832   * Get total staked per block2833   * @param address substrate or ethereum address2834   * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2835   */2836  async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2837    const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2838    return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => ({2839      block: block.toBigInt(),2840      amount: amount.toBigInt(),2841    }));2842  }28432844  /**2845   * Get total pending unstake amount for address2846   * @param address substrate or ethereum address2847   * @returns total pending unstake amount2848   */2849  async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2850    return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2851  }28522853  /**2854   * Get pending unstake amount per block for address2855   * @param address substrate or ethereum address2856   * @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 block2857   */2858  async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2859    const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2860    const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => ({2861      block: block.toBigInt(),2862      amount: amount.toBigInt(),2863    }));2864    return result;2865  }2866}28672868class SchedulerGroup extends HelperGroup<UniqueHelper> {2869  constructor(helper: UniqueHelper) {2870    super(helper);2871  }28722873  cancelScheduled(signer: TSigner, scheduledId: string) {2874    return this.helper.executeExtrinsic(2875      signer,2876      'api.tx.scheduler.cancelNamed',2877      [scheduledId],2878      true,2879    );2880  }28812882  changePriority(signer: TSigner, scheduledId: string, priority: number) {2883    return this.helper.executeExtrinsic(2884      signer,2885      'api.tx.scheduler.changeNamedPriority',2886      [scheduledId, priority],2887      true,2888    );2889  }28902891  scheduleAt<T extends UniqueHelper>(2892    executionBlockNumber: number,2893    options: ISchedulerOptions = {},2894  ) {2895    return this.schedule<T>('schedule', executionBlockNumber, options);2896  }28972898  scheduleAfter<T extends UniqueHelper>(2899    blocksBeforeExecution: number,2900    options: ISchedulerOptions = {},2901  ) {2902    return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2903  }29042905  schedule<T extends UniqueHelper>(2906    scheduleFn: 'schedule' | 'scheduleAfter',2907    blocksNum: number,2908    options: ISchedulerOptions = {},2909  ) {2910    // eslint-disable-next-line @typescript-eslint/naming-convention2911    const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2912    return this.helper.clone(ScheduledHelperType, {2913      scheduleFn,2914      blocksNum,2915      options,2916    }) as T;2917  }2918}29192920class CollatorSelectionGroup extends HelperGroup<UniqueHelper> {2921  //todo:collator documentation2922  addInvulnerable(signer: TSigner, address: string) {2923    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.addInvulnerable', [address]);2924  }29252926  removeInvulnerable(signer: TSigner, address: string) {2927    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.removeInvulnerable', [address]);2928  }29292930  async getInvulnerables(): Promise<string[]> {2931    return (await this.helper.callRpc('api.query.collatorSelection.invulnerables')).map((x: any) => x.toHuman());2932  }29332934  /** and also total max invulnerables */2935  maxCollators(): number {2936    return (this.helper.getApi().consts.configuration.defaultCollatorSelectionMaxCollators.toJSON() as number);2937  }29382939  async getDesiredCollators(): Promise<number> {2940    return (await this.helper.callRpc('api.query.configuration.collatorSelectionDesiredCollatorsOverride')).toNumber();2941  }29422943  setLicenseBond(signer: TSigner, amount: bigint) {2944    return this.helper.executeExtrinsic(signer, 'api.tx.configuration.setCollatorSelectionLicenseBond', [amount]);2945  }29462947  async getLicenseBond(): Promise<bigint> {2948    return (await this.helper.callRpc('api.query.configuration.collatorSelectionLicenseBondOverride')).toBigInt();2949  }29502951  obtainLicense(signer: TSigner) {2952    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.getLicense', []);2953  }29542955  releaseLicense(signer: TSigner) {2956    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.releaseLicense', []);2957  }29582959  forceReleaseLicense(signer: TSigner, released: string) {2960    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.forceReleaseLicense', [released]);2961  }29622963  async hasLicense(address: string): Promise<bigint> {2964    return (await this.helper.callRpc('api.query.collatorSelection.licenseDepositOf', [address])).toBigInt();2965  }29662967  onboard(signer: TSigner) {2968    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.onboard', []);2969  }29702971  offboard(signer: TSigner) {2972    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.offboard', []);2973  }29742975  async getCandidates(): Promise<string[]> {2976    return (await this.helper.callRpc('api.query.collatorSelection.candidates')).map((x: any) => x.toHuman());2977  }2978}29792980class CollectiveGroup extends HelperGroup<UniqueHelper> {2981  /**2982   * Pallet name to make an API call to. Examples: 'council', 'technicalCommittee'2983   */2984  private collective: string;29852986  constructor(helper: UniqueHelper, collective: string) {2987    super(helper);2988    this.collective = collective;2989  }29902991  /**2992   * Check the result of a proposal execution for the success of the underlying proposed extrinsic.2993   * @param events events of the proposal execution2994   * @returns proposal hash2995   */2996  private checkExecutedEvent(events: IPhasicEvent[]): string {2997    const executionEvents = events.filter(x =>2998      x.event.section === this.collective && (x.event.method === 'Executed' || x.event.method === 'MemberExecuted'));29993000    if(executionEvents.length != 1) {3001      if(events.filter(x => x.event.section === this.collective && x.event.method === 'Disapproved').length > 0)3002        throw new Error(`Disapproved by ${this.collective}`);3003      else3004        throw new Error(`Expected one 'Executed' or 'MemberExecuted' event for ${this.collective}`);3005    }30063007    const result = (executionEvents[0].event.data as any).result;30083009    if(result.isErr) {3010      if(result.asErr.isModule) {3011        const error = result.asErr.asModule;3012        const metaError = this.helper.getApi()?.registry.findMetaError(error);3013        throw new Error(`Proposal execution failed with ${metaError.section}.${metaError.name}`);3014      } else {3015        throw new Error('Proposal execution failed with ' + result.asErr.toHuman());3016      }3017    }30183019    return (executionEvents[0].event.data as any).proposalHash;3020  }30213022  /**3023   * Returns an array of members' addresses.3024   */3025  async getMembers() {3026    return (await this.helper.callRpc(`api.query.${this.collective}.members`, [])).toHuman();3027  }30283029  /**3030   * Returns the optional address of the prime member of the collective.3031   */3032  async getPrimeMember() {3033    return (await this.helper.callRpc(`api.query.${this.collective}.prime`, [])).toHuman();3034  }30353036  /**3037   * Returns an array of proposal hashes that are currently active for this collective.3038   */3039  async getProposals() {3040    return (await this.helper.callRpc(`api.query.${this.collective}.proposals`, [])).toHuman();3041  }30423043  /**3044   * Returns the call originally encoded under the specified hash.3045   * @param hash h256-encoded proposal3046   * @returns the optional call that the proposal hash stands for.3047   */3048  async getProposalCallOf(hash: string) {3049    return (await this.helper.callRpc(`api.query.${this.collective}.proposalOf`, [hash])).toHuman();3050  }30513052  /**3053   * Returns the total number of proposals so far.3054   */3055  async getTotalProposalsCount() {3056    return (await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, [])).toNumber();3057  }30583059  /**3060   * Creates a new proposal up for voting. If the threshold is set to 1, the proposal will be executed immediately.3061   * @param signer keyring of the proposer3062   * @param proposal constructed call to be executed if the proposal is successful3063   * @param voteThreshold minimal number of votes for the proposal to be verified and executed3064   * @param lengthBound byte length of the encoded call3065   * @returns promise of extrinsic execution and its result3066   */3067  async propose(signer: TSigner, proposal: any, voteThreshold: number, lengthBound = 10000) {3068    return await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [voteThreshold, proposal, lengthBound]);3069  }30703071  /**3072   * Casts a vote to either approve or reject a proposal.3073   * @param signer keyring of the voter3074   * @param proposalHash hash of the proposal to be voted for3075   * @param proposalIndex absolute index of the proposal used for absolutely nothing but throwing pointless errors3076   * @param approve aye or nay3077   * @returns promise of extrinsic execution and its result3078   */3079  vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {3080    return this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve]);3081  }30823083  /**3084   * Executes a call immediately as a member of the collective. Needed for the Member origin.3085   * @param signer keyring of the executor member3086   * @param proposal constructed call to be executed by the member3087   * @param lengthBound byte length of the encoded call3088   * @returns promise of extrinsic execution3089   */3090  async execute(signer: TSigner, proposal: any, lengthBound = 10000) {3091    const result = await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.execute`, [proposal, lengthBound]);3092    this.checkExecutedEvent(result.result.events);3093    return result;3094  }30953096  /**3097   * Attempt to close and execute a proposal. Note that there must already be enough votes to meet the threshold set when proposing.3098   * @param signer keyring of the executor. Can be absolutely anyone.3099   * @param proposalHash hash of the proposal to close3100   * @param proposalIndex index of the proposal generated on its creation3101   * @param weightBound weight of the proposed call. Can be obtained by calling `paymentInfo()` on the call.3102   * @param lengthBound byte length of the encoded call3103   * @returns promise of extrinsic execution and its result3104   */3105  async close(3106    signer: TSigner,3107    proposalHash: string,3108    proposalIndex: number,3109    weightBound: [number, number] | any = [20_000_000_000, 1000_000],3110    lengthBound = 10_000,3111  ) {3112    const result = await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [3113      proposalHash,3114      proposalIndex,3115      weightBound,3116      lengthBound,3117    ]);3118    this.checkExecutedEvent(result.result.events);3119    return result;3120  }31213122  /**3123   * Shut down a proposal, regardless of its current state.3124   * @param signer keyring of the disapprover. Must be root3125   * @param proposalHash hash of the proposal to close3126   * @returns promise of extrinsic execution and its result3127   */3128  disapproveProposal(signer: TSigner, proposalHash: string) {3129    return this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.disapproveProposal`, [proposalHash]);3130  }3131}31323133class CollectiveMembershipGroup extends HelperGroup<UniqueHelper> {3134  /**3135   * Pallet name to make an API call to. Examples: 'councilMembership', 'technicalCommitteeMembership'3136   */3137  private membership: string;31383139  constructor(helper: UniqueHelper, membership: string) {3140    super(helper);3141    this.membership = membership;3142  }31433144  /**3145   * Returns an array of members' addresses according to the membership pallet's perception.3146   * Note that it does not recognize the original pallet's members set with `setMembers()`.3147   */3148  async getMembers() {3149    return (await this.helper.callRpc(`api.query.${this.membership}.members`, [])).toHuman();3150  }31513152  /**3153   * Returns the optional address of the prime member of the collective.3154   */3155  async getPrimeMember() {3156    return (await this.helper.callRpc(`api.query.${this.membership}.prime`, [])).toHuman();3157  }31583159  /**3160   * Add a member to the collective.3161   * @param signer keyring of the setter. Must be root3162   * @param member address of the member to add3163   * @returns promise of extrinsic execution and its result3164   */3165  addMember(signer: TSigner, member: string) {3166    return this.helper.executeExtrinsic(signer, `api.tx.${this.membership}.addMember`, [member]);3167  }31683169  addMemberCall(member: string) {3170    return this.helper.constructApiCall(`api.tx.${this.membership}.addMember`, [member]);3171  }31723173  /**3174   * Remove a member from the collective.3175   * @param signer keyring of the setter. Must be root3176   * @param member address of the member to remove3177   * @returns promise of extrinsic execution and its result3178   */3179  removeMember(signer: TSigner, member: string) {3180    return this.helper.executeExtrinsic(signer, `api.tx.${this.membership}.removeMember`, [member]);3181  }31823183  removeMemberCall(member: string) {3184    return this.helper.constructApiCall(`api.tx.${this.membership}.removeMember`, [member]);3185  }31863187  /**3188   * Set members of the collective to the given list of addresses.3189   * @param signer keyring of the setter. Must be root (for the direct call, bypassing a public motion)3190   * @param members addresses of the members to set3191   * @returns promise of extrinsic execution and its result3192   */3193  resetMembers(signer: TSigner, members: string[]) {3194    return this.helper.executeExtrinsic(signer, `api.tx.${this.membership}.resetMembers`, [members]);3195  }31963197  /**3198   * Set the collective's prime member to the given address.3199   * @param signer keyring of the setter. Must be root (for the direct call, bypassing a public motion)3200   * @param prime address of the prime member of the collective3201   * @returns promise of extrinsic execution and its result3202   */3203  setPrime(signer: TSigner, prime: string) {3204    return this.helper.executeExtrinsic(signer, `api.tx.${this.membership}.setPrime`, [prime]);3205  }32063207  setPrimeCall(member: string) {3208    return this.helper.constructApiCall(`api.tx.${this.membership}.setPrime`, [member]);3209  }32103211  /**3212   * Remove the collective's prime member.3213   * @param signer keyring of the setter. Must be root (for the direct call, bypassing a public motion)3214   * @returns promise of extrinsic execution and its result3215   */3216  clearPrime(signer: TSigner) {3217    return this.helper.executeExtrinsic(signer, `api.tx.${this.membership}.clearPrime`, []);3218  }32193220  clearPrimeCall() {3221    return this.helper.constructApiCall(`api.tx.${this.membership}.clearPrime`, []);3222  }3223}32243225class RankedCollectiveGroup extends HelperGroup<UniqueHelper> {3226  /**3227   * Pallet name to make an API call to. Examples: 'FellowshipCollective'3228   */3229  private collective: string;32303231  constructor(helper: UniqueHelper, collective: string) {3232    super(helper);3233    this.collective = collective;3234  }32353236  addMember(signer: TSigner, newMember: string) {3237    return this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.addMember`, [newMember]);3238  }32393240  addMemberCall(newMember: string) {3241    return this.helper.constructApiCall(`api.tx.${this.collective}.addMember`, [newMember]);3242  }32433244  removeMember(signer: TSigner, member: string, minRank: number) {3245    return this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.removeMember`, [member, minRank]);3246  }32473248  removeMemberCall(newMember: string, minRank: number) {3249    return this.helper.constructApiCall(`api.tx.${this.collective}.removeMember`, [newMember, minRank]);3250  }32513252  promote(signer: TSigner, member: string) {3253    return this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.promoteMember`, [member]);3254  }32553256  promoteCall(newMember: string) {3257    return this.helper.constructApiCall(`api.tx.${this.collective}.promoteMember`, [newMember]);3258  }32593260  demote(signer: TSigner, member: string) {3261    return this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.demoteMember`, [member]);3262  }32633264  demoteCall(newMember: string) {3265    return this.helper.constructApiCall(`api.tx.${this.collective}.demoteMember`, [newMember]);3266  }32673268  vote(signer: TSigner, pollIndex: number, aye: boolean) {3269    return this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [pollIndex, aye]);3270  }32713272  async getMembers() {3273    return (await this.helper.getApi().query.fellowshipCollective.members.keys())3274      .map((key) => key.args[0].toString());3275  }3276}32773278class ReferendaGroup extends HelperGroup<UniqueHelper> {3279  /**3280   * Pallet name to make an API call to. Examples: 'FellowshipReferenda'3281   */3282  private referenda: string;32833284  constructor(helper: UniqueHelper, referenda: string) {3285    super(helper);3286    this.referenda = referenda;3287  }32883289  submit(3290    signer: TSigner,3291    proposalOrigin: string,3292    proposal: any,3293    enactmentMoment: any,3294  ) {3295    return this.helper.executeExtrinsic(signer, `api.tx.${this.referenda}.submit`, [3296      {Origins: proposalOrigin},3297      proposal,3298      enactmentMoment,3299    ]);3300  }33013302  placeDecisionDeposit(signer: TSigner, referendumIndex: number) {3303    return this.helper.executeExtrinsic(signer, `api.tx.${this.referenda}.placeDecisionDeposit`, [referendumIndex]);3304  }33053306  cancel(signer: TSigner, referendumIndex: number) {3307    return this.helper.executeExtrinsic(signer, `api.tx.${this.referenda}.cancel`, [referendumIndex]);3308  }33093310  cancelCall(referendumIndex: number) {3311    return this.helper.constructApiCall(`api.tx.${this.referenda}.cancel`, [referendumIndex]);3312  }33133314  async referendumInfo(referendumIndex: number) {3315    return (await this.helper.callRpc(`api.query.${this.referenda}.referendumInfoFor`, [referendumIndex])).toJSON();3316  }33173318  async enactmentEventId(referendumIndex: number) {3319    const api = await this.helper.getApi();33203321    const bytes = api.createType('([u8;8], Text, u32)', ['assembly', 'enactment', referendumIndex]).toU8a();3322    return blake2AsHex(bytes, 256);3323  }3324}33253326export interface IFellowshipGroup {3327  collective: RankedCollectiveGroup;3328  referenda: ReferendaGroup;3329}33303331export interface ICollectiveGroup {3332  collective: CollectiveGroup;3333  membership: CollectiveMembershipGroup;3334}33353336class DemocracyGroup extends HelperGroup<UniqueHelper> {3337  // todo displace proposal into types?3338  propose(signer: TSigner, call: any, deposit: bigint) {3339    return this.helper.executeExtrinsic(signer, 'api.tx.democracy.propose', [{Inline: call.method.toHex()}, deposit]);3340  }33413342  proposeWithPreimage(signer: TSigner, preimage: string, deposit: bigint) {3343    return this.helper.executeExtrinsic(signer, 'api.tx.democracy.propose', [{Legacy: preimage}, deposit]);3344  }33453346  proposeCall(call: any, deposit: bigint) {3347    return this.helper.constructApiCall('api.tx.democracy.propose', [{Inline: call.method.toHex()}, deposit]);3348  }33493350  second(signer: TSigner, proposalIndex: number) {3351    return this.helper.executeExtrinsic(signer, 'api.tx.democracy.second', [proposalIndex]);3352  }33533354  externalPropose(signer: TSigner, proposalCall: any) {3355    return this.helper.executeExtrinsic(signer, 'api.tx.democracy.externalPropose', [{Inline: proposalCall.method.toHex()}]);3356  }33573358  externalProposeMajority(signer: TSigner, proposalCall: any) {3359    return this.helper.executeExtrinsic(signer, 'api.tx.democracy.externalProposeMajority', [{Inline: proposalCall.method.toHex()}]);3360  }33613362  externalProposeDefault(signer: TSigner, proposalCall: any) {3363    return this.helper.executeExtrinsic(signer, 'api.tx.democracy.externalProposeDefault', [{Inline: proposalCall.method.toHex()}]);3364  }33653366  externalProposeDefaultWithPreimage(signer: TSigner, preimage: string) {3367    return this.helper.executeExtrinsic(signer, 'api.tx.democracy.externalProposeDefault', [{Legacy: preimage}]);3368  }33693370  externalProposeCall(proposalCall: any) {3371    return this.helper.constructApiCall('api.tx.democracy.externalPropose', [{Inline: proposalCall.method.toHex()}]);3372  }33733374  externalProposeMajorityCall(proposalCall: any) {3375    return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [{Inline: proposalCall.method.toHex()}]);3376  }33773378  externalProposeDefaultCall(proposalCall: any) {3379    return this.helper.constructApiCall('api.tx.democracy.externalProposeDefault', [{Inline: proposalCall.method.toHex()}]);3380  }33813382  // ... and blacklist external proposal hash.3383  vetoExternal(signer: TSigner, proposalHash: string) {3384    return this.helper.executeExtrinsic(signer, 'api.tx.democracy.vetoExternal', [proposalHash]);3385  }33863387  vetoExternalCall(proposalHash: string) {3388    return this.helper.constructApiCall('api.tx.democracy.vetoExternal', [proposalHash]);3389  }33903391  blacklist(signer: TSigner, proposalHash: string, referendumIndex: number | null = null) {3392    return this.helper.executeExtrinsic(signer, 'api.tx.democracy.blacklist', [proposalHash, referendumIndex]);3393  }33943395  blacklistCall(proposalHash: string, referendumIndex: number | null = null) {3396    return this.helper.constructApiCall('api.tx.democracy.blacklist', [proposalHash, referendumIndex]);3397  }33983399  // proposal. CancelProposalOrigin (root or all techcom)3400  cancelProposal(signer: TSigner, proposalIndex: number) {3401    return this.helper.executeExtrinsic(signer, 'api.tx.democracy.cancelProposal', [proposalIndex]);3402  }34033404  cancelProposalCall(proposalIndex: number) {3405    return this.helper.constructApiCall('api.tx.democracy.cancelProposal', [proposalIndex]);3406  }34073408  clearPublicProposals(signer: TSigner) {3409    return this.helper.executeExtrinsic(signer, 'api.tx.democracy.clearPublicProposals', []);3410  }34113412  fastTrack(signer: TSigner, proposalHash: string, votingPeriod: number, delayPeriod: number) {3413    return this.helper.executeExtrinsic(signer, 'api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);3414  }34153416  fastTrackCall(proposalHash: string, votingPeriod: number, delayPeriod: number) {3417    return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);3418  }34193420  // referendum. CancellationOrigin (TechCom member)3421  emergencyCancel(signer: TSigner, referendumIndex: number) {3422    return this.helper.executeExtrinsic(signer, 'api.tx.democracy.emergencyCancel', [referendumIndex]);3423  }34243425  emergencyCancelCall(referendumIndex: number) {3426    return this.helper.constructApiCall('api.tx.democracy.emergencyCancel', [referendumIndex]);3427  }34283429  vote(signer: TSigner, referendumIndex: number, vote: any) {3430    return this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, vote]);3431  }34323433  removeVote(signer: TSigner, referendumIndex: number, targetAccount?: string) {3434    if(targetAccount) {3435      return this.helper.executeExtrinsic(signer, 'api.tx.democracy.removeOtherVote', [targetAccount, referendumIndex]);3436    } else {3437      return this.helper.executeExtrinsic(signer, 'api.tx.democracy.removeVote', [referendumIndex]);3438    }3439  }34403441  unlock(signer: TSigner, targetAccount: string) {3442    return this.helper.executeExtrinsic(signer, 'api.tx.democracy.unlock', [targetAccount]);3443  }34443445  delegate(signer: TSigner, toAccount: string, conviction: PalletDemocracyConviction, balance: bigint) {3446    return this.helper.executeExtrinsic(signer, 'api.tx.democracy.delegate', [toAccount, conviction, balance]);3447  }34483449  undelegate(signer: TSigner) {3450    return this.helper.executeExtrinsic(signer, 'api.tx.democracy.undelegate', []);3451  }34523453  async referendumInfo(referendumIndex: number) {3454    return (await this.helper.callRpc('api.query.democracy.referendumInfoOf', [referendumIndex])).toJSON();3455  }34563457  async publicProposals() {3458    return (await this.helper.callRpc('api.query.democracy.publicProps', [])).toJSON();3459  }34603461  async findPublicProposal(proposalIndex: number) {3462    const proposalInfo = (await this.publicProposals()).find((proposalInfo: any[]) => proposalInfo[0] == proposalIndex);34633464    return proposalInfo ? proposalInfo[1] : null;3465  }34663467  async expectPublicProposal(proposalIndex: number) {3468    const proposal = await this.findPublicProposal(proposalIndex);34693470    if(proposal) {3471      return proposal;3472    } else {3473      throw Error(`Proposal #${proposalIndex} is expected to exist`);3474    }3475  }34763477  async getExternalProposal() {3478    return (await this.helper.callRpc('api.query.democracy.nextExternal', []));3479  }34803481  async expectExternalProposal() {3482    const proposal = await this.getExternalProposal();34833484    if(proposal) {3485      return proposal;3486    } else {3487      throw Error('An external proposal is expected to exist');3488    }3489  }34903491  /* setMetadata? */34923493  /* todo?3494  referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {3495    return this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);3496  }*/3497}34983499class PreimageGroup extends HelperGroup<UniqueHelper> {3500  async getPreimageInfo(h256: string) {3501    return (await this.helper.callRpc('api.query.preimage.statusFor', [h256])).toJSON();3502  }35033504  /**3505   * Create a preimage from an API call.3506   * @param signer keyring of the signer.3507   * @param call an extrinsic call3508   * @example await notePreimageFromCall(preimageMaker,3509   *   helper.constructApiCall('api.tx.identity.forceInsertIdentities', [identitiesToAdd])3510   * );3511   * @returns promise of extrinsic execution.3512   */3513  notePreimageFromCall(signer: TSigner, call: any, returnPreimageHash = false) {3514    return this.notePreimage(signer, call.method.toHex(), returnPreimageHash);3515  }35163517  /**3518   * Create a preimage with a hex or a byte array.3519   * @param signer keyring of the signer.3520   * @param bytes preimage encoded in hex or a byte array, e.g. an extrinsic call.3521   * @example await notePreimage(preimageMaker,3522   *   helper.constructApiCall('api.tx.identity.forceInsertIdentities', [identitiesToAdd]).method.toHex()3523   * );3524   * @returns promise of extrinsic execution.3525   */3526  async notePreimage(signer: TSigner, bytes: string | Uint8Array, returnPreimageHash = false) {3527    const promise = this.helper.executeExtrinsic(signer, 'api.tx.preimage.notePreimage', [bytes]);3528    if(returnPreimageHash) {3529      const result = await promise;3530      const events = result.result.events.filter(x => x.event.method === 'Noted' && x.event.section === 'preimage');3531      const preimageHash = events[0].event.data[0].toHuman();3532      return preimageHash;3533    }3534    return promise;3535  }35363537  /**3538   * Delete an existing preimage and return the deposit.3539   * @param signer keyring of the signer - either the owner or the preimage manager (sudo).3540   * @param h256 hash of the preimage.3541   * @returns promise of extrinsic execution.3542   */3543  unnotePreimage(signer: TSigner, h256: string) {3544    return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unnotePreimage', [h256]);3545  }35463547  /**3548   * Request a preimage be uploaded to the chain without paying any fees or deposits.3549   * @param signer keyring of the signer - either the owner or the preimage manager (sudo).3550   * @param h256 hash of the preimage.3551   * @returns promise of extrinsic execution.3552   */3553  requestPreimage(signer: TSigner, h256: string) {3554    return this.helper.executeExtrinsic(signer, 'api.tx.preimage.requestPreimage', [h256]);3555  }35563557  /**3558   * Clear a previously made request for a preimage.3559   * @param signer keyring of the signer - either the owner or the preimage manager (sudo).3560   * @param h256 hash of the preimage.3561   * @returns promise of extrinsic execution.3562   */3563  unrequestPreimage(signer: TSigner, h256: string) {3564    return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unrequestPreimage', [h256]);3565  }3566}35673568class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {3569  async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {3570    await this.helper.executeExtrinsic(3571      signer,3572      'api.tx.foreignAssets.registerForeignAsset',3573      [ownerAddress, location, metadata],3574      true,3575    );3576  }35773578  async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {3579    await this.helper.executeExtrinsic(3580      signer,3581      'api.tx.foreignAssets.updateForeignAsset',3582      [foreignAssetId, location, metadata],3583      true,3584    );3585  }3586}35873588class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {3589  palletName: string;35903591  constructor(helper: T, palletName: string) {3592    super(helper);35933594    this.palletName = palletName;3595  }35963597  async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {3598    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);3599  }36003601  async setSafeXcmVersion(signer: TSigner, version: number) {3602    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.forceDefaultXcmVersion`, [version], true);3603  }36043605  async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {3606    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);3607  }36083609  async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint, xcmVersion = 3) {3610    const destinationContent = {3611      parents: 0,3612      interior: {3613        X1: {3614          Parachain: destinationParaId,3615        },3616      },3617    };36183619    const beneficiaryContent = {3620      parents: 0,3621      interior: {3622        X1: {3623          AccountId32: {3624            network: 'Any',3625            id: targetAccount,3626          },3627        },3628      },3629    };36303631    const assetsContent = [3632      {3633        id: {3634          Concrete: {3635            parents: 0,3636            interior: 'Here',3637          },3638        },3639        fun: {3640          Fungible: amount,3641        },3642      },3643    ];36443645    let destination;3646    let beneficiary;3647    let assets;36483649    if(xcmVersion == 2) {3650      destination = {V1: destinationContent};3651      beneficiary = {V1: beneficiaryContent};3652      assets = {V1: assetsContent};36533654    } else if(xcmVersion == 3) {3655      destination = {V2: destinationContent};3656      beneficiary = {V2: beneficiaryContent};3657      assets = {V2: assetsContent};36583659    } else {3660      throw Error('Unknown XCM version: ' + xcmVersion);3661    }36623663    const feeAssetItem = 0;36643665    await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);3666  }36673668  async send(signer: IKeyringPair, destination: any, message: any) {3669    await this.helper.executeExtrinsic(3670      signer,3671      `api.tx.${this.palletName}.send`,3672      [3673        destination,3674        message,3675      ],3676      true,3677    );3678  }3679}36803681class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {3682  async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {3683    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);3684  }36853686  async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {3687    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);3688  }36893690  async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {3691    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);3692  }3693}36943695class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {3696  async accounts(address: string, currencyId: any) {3697    const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;3698    return BigInt(free);3699  }3700}37013702class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {3703  async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {3704    await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);3705  }37063707  async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {3708    await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);3709  }37103711  async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {3712    await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);3713  }37143715  async account(assetId: string | number, address: string) {3716    const accountAsset = (3717      await this.helper.callRpc('api.query.assets.account', [assetId, address])3718    ).toJSON()! as any;37193720    if(accountAsset !== null) {3721      return BigInt(accountAsset['balance']);3722    } else {3723      return null;3724    }3725  }3726}37273728class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {3729  async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {3730    await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);3731  }3732}37333734class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {3735  makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {3736    const apiPrefix = 'api.tx.assetManager.';37373738    const registerTx = this.helper.constructApiCall(3739      apiPrefix + 'registerForeignAsset',3740      [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],3741    );37423743    const setUnitsTx = this.helper.constructApiCall(3744      apiPrefix + 'setAssetUnitsPerSecond',3745      [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],3746    );37473748    const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);3749    const encodedProposal = batchCall?.method.toHex() || '';3750    return encodedProposal;3751  }37523753  async assetTypeId(location: any) {3754    return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);3755  }3756}37573758class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {3759  notePreimagePallet: string;37603761  constructor(helper: MoonbeamHelper, options: { [key: string]: any } = {}) {3762    super(helper);3763    this.notePreimagePallet = options.notePreimagePallet;3764  }37653766  async notePreimage(signer: TSigner, encodedProposal: string) {3767    await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);3768  }37693770  externalProposeMajority(proposal: any) {3771    return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);3772  }37733774  fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {3775    return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);3776  }37773778  async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {3779    await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);3780  }3781}37823783class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {3784  collective: string;37853786  constructor(helper: MoonbeamHelper, collective: string) {3787    super(helper);37883789    this.collective = collective;3790  }37913792  async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {3793    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);3794  }37953796  async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {3797    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);3798  }37993800  async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {3801    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);3802  }38033804  async proposalCount() {3805    return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));3806  }3807}38083809export type ChainHelperBaseConstructor = new (...args: any[]) => ChainHelperBase;3810export type UniqueHelperConstructor = new (...args: any[]) => UniqueHelper;38113812export class UniqueHelper extends ChainHelperBase {3813  balance: BalanceGroup<UniqueHelper>;3814  collection: CollectionGroup;3815  nft: NFTGroup;3816  rft: RFTGroup;3817  ft: FTGroup;3818  staking: StakingGroup;3819  scheduler: SchedulerGroup;3820  collatorSelection: CollatorSelectionGroup;3821  council: ICollectiveGroup;3822  technicalCommittee: ICollectiveGroup;3823  fellowship: IFellowshipGroup;3824  democracy: DemocracyGroup;3825  preimage: PreimageGroup;3826  foreignAssets: ForeignAssetsGroup;3827  xcm: XcmGroup<UniqueHelper>;3828  xTokens: XTokensGroup<UniqueHelper>;3829  tokens: TokensGroup<UniqueHelper>;38303831  constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3832    super(logger, options.helperBase ?? UniqueHelper);38333834    this.balance = new BalanceGroup(this);3835    this.collection = new CollectionGroup(this);3836    this.nft = new NFTGroup(this);3837    this.rft = new RFTGroup(this);3838    this.ft = new FTGroup(this);3839    this.staking = new StakingGroup(this);3840    this.scheduler = new SchedulerGroup(this);3841    this.collatorSelection = new CollatorSelectionGroup(this);3842    this.council = {3843      collective: new CollectiveGroup(this, 'council'),3844      membership: new CollectiveMembershipGroup(this, 'councilMembership'),3845    };3846    this.technicalCommittee = {3847      collective: new CollectiveGroup(this, 'technicalCommittee'),3848      membership: new CollectiveMembershipGroup(this, 'technicalCommitteeMembership'),3849    };3850    this.fellowship = {3851      collective: new RankedCollectiveGroup(this, 'fellowshipCollective'),3852      referenda: new ReferendaGroup(this, 'fellowshipReferenda'),3853    };3854    this.democracy = new DemocracyGroup(this);3855    this.preimage = new PreimageGroup(this);3856    this.foreignAssets = new ForeignAssetsGroup(this);3857    this.xcm = new XcmGroup(this, 'polkadotXcm');3858    this.xTokens = new XTokensGroup(this);3859    this.tokens = new TokensGroup(this);3860  }38613862  getSudo<T extends UniqueHelper>() {3863    // eslint-disable-next-line @typescript-eslint/naming-convention3864    const SudoHelperType = SudoHelper(this.helperBase);3865    return this.clone(SudoHelperType) as T;3866  }3867}38683869export class XcmChainHelper extends ChainHelperBase {3870  async connect(wsEndpoint: string, _listeners?: any): Promise<void> {3871    const wsProvider = new WsProvider(wsEndpoint);3872    this.api = new ApiPromise({3873      provider: wsProvider,3874    });3875    await this.api.isReadyOrError;3876    this.network = await UniqueHelper.detectNetwork(this.api);3877  }3878}38793880export class RelayHelper extends XcmChainHelper {3881  balance: SubstrateBalanceGroup<RelayHelper>;3882  xcm: XcmGroup<RelayHelper>;38833884  constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3885    super(logger, options.helperBase ?? RelayHelper);38863887    this.balance = new SubstrateBalanceGroup(this);3888    this.xcm = new XcmGroup(this, 'xcmPallet');3889  }3890}38913892export class WestmintHelper extends XcmChainHelper {3893  balance: SubstrateBalanceGroup<WestmintHelper>;3894  xcm: XcmGroup<WestmintHelper>;3895  assets: AssetsGroup<WestmintHelper>;3896  xTokens: XTokensGroup<WestmintHelper>;38973898  constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3899    super(logger, options.helperBase ?? WestmintHelper);39003901    this.balance = new SubstrateBalanceGroup(this);3902    this.xcm = new XcmGroup(this, 'polkadotXcm');3903    this.assets = new AssetsGroup(this);3904    this.xTokens = new XTokensGroup(this);3905  }3906}39073908export class MoonbeamHelper extends XcmChainHelper {3909  balance: EthereumBalanceGroup<MoonbeamHelper>;3910  assetManager: MoonbeamAssetManagerGroup;3911  assets: AssetsGroup<MoonbeamHelper>;3912  xTokens: XTokensGroup<MoonbeamHelper>;3913  democracy: MoonbeamDemocracyGroup;3914  collective: {3915    council: MoonbeamCollectiveGroup,3916    techCommittee: MoonbeamCollectiveGroup,3917  };39183919  constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3920    super(logger, options.helperBase ?? MoonbeamHelper);39213922    this.balance = new EthereumBalanceGroup(this);3923    this.assetManager = new MoonbeamAssetManagerGroup(this);3924    this.assets = new AssetsGroup(this);3925    this.xTokens = new XTokensGroup(this);3926    this.democracy = new MoonbeamDemocracyGroup(this, options);3927    this.collective = {3928      council: new MoonbeamCollectiveGroup(this, 'councilCollective'),3929      techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),3930    };3931  }3932}39333934export class AstarHelper extends XcmChainHelper {3935  balance: SubstrateBalanceGroup<AstarHelper>;3936  assets: AssetsGroup<AstarHelper>;3937  xcm: XcmGroup<AstarHelper>;39383939  constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3940    super(logger, options.helperBase ?? AstarHelper);39413942    this.balance = new SubstrateBalanceGroup(this);3943    this.assets = new AssetsGroup(this);3944    this.xcm = new XcmGroup(this, 'polkadotXcm');3945  }39463947  getSudo<T extends UniqueHelper>() {3948    // eslint-disable-next-line @typescript-eslint/naming-convention3949    const SudoHelperType = SudoHelper(this.helperBase);3950    return this.clone(SudoHelperType) as T;3951  }3952}39533954export class AcalaHelper extends XcmChainHelper {3955  balance: SubstrateBalanceGroup<AcalaHelper>;3956  assetRegistry: AcalaAssetRegistryGroup;3957  xTokens: XTokensGroup<AcalaHelper>;3958  tokens: TokensGroup<AcalaHelper>;3959  xcm: XcmGroup<AcalaHelper>;39603961  constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3962    super(logger, options.helperBase ?? AcalaHelper);39633964    this.balance = new SubstrateBalanceGroup(this);3965    this.assetRegistry = new AcalaAssetRegistryGroup(this);3966    this.xTokens = new XTokensGroup(this);3967    this.tokens = new TokensGroup(this);3968    this.xcm = new XcmGroup(this, 'polkadotXcm');3969  }39703971  getSudo<T extends AcalaHelper>() {3972    // eslint-disable-next-line @typescript-eslint/naming-convention3973    const SudoHelperType = SudoHelper(this.helperBase);3974    return this.clone(SudoHelperType) as T;3975  }3976}39773978// eslint-disable-next-line @typescript-eslint/naming-convention3979function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3980  return class extends Base {3981    scheduleFn: 'schedule' | 'scheduleAfter';3982    blocksNum: number;3983    options: ISchedulerOptions;39843985    constructor(...args: any[]) {3986      const logger = args[0] as ILogger;3987      const options = args[1] as {3988        scheduleFn: 'schedule' | 'scheduleAfter',3989        blocksNum: number,3990        options: ISchedulerOptions3991      };39923993      super(logger);39943995      this.scheduleFn = options.scheduleFn;3996      this.blocksNum = options.blocksNum;3997      this.options = options.options;3998    }39994000    executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {4001      const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);40024003      const mandatorySchedArgs = [4004        this.blocksNum,4005        this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,4006        this.options.priority ?? null,4007        scheduledTx,4008      ];40094010      let schedArgs;4011      let scheduleFn;40124013      if(this.options.scheduledId) {4014        schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];40154016        if(this.scheduleFn == 'schedule') {4017          scheduleFn = 'scheduleNamed';4018        } else if(this.scheduleFn == 'scheduleAfter') {4019          scheduleFn = 'scheduleNamedAfter';4020        }4021      } else {4022        schedArgs = mandatorySchedArgs;4023        scheduleFn = this.scheduleFn;4024      }40254026      const extrinsic = 'api.tx.scheduler.' + scheduleFn;40274028      return super.executeExtrinsic(4029        sender,4030        extrinsic as any,4031        schedArgs,4032        expectSuccess,4033      );4034    }4035  };4036}40374038// eslint-disable-next-line @typescript-eslint/naming-convention4039function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {4040  return class extends Base {4041    constructor(...args: any[]) {4042      super(...args);4043    }40444045    async executeExtrinsic(4046      sender: IKeyringPair,4047      extrinsic: string,4048      params: any[],4049      expectSuccess?: boolean,4050      options: Partial<SignerOptions> | null = null,4051    ): Promise<ITransactionResult> {4052      const call = this.constructApiCall(extrinsic, params);4053      const result = await super.executeExtrinsic(4054        sender,4055        'api.tx.sudo.sudo',4056        [call],4057        expectSuccess,4058        options,4059      );40604061      if(result.status === 'Fail') return result;40624063      const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;4064      if(data.isErr) {4065        if(data.asErr.isModule) {4066          const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;4067          const metaError = super.getApi()?.registry.findMetaError(error);4068          throw new Error(`${metaError.section}.${metaError.name}`);4069        } else if(data.asErr.isToken) {4070          throw new Error(`Token: ${data.asErr.asToken}`);4071        }4072        // May be [object Object] in case of unhandled non-unit enum4073        throw new Error(`Misc: ${data.asErr.toHuman()}`);4074      }4075      return result;4076    }4077    async executeExtrinsicUncheckedWeight(4078      sender: IKeyringPair,4079      extrinsic: string,4080      params: any[],4081      expectSuccess?: boolean,4082      options: Partial<SignerOptions> | null = null,4083    ): Promise<ITransactionResult> {4084      const call = this.constructApiCall(extrinsic, params);4085      const result = await super.executeExtrinsic(4086        sender,4087        'api.tx.sudo.sudoUncheckedWeight',4088        [call, {refTime: 0, proofSize: 0}],4089        expectSuccess,4090        options,4091      );40924093      if(result.status === 'Fail') return result;40944095      const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;4096      if(data.isErr) {4097        if(data.asErr.isModule) {4098          const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;4099          const metaError = super.getApi()?.registry.findMetaError(error);4100          throw new Error(`${metaError.section}.${metaError.name}`);4101        } else if(data.asErr.isToken) {4102          throw new Error(`Token: ${data.asErr.asToken}`);4103        }4104        // May be [object Object] in case of unhandled non-unit enum4105        throw new Error(`Misc: ${data.asErr.toHuman()}`);4106      }4107      return result;4108    }4109  };4110}41114112export class UniqueBaseCollection {4113  helper: UniqueHelper;4114  collectionId: number;41154116  constructor(collectionId: number, uniqueHelper: UniqueHelper) {4117    this.collectionId = collectionId;4118    this.helper = uniqueHelper;4119  }41204121  async getData() {4122    return await this.helper.collection.getData(this.collectionId);4123  }41244125  async getLastTokenId() {4126    return await this.helper.collection.getLastTokenId(this.collectionId);4127  }41284129  async doesTokenExist(tokenId: number) {4130    return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);4131  }41324133  async getAdmins() {4134    return await this.helper.collection.getAdmins(this.collectionId);4135  }41364137  async getAllowList() {4138    return await this.helper.collection.getAllowList(this.collectionId);4139  }41404141  async getEffectiveLimits() {4142    return await this.helper.collection.getEffectiveLimits(this.collectionId);4143  }41444145  async getProperties(propertyKeys?: string[] | null) {4146    return await this.helper.collection.getProperties(this.collectionId, propertyKeys);4147  }41484149  async getPropertiesConsumedSpace() {4150    return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);4151  }41524153  async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {4154    return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);4155  }41564157  async getOptions() {4158    return await this.helper.collection.getCollectionOptions(this.collectionId);4159  }41604161  async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {4162    return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);4163  }41644165  async confirmSponsorship(signer: TSigner) {4166    return await this.helper.collection.confirmSponsorship(signer, this.collectionId);4167  }41684169  async removeSponsor(signer: TSigner) {4170    return await this.helper.collection.removeSponsor(signer, this.collectionId);4171  }41724173  async setLimits(signer: TSigner, limits: ICollectionLimits) {4174    return await this.helper.collection.setLimits(signer, this.collectionId, limits);4175  }41764177  async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {4178    return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);4179  }41804181  async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {4182    return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);4183  }41844185  async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {4186    return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);4187  }41884189  async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {4190    return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);4191  }41924193  async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {4194    return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);4195  }41964197  async setProperties(signer: TSigner, properties: IProperty[]) {4198    return await this.helper.collection.setProperties(signer, this.collectionId, properties);4199  }42004201  async deleteProperties(signer: TSigner, propertyKeys: string[]) {4202    return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);4203  }42044205  async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {4206    return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);4207  }42084209  async enableNesting(signer: TSigner, permissions: INestingPermissions) {4210    return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);4211  }42124213  async disableNesting(signer: TSigner) {4214    return await this.helper.collection.disableNesting(signer, this.collectionId);4215  }42164217  async burn(signer: TSigner) {4218    return await this.helper.collection.burn(signer, this.collectionId);4219  }42204221  scheduleAt<T extends UniqueHelper>(4222    executionBlockNumber: number,4223    options: ISchedulerOptions = {},4224  ) {4225    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);4226    return new UniqueBaseCollection(this.collectionId, scheduledHelper);4227  }42284229  scheduleAfter<T extends UniqueHelper>(4230    blocksBeforeExecution: number,4231    options: ISchedulerOptions = {},4232  ) {4233    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);4234    return new UniqueBaseCollection(this.collectionId, scheduledHelper);4235  }42364237  getSudo<T extends UniqueHelper>() {4238    return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());4239  }4240}424142424243export class UniqueNFTCollection extends UniqueBaseCollection {4244  getTokenObject(tokenId: number) {4245    return new UniqueNFToken(tokenId, this);4246  }42474248  async getTokensByAddress(addressObj: ICrossAccountId) {4249    return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);4250  }42514252  async getToken(tokenId: number, blockHashAt?: string) {4253    return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);4254  }42554256  async getTokenOwner(tokenId: number, blockHashAt?: string) {4257    return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);4258  }42594260  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {4261    return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);4262  }42634264  async getTokenChildren(tokenId: number, blockHashAt?: string) {4265    return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);4266  }42674268  async getPropertyPermissions(propertyKeys: string[] | null = null) {4269    return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);4270  }42714272  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {4273    return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);4274  }42754276  async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {4277    const api = this.helper.getApi();4278    const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();42794280    return (props! as any).consumedSpace;4281  }42824283  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {4284    return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);4285  }42864287  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {4288    return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);4289  }42904291  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {4292    return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);4293  }42944295  async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {4296    return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);4297  }42984299  async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {4300    return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});4301  }43024303  async mintMultipleTokens(signer: TSigner, tokens: { owner: ICrossAccountId, properties?: IProperty[] }[]) {4304    return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);4305  }43064307  async burnToken(signer: TSigner, tokenId: number) {4308    return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);4309  }43104311  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {4312    return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);4313  }43144315  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {4316    return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);4317  }43184319  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {4320    return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);4321  }43224323  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {4324    return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);4325  }43264327  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {4328    return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);4329  }43304331  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {4332    return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);4333  }43344335  scheduleAt<T extends UniqueHelper>(4336    executionBlockNumber: number,4337    options: ISchedulerOptions = {},4338  ) {4339    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);4340    return new UniqueNFTCollection(this.collectionId, scheduledHelper);4341  }43424343  scheduleAfter<T extends UniqueHelper>(4344    blocksBeforeExecution: number,4345    options: ISchedulerOptions = {},4346  ) {4347    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);4348    return new UniqueNFTCollection(this.collectionId, scheduledHelper);4349  }43504351  getSudo<T extends UniqueHelper>() {4352    return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());4353  }4354}435543564357export class UniqueRFTCollection extends UniqueBaseCollection {4358  getTokenObject(tokenId: number) {4359    return new UniqueRFToken(tokenId, this);4360  }43614362  async getToken(tokenId: number, blockHashAt?: string) {4363    return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);4364  }43654366  async getTokenOwner(tokenId: number, blockHashAt?: string) {4367    return await this.helper.rft.getTokenOwner(this.collectionId, tokenId, blockHashAt);4368  }43694370  async getTokensByAddress(addressObj: ICrossAccountId) {4371    return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);4372  }43734374  async getTop10TokenOwners(tokenId: number) {4375    return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);4376  }43774378  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {4379    return await this.helper.rft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);4380  }43814382  async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {4383    return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);4384  }43854386  async getTokenTotalPieces(tokenId: number) {4387    return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);4388  }43894390  async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {4391    return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);4392  }43934394  async getPropertyPermissions(propertyKeys: string[] | null = null) {4395    return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);4396  }43974398  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {4399    return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);4400  }44014402  async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {4403    const api = this.helper.getApi();4404    const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();44054406    return (props! as any).consumedSpace;4407  }44084409  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount = 1n) {4410    return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);4411  }44124413  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {4414    return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);4415  }44164417  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {4418    return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);4419  }44204421  async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {4422    return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);4423  }44244425  async mintToken(signer: TSigner, pieces = 1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {4426    return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});4427  }44284429  async mintMultipleTokens(signer: TSigner, tokens: { pieces: bigint, owner: ICrossAccountId, properties?: IProperty[] }[]) {4430    return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);4431  }44324433  async burnToken(signer: TSigner, tokenId: number, amount = 1n) {4434    return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);4435  }44364437  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n) {4438    return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);4439  }44404441  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {4442    return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);4443  }44444445  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {4446    return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);4447  }44484449  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {4450    return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);4451  }44524453  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {4454    return await this.helper.rft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);4455  }44564457  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {4458    return await this.helper.rft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);4459  }44604461  scheduleAt<T extends UniqueHelper>(4462    executionBlockNumber: number,4463    options: ISchedulerOptions = {},4464  ) {4465    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);4466    return new UniqueRFTCollection(this.collectionId, scheduledHelper);4467  }44684469  scheduleAfter<T extends UniqueHelper>(4470    blocksBeforeExecution: number,4471    options: ISchedulerOptions = {},4472  ) {4473    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);4474    return new UniqueRFTCollection(this.collectionId, scheduledHelper);4475  }44764477  getSudo<T extends UniqueHelper>() {4478    return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());4479  }4480}448144824483export class UniqueFTCollection extends UniqueBaseCollection {4484  async getBalance(addressObj: ICrossAccountId) {4485    return await this.helper.ft.getBalance(this.collectionId, addressObj);4486  }44874488  async getTotalPieces() {4489    return await this.helper.ft.getTotalPieces(this.collectionId);4490  }44914492  async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {4493    return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);4494  }44954496  async getTop10Owners() {4497    return await this.helper.ft.getTop10Owners(this.collectionId);4498  }44994500  async mint(signer: TSigner, amount = 1n, owner: ICrossAccountId = {Substrate: signer.address}) {4501    return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);4502  }45034504  async mintWithOneOwner(signer: TSigner, tokens: { value: bigint }[], owner: ICrossAccountId = {Substrate: signer.address}) {4505    return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);4506  }45074508  async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {4509    return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);4510  }45114512  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {4513    return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);4514  }45154516  async burnTokens(signer: TSigner, amount = 1n) {4517    return await this.helper.ft.burnTokens(signer, this.collectionId, amount);4518  }45194520  async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount = 1n) {4521    return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);4522  }45234524  async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {4525    return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);4526  }45274528  scheduleAt<T extends UniqueHelper>(4529    executionBlockNumber: number,4530    options: ISchedulerOptions = {},4531  ) {4532    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);4533    return new UniqueFTCollection(this.collectionId, scheduledHelper);4534  }45354536  scheduleAfter<T extends UniqueHelper>(4537    blocksBeforeExecution: number,4538    options: ISchedulerOptions = {},4539  ) {4540    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);4541    return new UniqueFTCollection(this.collectionId, scheduledHelper);4542  }45434544  getSudo<T extends UniqueHelper>() {4545    return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());4546  }4547}454845494550export class UniqueBaseToken {4551  collection: UniqueNFTCollection | UniqueRFTCollection;4552  collectionId: number;4553  tokenId: number;45544555  constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {4556    this.collection = collection;4557    this.collectionId = collection.collectionId;4558    this.tokenId = tokenId;4559  }45604561  async getNextSponsored(addressObj: ICrossAccountId) {4562    return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);4563  }45644565  async getProperties(propertyKeys?: string[] | null) {4566    return await this.collection.getTokenProperties(this.tokenId, propertyKeys);4567  }45684569  async getTokenPropertiesConsumedSpace() {4570    return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);4571  }45724573  async setProperties(signer: TSigner, properties: IProperty[]) {4574    return await this.collection.setTokenProperties(signer, this.tokenId, properties);4575  }45764577  async deleteProperties(signer: TSigner, propertyKeys: string[]) {4578    return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);4579  }45804581  async doesExist() {4582    return await this.collection.doesTokenExist(this.tokenId);4583  }45844585  nestingAccount() {4586    return this.collection.helper.util.getTokenAccount(this);4587  }45884589  scheduleAt<T extends UniqueHelper>(4590    executionBlockNumber: number,4591    options: ISchedulerOptions = {},4592  ) {4593    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);4594    return new UniqueBaseToken(this.tokenId, scheduledCollection);4595  }45964597  scheduleAfter<T extends UniqueHelper>(4598    blocksBeforeExecution: number,4599    options: ISchedulerOptions = {},4600  ) {4601    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);4602    return new UniqueBaseToken(this.tokenId, scheduledCollection);4603  }46044605  getSudo<T extends UniqueHelper>() {4606    return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());4607  }4608}460946104611export class UniqueNFToken extends UniqueBaseToken {4612  collection: UniqueNFTCollection;46134614  constructor(tokenId: number, collection: UniqueNFTCollection) {4615    super(tokenId, collection);4616    this.collection = collection;4617  }46184619  async getData(blockHashAt?: string) {4620    return await this.collection.getToken(this.tokenId, blockHashAt);4621  }46224623  async getOwner(blockHashAt?: string) {4624    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);4625  }46264627  async getTopmostOwner(blockHashAt?: string) {4628    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);4629  }46304631  async getChildren(blockHashAt?: string) {4632    return await this.collection.getTokenChildren(this.tokenId, blockHashAt);4633  }46344635  async nest(signer: TSigner, toTokenObj: IToken) {4636    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);4637  }46384639  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {4640    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);4641  }46424643  async transfer(signer: TSigner, addressObj: ICrossAccountId) {4644    return await this.collection.transferToken(signer, this.tokenId, addressObj);4645  }46464647  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {4648    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);4649  }46504651  async approve(signer: TSigner, toAddressObj: ICrossAccountId) {4652    return await this.collection.approveToken(signer, this.tokenId, toAddressObj);4653  }46544655  async isApproved(toAddressObj: ICrossAccountId) {4656    return await this.collection.isTokenApproved(this.tokenId, toAddressObj);4657  }46584659  async burn(signer: TSigner) {4660    return await this.collection.burnToken(signer, this.tokenId);4661  }46624663  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {4664    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);4665  }46664667  scheduleAt<T extends UniqueHelper>(4668    executionBlockNumber: number,4669    options: ISchedulerOptions = {},4670  ) {4671    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);4672    return new UniqueNFToken(this.tokenId, scheduledCollection);4673  }46744675  scheduleAfter<T extends UniqueHelper>(4676    blocksBeforeExecution: number,4677    options: ISchedulerOptions = {},4678  ) {4679    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);4680    return new UniqueNFToken(this.tokenId, scheduledCollection);4681  }46824683  getSudo<T extends UniqueHelper>() {4684    return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());4685  }4686}46874688export class UniqueRFToken extends UniqueBaseToken {4689  collection: UniqueRFTCollection;46904691  constructor(tokenId: number, collection: UniqueRFTCollection) {4692    super(tokenId, collection);4693    this.collection = collection;4694  }46954696  async getData(blockHashAt?: string) {4697    return await this.collection.getToken(this.tokenId, blockHashAt);4698  }46994700  async getOwner(blockHashAt?: string) {4701    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);4702  }47034704  async getTop10Owners() {4705    return await this.collection.getTop10TokenOwners(this.tokenId);4706  }47074708  async getTopmostOwner(blockHashAt?: string) {4709    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);4710  }47114712  async nest(signer: TSigner, toTokenObj: IToken) {4713    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);4714  }47154716  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {4717    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);4718  }47194720  async getBalance(addressObj: ICrossAccountId) {4721    return await this.collection.getTokenBalance(this.tokenId, addressObj);4722  }47234724  async getTotalPieces() {4725    return await this.collection.getTokenTotalPieces(this.tokenId);4726  }47274728  async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {4729    return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);4730  }47314732  async transfer(signer: TSigner, addressObj: ICrossAccountId, amount = 1n) {4733    return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);4734  }47354736  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {4737    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);4738  }47394740  async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {4741    return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);4742  }47434744  async repartition(signer: TSigner, amount: bigint) {4745    return await this.collection.repartitionToken(signer, this.tokenId, amount);4746  }47474748  async burn(signer: TSigner, amount = 1n) {4749    return await this.collection.burnToken(signer, this.tokenId, amount);4750  }47514752  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount = 1n) {4753    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);4754  }47554756  scheduleAt<T extends UniqueHelper>(4757    executionBlockNumber: number,4758    options: ISchedulerOptions = {},4759  ) {4760    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);4761    return new UniqueRFToken(this.tokenId, scheduledCollection);4762  }47634764  scheduleAfter<T extends UniqueHelper>(4765    blocksBeforeExecution: number,4766    options: ISchedulerOptions = {},4767  ) {4768    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);4769    return new UniqueRFToken(this.tokenId, scheduledCollection);4770  }47714772  getSudo<T extends UniqueHelper>() {4773    return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());4774  }4775}