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

difftreelog

source

tests/src/util/playgrounds/unique.ts97.1 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IChainEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {15  const address = {} as ICrossAccountId;16  if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;17  if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;18  return address;19};202122const nesting = {23  toChecksumAddress(address: string): string {24    if (typeof address === 'undefined') return '';2526    if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);2728    address = address.toLowerCase().replace(/^0x/i,'');29    const addressHash = keccakAsHex(address).replace(/^0x/i,'');30    const checksumAddress = ['0x'];3132    for (let i = 0; i < address.length; i++) {33      // If ith character is 8 to f then make it uppercase34      if (parseInt(addressHash[i], 16) > 7) {35        checksumAddress.push(address[i].toUpperCase());36      } else {37        checksumAddress.push(address[i]);38      }39    }40    return checksumAddress.join('');41  },42  tokenIdToAddress(collectionId: number, tokenId: number) {43    return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);44  },45};4647class UniqueUtil {48  static transactionStatus = {49    NOT_READY: 'NotReady',50    FAIL: 'Fail',51    SUCCESS: 'Success',52  };5354  static chainLogType = {55    EXTRINSIC: 'extrinsic',56    RPC: 'rpc',57  };5859  static getNestingTokenAddress(collectionId: number, tokenId: number) {60    return nesting.tokenIdToAddress(collectionId, tokenId);61  }6263  static getDefaultLogger(): ILogger {64    return {65      log(msg: any, level = 'INFO') {66        console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));67      },68      level: {69        ERROR: 'ERROR',70        WARNING: 'WARNING',71        INFO: 'INFO',72      },73    };74  }7576  static vec2str(arr: string[] | number[]) {77    return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');78  }7980  static str2vec(string: string) {81    if (typeof string !== 'string') return string;82    return Array.from(string).map(x => x.charCodeAt(0));83  }8485  static fromSeed(seed: string, ss58Format = 42) {86    const keyring = new Keyring({type: 'sr25519', ss58Format});87    return keyring.addFromUri(seed);88  }8990  static normalizeSubstrateAddress(address: string, ss58Format = 42) {91    return encodeAddress(decodeAddress(address), ss58Format);92  }9394  static extractCollectionIdFromCreationResult(creationResult: ITransactionResult, label = 'new collection') {95    if (creationResult.status !== this.transactionStatus.SUCCESS) {96      throw Error(`Unable to create collection for ${label}`);97    }9899    let collectionId = null;100    creationResult.result.events.forEach(({event: {data, method, section}}) => {101      if ((section === 'common') && (method === 'CollectionCreated')) {102        collectionId = parseInt(data[0].toString(), 10);103      }104    });105106    if (collectionId === null) {107      throw Error(`No CollectionCreated event for ${label}`);108    }109110    return collectionId;111  }112113  static extractTokensFromCreationResult(creationResult: ITransactionResult, label = 'new tokens') {114    if (creationResult.status !== this.transactionStatus.SUCCESS) {115      throw Error(`Unable to create tokens for ${label}`);116    }117    let success = false;118    const tokens = [] as any;119    creationResult.result.events.forEach(({event: {data, method, section}}) => {120      if (method === 'ExtrinsicSuccess') {121        success = true;122      } else if ((section === 'common') && (method === 'ItemCreated')) {123        tokens.push({124          collectionId: parseInt(data[0].toString(), 10),125          tokenId: parseInt(data[1].toString(), 10),126          owner: data[2].toJSON(),127        });128      }129    });130    return {success, tokens};131  }132133  static extractTokensFromBurnResult(burnResult: ITransactionResult, label = 'burned tokens') {134    if (burnResult.status !== this.transactionStatus.SUCCESS) {135      throw Error(`Unable to burn tokens for ${label}`);136    }137    let success = false;138    const tokens = [] as any;139    burnResult.result.events.forEach(({event: {data, method, section}}) => {140      if (method === 'ExtrinsicSuccess') {141        success = true;142      } else if ((section === 'common') && (method === 'ItemDestroyed')) {143        tokens.push({144          collectionId: parseInt(data[0].toString(), 10),145          tokenId: parseInt(data[1].toString(), 10),146          owner: data[2].toJSON(),147        });148      }149    });150    return {success, tokens};151  }152153  static findCollectionInEvents(events: {event: IChainEvent}[], collectionId: number, expectedSection: string, expectedMethod: string, label?: string) {154    let eventId = null;155    events.forEach(({event: {data, method, section}}) => {156      if ((section === expectedSection) && (method === expectedMethod)) {157        eventId = parseInt(data[0].toString(), 10);158      }159    });160161    if (eventId === null) {162      throw Error(`No ${expectedMethod} event for ${label}`);163    }164    return eventId === collectionId;165  }166167  static isTokenTransferSuccess(events: {event: IChainEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {168    const normalizeAddress = (address: string | ICrossAccountId) => {169      if(typeof address === 'string') return address;170      const obj = {} as any;171      Object.keys(address).forEach(k => {172        obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];173      });174      if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};175      if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};176      return address;177    };178    let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;179    events.forEach(({event: {data, method, section}}) => {180      if ((section === 'common') && (method === 'Transfer')) {181        const hData = (data as any).toJSON();182        transfer = {183          collectionId: hData[0],184          tokenId: hData[1],185          from: normalizeAddress(hData[2]),186          to: normalizeAddress(hData[3]),187          amount: BigInt(hData[4]),188        };189      }190    });191    let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;192    isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);193    isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);194    isSuccess = isSuccess && amount === transfer.amount;195    return isSuccess;196  }197}198199200class ChainHelperBase {201  transactionStatus = UniqueUtil.transactionStatus;202  chainLogType = UniqueUtil.chainLogType;203  util: typeof UniqueUtil;204  logger: ILogger;205  api: ApiPromise | null;206  forcedNetwork: TUniqueNetworks | null;207  network: TUniqueNetworks | null;208  chainLog: IUniqueHelperLog[];209210  constructor(logger?: ILogger) {211    this.util = UniqueUtil;212    if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();213    this.logger = logger;214    this.api = null;215    this.forcedNetwork = null;216    this.network = null;217    this.chainLog = [];218  }219220  clearChainLog(): void {221    this.chainLog = [];222  }223224  forceNetwork(value: TUniqueNetworks): void {225    this.forcedNetwork = value;226  }227228  async connect(wsEndpoint: string, listeners?: IApiListeners) {229    if (this.api !== null) throw Error('Already connected');230    const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);231    this.api = api;232    this.network = network;233  }234235  async disconnect() {236    if (this.api === null) return;237    await this.api.disconnect();238    this.api = null;239    this.network = null;240  }241242  static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {243    const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;244    if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;245    return 'opal';246  }247248  static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {249    const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});250    await api.isReady;251252    const network = await this.detectNetwork(api);253254    await api.disconnect();255256    return network;257  }258259  static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{ 260    api: ApiPromise; 261    network: TUniqueNetworks; 262  }> {263    if(typeof network === 'undefined' || network === null) network = 'opal';264    const supportedRPC = {265      opal: {266        unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,267      },268      quartz: {269        unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,270      },271      unique: {272        unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,273      },274    };275    if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);276    const rpc = supportedRPC[network];277278    // TODO: investigate how to replace rpc in runtime279    // api._rpcCore.addUserInterfaces(rpc);280281    const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});282283    await api.isReadyOrError;284285    if (typeof listeners === 'undefined') listeners = {};286    for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {287      if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;288      api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);289    }290291    return {api, network};292  }293294  getTransactionStatus(data: {events: {event: IChainEvent}[], status: any}) {295    const {events, status} = data;296    if (status.isReady) {297      return this.transactionStatus.NOT_READY;298    }299    if (status.isBroadcast) {300      return this.transactionStatus.NOT_READY;301    }302    if (status.isInBlock || status.isFinalized) {303      const errors = events.filter(e => e.event.data.method === 'ExtrinsicFailed');304      if (errors.length > 0) {305        return this.transactionStatus.FAIL;306      }307      if (events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {308        return this.transactionStatus.SUCCESS;309      }310    }311312    return this.transactionStatus.FAIL;313  }314315  signTransaction(sender: TSigner, transaction: any, label = 'transaction', options: any = null) {316    const sign = (callback: any) => {317      if(options !== null) return transaction.signAndSend(sender, options, callback);318      return transaction.signAndSend(sender, callback);319    };320    return new Promise(async (resolve, reject) => {321      try {322        const unsub = await sign((result: any) => {323          const status = this.getTransactionStatus(result);324325          if (status === this.transactionStatus.SUCCESS) {326            this.logger.log(`${label} successful`);327            unsub();328            resolve({result, status});329          } else if (status === this.transactionStatus.FAIL) {330            let moduleError = null;331332            if (result.hasOwnProperty('dispatchError')) {333              const dispatchError = result['dispatchError'];334335              if (dispatchError && dispatchError.isModule) {336                const modErr = dispatchError.asModule;337                const errorMeta = dispatchError.registry.findMetaError(modErr);338339                moduleError = `${errorMeta.section}.${errorMeta.name}`;340              }341              else {342                this.logger.log(result, this.logger.level.ERROR);343              }344            }345346            this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);347            unsub();348            reject({status, moduleError, result});349          }350        });351      } catch (e) {352        this.logger.log(e, this.logger.level.ERROR);353        reject(e);354      }355    });356  }357358  constructApiCall(apiCall: string, params: any[]) {359    if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);360    let call = this.api as any;361    for(const part of apiCall.slice(4).split('.')) {362      call = call[part];363    }364    return call(...params);365  }366367  async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=false, failureMessage='expected success') {368    if(this.api === null) throw Error('API not initialized');369    if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);370371    const startTime = (new Date()).getTime();372    let result: ITransactionResult;373    let events = [];374    try {375      result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), extrinsic) as ITransactionResult;376      events = result.result.events.map((x: any) => x.toHuman());377    }378    catch(e) {379      if(!(e as object).hasOwnProperty('status')) throw e;380      result = e as ITransactionResult;381    }382383    const endTime = (new Date()).getTime();384385    const log = {386      executedAt: endTime,387      executionTime: endTime - startTime,388      type: this.chainLogType.EXTRINSIC,389      status: result.status,390      call: extrinsic,391      signer: this.getSignerAddress(sender),392      params,393    } as IUniqueHelperLog;394395    if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;396    if(events.length > 0) log.events = events;397398    this.chainLog.push(log);399400    if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(failureMessage);401    return result;402  }403404  async callRpc(rpc: string, params?: any[]) {405    if(typeof params === 'undefined') params = [];406    if(this.api === null) throw Error('API not initialized');407    if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);408409    const startTime = (new Date()).getTime();410    let result;411    let error = null;412    const log = {413      type: this.chainLogType.RPC,414      call: rpc,415      params,416    } as IUniqueHelperLog;417418    try {419      result = await this.constructApiCall(rpc, params);420    }421    catch(e) {422      error = e;423    }424425    const endTime = (new Date()).getTime();426427    log.executedAt = endTime;428    log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';429    log.executionTime = endTime - startTime;430431    this.chainLog.push(log);432433    if(error !== null) throw error;434435    return result;436  }437438  getSignerAddress(signer: IKeyringPair | string): string {439    if(typeof signer === 'string') return signer;440    return signer.address;441  }442}443444445class HelperGroup {446  helper: UniqueHelper;447448  constructor(uniqueHelper: UniqueHelper) {449    this.helper = uniqueHelper;450  }451}452453454class CollectionGroup extends HelperGroup {455  /**456 * Get number of blocks when sponsored transaction is available.457 *458 * @param collectionId ID of collection459 * @param tokenId ID of token460 * @param addressObj address for which the sponsorship is checked461 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});462 * @returns number of blocks or null if sponsorship hasn't been set463 */464  async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {465    return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();466  }467468  /**469   * Get the number of created collections.470   * 471   * @returns number of created collections472   */473  async getTotalCount(): Promise<number> {474    return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();475  }476477  /**478   * Get information about the collection with additional data, including the number of tokens it contains, its administrators, the normalized address of the collection's owner, and decoded name and description.479   * 480   * @param collectionId ID of collection481   * @example await getData(2)482   * @returns collection information object483   */484  async getData(collectionId: number): Promise<{485    id: number;486    name: string;487    description: string;488    tokensCount: number;489    admins: ICrossAccountId[];490    normalizedOwner: TSubstrateAccount;491    raw: any492  } | null> {493    const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);494    const humanCollection = collection.toHuman(), collectionData = {495      id: collectionId, name: null, description: null, tokensCount: 0, admins: [],496      raw: humanCollection,497    } as any, jsonCollection = collection.toJSON();498    if (humanCollection === null) return null;499    collectionData.raw.limits = jsonCollection.limits;500    collectionData.raw.permissions = jsonCollection.permissions;501    collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);502    for (const key of ['name', 'description']) {503      collectionData[key] = this.helper.util.vec2str(humanCollection[key]);504    }505506    collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode)) ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId) : 0;507    collectionData.admins = await this.getAdmins(collectionId);508509    return collectionData;510  }511512  /**513   * Get the normalized addresses of the collection's administrators.514   * 515   * @param collectionId ID of collection516   * @example await getAdmins(1)517   * @returns array of administrators518   */519  async getAdmins(collectionId: number): Promise<ICrossAccountId[]> {520    const normalized = [];521    for(const admin of (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman()) {522      if(admin.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(admin.Substrate)});523      else normalized.push(admin);524    }525    return normalized;526  }527528  /**529   * Get the normalized addresses added to the collection allow-list.530   * @param collectionId ID of collection531   * @example await getAllowList(1)532   * @returns array of allow-listed addresses533   */534  async getAllowList(collectionId: number): Promise<ICrossAccountId[]> {535    const normalized = [];536    const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();537    for (const address of allowListed) {538      if (address.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(address.Substrate)});539      else normalized.push(address);540    }541    return normalized;542  }543544  /**545   * Get the effective limits of the collection instead of null for default values546   * 547   * @param collectionId ID of collection548   * @example await getEffectiveLimits(2)549   * @returns object of collection limits550   */551  async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {552    return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();553  }554555  /**556   * Burns the collection if the signer has sufficient permissions and collection is empty.557   * 558   * @param signer keyring of signer559   * @param collectionId ID of collection560   * @param label extra label for log561   * @example await helper.collection.burn(aliceKeyring, 3);562   * @returns ```true``` if extrinsic success, otherwise ```false```563   */564  async burn(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {565    if(typeof label === 'undefined') label = `collection #${collectionId}`;566    const result = await this.helper.executeExtrinsic(567      signer,568      'api.tx.unique.destroyCollection', [collectionId],569      true, `Unable to burn collection for ${label}`,570    );571572    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed', label);573  }574575  /**576   * Sets the sponsor for the collection (Requires the Substrate address).577   * 578   * @param signer keyring of signer579   * @param collectionId ID of collection580   * @param sponsorAddress Sponsor substrate address581   * @param label extra label for log582   * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")583   * @returns ```true``` if extrinsic success, otherwise ```false```584   */585  async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount, label?: string): Promise<boolean> {586    if(typeof label === 'undefined') label = `collection #${collectionId}`;587    const result = await this.helper.executeExtrinsic(588      signer,589      'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],590      true, `Unable to set collection sponsor for ${label}`,591    );592593    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet', label);594  }595596  /**597   * Confirms consent to sponsor the collection on behalf of the signer.598   * 599   * @param signer keyring of signer600   * @param collectionId ID of collection601   * @param label extra label for log602   * @example confirmSponsorship(aliceKeyring, 10)603   * @returns ```true``` if extrinsic success, otherwise ```false```604   */605  async confirmSponsorship(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {606    if(typeof label === 'undefined') label = `collection #${collectionId}`;607    const result = await this.helper.executeExtrinsic(608      signer,609      'api.tx.unique.confirmSponsorship', [collectionId],610      true, `Unable to confirm collection sponsorship for ${label}`,611    );612613    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed', label);614  }615616  /**617   * Sets the limits of the collection. At least one limit must be specified for a correct call.618   * 619   * @param signer keyring of signer620   * @param collectionId ID of collection621   * @param limits collection limits object622   * @param label extra label for log623   * @example624   * await setLimits(625   *   aliceKeyring,626   *   10,627   *   {628   *     sponsorTransferTimeout: 0,629   *     ownerCanDestroy: false630   *   }631   * )632   * @returns ```true``` if extrinsic success, otherwise ```false```633   */634  async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits, label?: string): Promise<boolean> {635    if(typeof label === 'undefined') label = `collection #${collectionId}`;636    const result = await this.helper.executeExtrinsic(637      signer,638      'api.tx.unique.setCollectionLimits', [collectionId, limits],639      true, `Unable to set collection limits for ${label}`,640    );641642    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet', label);643  }644645  /**646   * Changes the owner of the collection to the new Substrate address.647   * 648   * @param signer keyring of signer649   * @param collectionId ID of collection650   * @param ownerAddress substrate address of new owner651   * @param label extra label for log652   * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")653   * @returns ```true``` if extrinsic success, otherwise ```false```654   */655  async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount, label?: string): Promise<boolean> {656    if(typeof label === 'undefined') label = `collection #${collectionId}`;657    const result = await this.helper.executeExtrinsic(658      signer,659      'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],660      true, `Unable to change collection owner for ${label}`,661    );662663    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged', label);664  }665666  /**667   * Adds a collection administrator. 668   * 669   * @param signer keyring of signer670   * @param collectionId ID of collection671   * @param adminAddressObj Administrator address (substrate or ethereum)672   * @param label extra label for log673   * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})674   * @returns ```true``` if extrinsic success, otherwise ```false```675   */676  async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {677    if(typeof label === 'undefined') label = `collection #${collectionId}`;678    const result = await this.helper.executeExtrinsic(679      signer,680      'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],681      true, `Unable to add collection admin for ${label}`,682    );683684    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded', label);685  }686687  /**688   * Adds an address to allow list 689   * @param signer keyring of signer690   * @param collectionId ID of collection691   * @param addressObj address to add to the allow list692   * @param label extra label for log693   * @returns ```true``` if extrinsic success, otherwise ```false```694   */695  async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId, label?: string): Promise<boolean> {696    if(typeof label === 'undefined') label = `collection #${collectionId}`;697    const result = await this.helper.executeExtrinsic(698      signer,699      'api.tx.unique.addToAllowList', [collectionId, addressObj],700      true, `Unable to add address to allow list for ${label}`,701    );702703    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');704  }705706  /**707   * Removes a collection administrator.708   * 709   * @param signer keyring of signer710   * @param collectionId ID of collection711   * @param adminAddressObj Administrator address (substrate or ethereum)712   * @param label extra label for log713   * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})714   * @returns ```true``` if extrinsic success, otherwise ```false```715   */716  async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {717    if(typeof label === 'undefined') label = `collection #${collectionId}`;718    const result = await this.helper.executeExtrinsic(719      signer,720      'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],721      true, `Unable to remove collection admin for ${label}`,722    );723724    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved', label);725  }726727  /**728   * Sets onchain permissions for selected collection.729   * 730   * @param signer keyring of signer731   * @param collectionId ID of collection732   * @param permissions collection permissions object733   * @param label extra label for log734   * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});735   * @returns ```true``` if extrinsic success, otherwise ```false```736   */737  async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions, label?: string): Promise<boolean> {738    if(typeof label === 'undefined') label = `collection #${collectionId}`;739    const result = await this.helper.executeExtrinsic(740      signer,741      'api.tx.unique.setCollectionPermissions', [collectionId, permissions],742      true, `Unable to set collection permissions for ${label}`,743    );744745    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet', label);746  }747748  /**749   * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.750   * 751   * @param signer keyring of signer752   * @param collectionId ID of collection753   * @param permissions nesting permissions object754   * @param label extra label for log755   * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});756   * @returns ```true``` if extrinsic success, otherwise ```false```757   */758  async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions, label?: string): Promise<boolean> {759    return await this.setPermissions(signer, collectionId, {nesting: permissions}, label);760  }761762  /**763   * Disables nesting for selected collection.764   * 765   * @param signer keyring of signer766   * @param collectionId ID of collection767   * @param label extra label for log768   * @example disableNesting(aliceKeyring, 10);769   * @returns ```true``` if extrinsic success, otherwise ```false```770   */771  async disableNesting(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {772    return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}}, label);773  }774775  /**776   * Sets onchain properties to the collection.777   * 778   * @param signer keyring of signer779   * @param collectionId ID of collection780   * @param properties array of property objects781   * @param label extra label for log782   * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);783   * @returns ```true``` if extrinsic success, otherwise ```false```784   */785  async setProperties(signer: TSigner, collectionId: number, properties: IProperty[], label?: string): Promise<boolean> {786    if(typeof label === 'undefined') label = `collection #${collectionId}`;787    const result = await this.helper.executeExtrinsic(788      signer,789      'api.tx.unique.setCollectionProperties', [collectionId, properties],790      true, `Unable to set collection properties for ${label}`,791    );792793    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet', label);794  }795796  /**797   * Deletes onchain properties from the collection.798   * 799   * @param signer keyring of signer800   * @param collectionId ID of collection801   * @param propertyKeys array of property keys to delete802   * @param label803   * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);804   * @returns ```true``` if extrinsic success, otherwise ```false```805   */806  async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[], label?: string): Promise<boolean> {807    if(typeof label === 'undefined') label = `collection #${collectionId}`;808    const result = await this.helper.executeExtrinsic(809      signer,810      'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],811      true, `Unable to delete collection properties for ${label}`,812    );813814    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted', label);815  }816817  /**818   * Changes the owner of the token.819   * 820   * @param signer keyring of signer821   * @param collectionId ID of collection822   * @param tokenId ID of token823   * @param addressObj address of a new owner824   * @param amount amount of tokens to be transfered. For NFT must be set to 1n825   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})826   * @returns true if the token success, otherwise false827   */828  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {829    const result = await this.helper.executeExtrinsic(830      signer,831      'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],832      true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,833    );834835    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);836  }837838  /**839   * 840   * Change ownership of a token(s) on behalf of the owner. 841   * 842   * @param signer keyring of signer843   * @param collectionId ID of collection844   * @param tokenId ID of token845   * @param fromAddressObj address on behalf of which the token will be sent846   * @param toAddressObj new token owner847   * @param amount amount of tokens to be transfered. For NFT must be set to 1n848   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})849   * @returns true if the token success, otherwise false850   */851  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {852    const result = await this.helper.executeExtrinsic(853      signer,854      'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],855      true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,856    );857    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);858  }859860  /**861   * 862   * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.863   * 864   * @param signer keyring of signer865   * @param collectionId ID of collection866   * @param tokenId ID of token867   * @param label 868   * @param amount amount of tokens to be burned. For NFT must be set to 1n869   * @example burnToken(aliceKeyring, 10, 5);870   * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```871   */872  async burnToken(signer: TSigner, collectionId: number, tokenId: number, label?: string, amount=1n): Promise<{873    success: boolean,874    token: number | null875  }> {876    if(typeof label === 'undefined') label = `collection #${collectionId}`;877    const burnResult = await this.helper.executeExtrinsic(878      signer,879      'api.tx.unique.burnItem', [collectionId, tokenId, amount],880      true, `Unable to burn token for ${label}`,881    );882    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);883    if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');884    return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};885  }886887  /**888   * Destroys a concrete instance of NFT on behalf of the owner889   * 890   * @param signer keyring of signer891   * @param collectionId ID of collection892   * @param fromAddressObj address on behalf of which the token will be burnt893   * @param tokenId ID of token894   * @param label 895   * @param amount amount of tokens to be burned. For NFT must be set to 1n896   * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})897   * @returns ```true``` if extrinsic success, otherwise ```false```898   */899  async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, label?: string, amount=1n): Promise<boolean> {900    if(typeof label === 'undefined') label = `collection #${collectionId}`;901    const burnResult = await this.helper.executeExtrinsic(902      signer,903      'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],904      true, `Unable to burn token from for ${label}`,905    );906    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);907    return burnedTokens.success && burnedTokens.tokens.length > 0;908  }909910  /**911   * Set, change, or remove approved address to transfer the ownership of the NFT.912   * 913   * @param signer keyring of signer914   * @param collectionId ID of collection915   * @param tokenId ID of token916   * @param toAddressObj 917   * @param label 918   * @param amount amount of token to be approved. For NFT must be set to 1n919   * @returns ```true``` if extrinsic success, otherwise ```false```920   */921  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=1n) {922    if(typeof label === 'undefined') label = `collection #${collectionId}`;923    const approveResult = await this.helper.executeExtrinsic(924      signer, 925      'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],926      true, `Unable to approve token for ${label}`,927    );928929    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved', label);930  }931932  /**933   * Get the amount of token pieces approved to transfer934   * @param collectionId ID of collection935   * @param tokenId ID of token936   * @param toAccountObj 937   * @param fromAccountObj938   * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})939   * @returns number of approved to transfer pieces940   */941  async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {942    return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();943  }944945  /**946   * Get the last created token id947   * @param collectionId ID of collection948   * @example getLastTokenId(10);949   * @returns id of the last created token950   */951  async getLastTokenId(collectionId: number): Promise<number> {952    return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();953  }954955  /**956   * Check if token exists957   * @param collectionId ID of collection958   * @param tokenId ID of token959   * @example isTokenExists(10, 20);960   * @returns true if the token exists, otherwise false961   */962  async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {963    return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();964  }965}966967class NFTnRFT extends CollectionGroup {968  /**969   * Get tokens owned by account970   * 971   * @param collectionId ID of collection972   * @param addressObj tokens owner973   * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})974   * @returns array of token ids owned by account975   */976  async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {977    return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();978  }979980  /**981   * Get token data982   * @param collectionId ID of collection983   * @param tokenId ID of token984   * @param blockHashAt 985   * @param propertyKeys986   * @example getToken(10, 5);987   * @returns human readable token data 988   */989  async getToken(collectionId: number, tokenId: number, blockHashAt?: string, propertyKeys?: string[]): Promise<{990    properties: IProperty[];991    owner: ICrossAccountId;992    normalizedOwner: ICrossAccountId;993  }| null> {994    let tokenData;995    if(typeof blockHashAt === 'undefined') {996      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);997    }998    else {999      if(typeof propertyKeys === 'undefined') {1000        const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1001        if(!collection) return null;1002        propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1003      }1004      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1005    }1006    tokenData = tokenData.toHuman();1007    if (tokenData === null || tokenData.owner === null) return null;1008    const owner = {} as any;1009    for (const key of Object.keys(tokenData.owner)) {1010      owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];1011    }1012    tokenData.normalizedOwner = crossAccountIdFromLower(owner);1013    return tokenData;1014  }10151016  /**1017   * Set permissions to change token properties1018   * @param signer keyring of signer1019   * @param collectionId ID of collection1020   * @param permissions permissions to change a property by the collection owner or admin1021   * @param label 1022   * @example setTokenPropertyPermissions(1023   *   aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1024   * )1025   * @returns true if extrinsic success otherwise false1026   */1027  async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[], label?: string): Promise<boolean> {1028    if(typeof label === 'undefined') label = `collection #${collectionId}`;1029    const result = await this.helper.executeExtrinsic(1030      signer,1031      'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1032      true, `Unable to set token property permissions for ${label}`,1033    );10341035    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet', label);1036  }10371038  /**1039   * Set token properties1040   * @param signer keyring of signer1041   * @param collectionId ID of collection1042   * @param tokenId ID of token1043   * @param properties 1044   * @param label 1045   * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1046   * @returns ```true``` if extrinsic success, otherwise ```false```1047   */1048  async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[], label?: string): Promise<boolean> {1049    if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;1050    const result = await this.helper.executeExtrinsic(1051      signer,1052      'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1053      true, `Unable to set token properties for ${label}`,1054    );10551056    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet', label);1057  }10581059  /**1060   * Delete the provided properties of a token1061   * @param signer keyring of signer1062   * @param collectionId ID of collection1063   * @param tokenId ID of token1064   * @param propertyKeys property keys to be deleted 1065   * @param label 1066   * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1067   * @returns ```true``` if extrinsic success, otherwise ```false```1068   */1069  async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[], label?: string): Promise<boolean> {1070    if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;1071    const result = await this.helper.executeExtrinsic(1072      signer,1073      'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1074      true, `Unable to delete token properties for ${label}`,1075    );10761077    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted', label);1078  }10791080  /**1081   * Mint new collection1082   * @param signer keyring of signer1083   * @param collectionOptions basic collection options and properties 1084   * @param mode NFT or RFT type of a collection1085   * @param errorLabel 1086   * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1087   * @returns object of the created collection1088   */1089  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT', errorLabel = 'Unable to mint collection'): Promise<UniqueCollectionBase> {1090    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1091    collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1092    for (const key of ['name', 'description', 'tokenPrefix']) {1093      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);1094    }1095    const creationResult = await this.helper.executeExtrinsic(1096      signer,1097      'api.tx.unique.createCollectionEx', [collectionOptions],1098      true, errorLabel,1099    );1100    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1101  }11021103  getCollectionObject(collectionId: number): any {1104    return null;1105  }11061107  getTokenObject(collectionId: number, tokenId: number): any {1108    return null;1109  }1110}111111121113class NFTGroup extends NFTnRFT {1114  /**1115   * Get collection object1116   * @param collectionId ID of collection1117   * @example getCollectionObject(2);1118   * @returns instance of UniqueNFTCollection1119   */1120  getCollectionObject(collectionId: number): UniqueNFTCollection {1121    return new UniqueNFTCollection(collectionId, this.helper);1122  }11231124  /**1125   * Get token object1126   * @param collectionId ID of collection1127   * @param tokenId ID of token1128   * @example getTokenObject(10, 5);1129   * @returns instance of UniqueNFTToken1130   */1131  getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1132    return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1133  }11341135  /**1136   * Get token's owner1137   * @param collectionId ID of collection1138   * @param tokenId ID of token1139   * @param blockHashAt 1140   * @example getTokenOwner(10, 5);1141   * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1142   */1143  async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1144    let owner;1145    if (typeof blockHashAt === 'undefined') {1146      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1147    } else {1148      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1149    }1150    return crossAccountIdFromLower(owner.toJSON());1151  }11521153  /**1154   * Is token approved to transfer1155   * @param collectionId ID of collection1156   * @param tokenId ID of token1157   * @param toAccountObj address to be approved1158   * @returns ```true``` if extrinsic success, otherwise ```false```1159   */1160  async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1161    return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1162  }11631164  /**1165   * Changes the owner of the token.1166   * 1167   * @param signer keyring of signer1168   * @param collectionId ID of collection1169   * @param tokenId ID of token1170   * @param addressObj address of a new owner1171   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1172   * @returns ```true``` if extrinsic success, otherwise ```false```1173   */1174  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1175    return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1176  }11771178  /**1179   * 1180   * Change ownership of a NFT on behalf of the owner. 1181   * 1182   * @param signer keyring of signer1183   * @param collectionId ID of collection1184   * @param tokenId ID of token1185   * @param fromAddressObj address on behalf of which the token will be sent1186   * @param toAddressObj new token owner1187   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1188   * @returns ```true``` if extrinsic success, otherwise ```false```1189   */1190  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1191    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1192  }11931194  /**1195   * Recursively find the address that owns the token1196   * @param collectionId ID of collection1197   * @param tokenId ID of token1198   * @param blockHashAt 1199   * @example getTokenTopmostOwner(10, 5);1200   * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1201   */1202  async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1203    let owner;1204    if (typeof blockHashAt === 'undefined') {1205      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1206    } else {1207      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1208    }12091210    if (owner === null) return null;12111212    owner = owner.toHuman();12131214    return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1215  }12161217  /**1218   * Get tokens nested in the provided token1219   * @param collectionId ID of collection1220   * @param tokenId ID of token1221   * @param blockHashAt 1222   * @example getTokenChildren(10, 5);1223   * @returns tokens whose depth of nesting is <= 5 1224   */1225  async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1226    let children;1227    if(typeof blockHashAt === 'undefined') {1228      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1229    } else {1230      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1231    }12321233    return children.toJSON().map((x: any) => {1234      return {collectionId: x.collection, tokenId: x.token};1235    });1236  }12371238  /**1239   * Nest one token into another1240   * @param signer keyring of signer1241   * @param tokenObj token to be nested1242   * @param rootTokenObj token to be parent1243   * @param label 1244   * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1245   * @returns ```true``` if extrinsic success, otherwise ```false```1246   */1247  async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, label='nest token'): Promise<boolean> {1248    const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1249    const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1250    if(!result) {1251      throw Error(`Unable to nest token for ${label}`);1252    }1253    return result;1254  }12551256  /**1257   * Remove token from nested state1258   * @param signer keyring of signer1259   * @param tokenObj token to unnest1260   * @param rootTokenObj parent of a token1261   * @param toAddressObj address of a new token owner 1262   * @param label 1263   * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1264   * @returns ```true``` if extrinsic success, otherwise ```false```1265   */1266  async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId, label='unnest token'): Promise<boolean> {1267    const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1268    const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1269    if(!result) {1270      throw Error(`Unable to unnest token for ${label}`);1271    }1272    return result;1273  }12741275  /**1276   * Mint new collection1277   * @param signer keyring of signer1278   * @param collectionOptions Collection options1279   * @param label 1280   * @example 1281   * mintCollection(aliceKeyring, {1282   *   name: 'New',1283   *   description: 'New collection',1284   *   tokenPrefix: 'NEW',1285   * })1286   * @returns object of the created collection1287   */1288  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueNFTCollection> {1289    return await super.mintCollection(signer, collectionOptions, 'NFT', `Unable to mint NFT collection for ${label}`) as UniqueNFTCollection;1290  }12911292  /**1293   * Mint new token1294   * @param signer keyring of signer1295   * @param data token data1296   * @param label 1297   * @returns created token object1298   */1299  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }, label?: string): Promise<UniqueNFTToken> {1300    if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1301    const creationResult = await this.helper.executeExtrinsic(1302      signer,1303      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1304        nft: {1305          properties: data.properties,1306        },1307      }],1308      true, `Unable to mint NFT token for ${label}`,1309    );1310    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1311    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1312    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1313    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1314  }13151316  /**1317   * Mint multiple NFT tokens1318   * @param signer keyring of signer1319   * @param collectionId ID of collection1320   * @param tokens array of tokens with owner and properties1321   * @param label 1322   * @example 1323   * mintMultipleTokens(aliceKeyring, 10, [{1324   *     owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1325   *     properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1326   *   },{1327   *     owner: {Ethereum: "0x9F0583DbB855d..."},1328   *     properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1329   * }]);1330   * @returns ```true``` if extrinsic success, otherwise ```false```1331   */1332  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1333    if(typeof label === 'undefined') label = `collection #${collectionId}`;1334    const creationResult = await this.helper.executeExtrinsic(1335      signer,1336      'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1337      true, `Unable to mint NFT tokens for ${label}`,1338    );1339    const collection = this.getCollectionObject(collectionId);1340    return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1341  }13421343  /**1344   * Mint multiple NFT tokens with one owner1345   * @param signer keyring of signer1346   * @param collectionId ID of collection1347   * @param owner tokens owner1348   * @param tokens array of tokens with owner and properties1349   * @param label 1350   * @example1351   * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1352   *   properties: [{1353   *   key: "gender",1354   *   value: "female",1355   *  },{1356   *   key: "age",1357   *   value: "33",1358   *  }],1359   * }]);1360   * @returns array of newly created tokens1361   */1362  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1363    if(typeof label === 'undefined') label = `collection #${collectionId}`;1364    const rawTokens = [];1365    for (const token of tokens) {1366      const raw = {NFT: {properties: token.properties}};1367      rawTokens.push(raw);1368    }1369    const creationResult = await this.helper.executeExtrinsic(1370      signer,1371      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1372      true, `Unable to mint NFT tokens for ${label}`,1373    );1374    const collection = this.getCollectionObject(collectionId);1375    return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1376  }13771378  /**1379   * Destroys a concrete instance of NFT.1380   * @param signer keyring of signer1381   * @param collectionId ID of collection1382   * @param tokenId ID of token1383   * @param label 1384   * @example burnToken(aliceKeyring, 10, 5);1385   * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1386   */1387  async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string): Promise<{ success: boolean; token: number | null; }> {1388    return await super.burnToken(signer, collectionId, tokenId, label, 1n);1389  }13901391  /**1392   * Set, change, or remove approved address to transfer the ownership of the NFT.1393   * 1394   * @param signer keyring of signer1395   * @param collectionId ID of collection1396   * @param tokenId ID of token1397   * @param toAddressObj address to approve1398   * @param label 1399   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1400   * @returns ```true``` if extrinsic success, otherwise ```false```1401   */1402  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {1403    return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, 1n);1404  }1405}140614071408class RFTGroup extends NFTnRFT {1409  /**1410   * Get collection object1411   * @param collectionId ID of collection1412   * @example getCollectionObject(2);1413   * @returns instance of UniqueRFTCollection1414   */1415  getCollectionObject(collectionId: number): UniqueRFTCollection {1416    return new UniqueRFTCollection(collectionId, this.helper);1417  }14181419  /**1420   * Get token object1421   * @param collectionId ID of collection1422   * @param tokenId ID of token1423   * @example getTokenObject(10, 5);1424   * @returns instance of UniqueNFTToken1425   */1426  getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1427    return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1428  }14291430  /**1431   * Get top 10 token owners with the largest number of pieces 1432   * @param collectionId ID of collection1433   * @param tokenId ID of token1434   * @example getTokenTop10Owners(10, 5);1435   * @returns array of top 10 owners1436   */1437  async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1438    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1439  }14401441  /**1442   * Get number of pieces owned by address1443   * @param collectionId ID of collection1444   * @param tokenId ID of token1445   * @param addressObj address token owner1446   * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1447   * @returns number of pieces ownerd by address1448   */1449  async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1450    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1451  }14521453  /**1454   * Transfer pieces of token to another address1455   * @param signer keyring of signer1456   * @param collectionId ID of collection1457   * @param tokenId ID of token1458   * @param addressObj address of a new owner1459   * @param amount number of pieces to be transfered1460   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1461   * @returns ```true``` if extrinsic success, otherwise ```false```1462   */1463  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=100n): Promise<boolean> {1464    return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1465  }14661467  /**1468   * Change ownership of some pieces of RFT on behalf of the owner. 1469   * @param signer keyring of signer1470   * @param collectionId ID of collection1471   * @param tokenId ID of token1472   * @param fromAddressObj address on behalf of which the token will be sent1473   * @param toAddressObj new token owner1474   * @param amount number of pieces to be transfered1475   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1476   * @returns ```true``` if extrinsic success, otherwise ```false```1477   */1478  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n): Promise<boolean> {1479    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1480  }14811482  /**1483   * Mint new collection1484   * @param signer keyring of signer1485   * @param collectionOptions Collection options1486   * @param label 1487   * @example1488   * mintCollection(aliceKeyring, {1489   *   name: 'New',1490   *   description: 'New collection',1491   *   tokenPrefix: 'NEW',1492   * })1493   * @returns object of the created collection1494   */1495  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueRFTCollection> {1496    return await super.mintCollection(signer, collectionOptions, 'RFT', `Unable to mint RFT collection for ${label}`) as UniqueRFTCollection;1497  }14981499  /**1500   * Mint new token1501   * @param signer keyring of signer1502   * @param data token data1503   * @param label 1504   * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1505   * @returns created token object1506   */1507  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }, label?: string): Promise<UniqueRFTToken> {1508    if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1509    const creationResult = await this.helper.executeExtrinsic(1510      signer,1511      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1512        refungible: {1513          pieces: data.pieces,1514          properties: data.properties,1515        },1516      }],1517      true, `Unable to mint RFT token for ${label}`,1518    );1519    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1520    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1521    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1522    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1523  }15241525  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1526    throw Error('Not implemented');1527    if(typeof label === 'undefined') label = `collection #${collectionId}`;1528    const creationResult = await this.helper.executeExtrinsic(1529      signer,1530      'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1531      true, `Unable to mint RFT tokens for ${label}`,1532    );1533    const collection = this.getCollectionObject(collectionId);1534    return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1535  }15361537  /**1538   * Mint multiple RFT tokens with one owner1539   * @param signer keyring of signer1540   * @param collectionId ID of collection1541   * @param owner tokens owner1542   * @param tokens array of tokens with properties and pieces1543   * @param label 1544   * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1545   * @returns array of newly created RFT tokens1546   */1547  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1548    if(typeof label === 'undefined') label = `collection #${collectionId}`;1549    const rawTokens = [];1550    for (const token of tokens) {1551      const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1552      rawTokens.push(raw);1553    }1554    const creationResult = await this.helper.executeExtrinsic(1555      signer,1556      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1557      true, `Unable to mint RFT tokens for ${label}`,1558    );1559    const collection = this.getCollectionObject(collectionId);1560    return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1561  }15621563  /**1564   * Destroys a concrete instance of RFT.1565   * @param signer keyring of signer1566   * @param collectionId ID of collection1567   * @param tokenId ID of token1568   * @param label 1569   * @param amount number of pieces to be burnt1570   * @example burnToken(aliceKeyring, 10, 5);1571   * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1572   */1573  async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string, amount=100n): Promise<{ success: boolean; token: number | null; }> {1574    return await super.burnToken(signer, collectionId, tokenId, label, amount);1575  }15761577  /**1578   * Set, change, or remove approved address to transfer the ownership of the RFT.1579   * 1580   * @param signer keyring of signer1581   * @param collectionId ID of collection1582   * @param tokenId ID of token1583   * @param toAddressObj address to approve1584   * @param label 1585   * @param amount number of pieces to be approved1586   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1587   * @returns true if the token success, otherwise false1588   */1589  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=100n) {1590    return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, amount);1591  }15921593  /**1594   * Get total number of pieces1595   * @param collectionId ID of collection1596   * @param tokenId ID of token1597   * @example getTokenTotalPieces(10, 5);1598   * @returns number of pieces1599   */1600  async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1601    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1602  }16031604  /**1605   * Change number of token pieces. Signer must be the owner of all token pieces.1606   * @param signer keyring of signer1607   * @param collectionId ID of collection1608   * @param tokenId ID of token1609   * @param amount new number of pieces1610   * @param label 1611   * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1612   * @returns true if the repartion was success, otherwise false1613   */1614  async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint, label?: string): Promise<boolean> {1615    if(typeof label === 'undefined') label = `collection #${collectionId}`;1616    const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1617    const repartitionResult = await this.helper.executeExtrinsic(1618      signer,1619      'api.tx.unique.repartition', [collectionId, tokenId, amount],1620      true, `Unable to repartition RFT token for ${label}`,1621    );1622    if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated', label);1623    return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed', label);1624  }1625}162616271628class FTGroup extends CollectionGroup {1629  /**1630   * Get collection object1631   * @param collectionId ID of collection1632   * @example getCollectionObject(2);1633   * @returns instance of UniqueFTCollection1634   */1635  getCollectionObject(collectionId: number): UniqueFTCollection {1636    return new UniqueFTCollection(collectionId, this.helper);1637  }16381639  /**1640   * Mint new fungible collection1641   * @param signer keyring of signer1642   * @param collectionOptions Collection options1643   * @param decimalPoints number of token decimals 1644   * @param errorLabel 1645   * @example1646   * mintCollection(aliceKeyring, {1647   *   name: 'New',1648   *   description: 'New collection',1649   *   tokenPrefix: 'NEW',1650   * }, 18)1651   * @returns newly created fungible collection1652   */1653  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0, errorLabel = 'Unable to mint collection'): Promise<UniqueFTCollection> {1654    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1655    if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1656    collectionOptions.mode = {fungible: decimalPoints};1657    for (const key of ['name', 'description', 'tokenPrefix']) {1658      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);1659    }1660    const creationResult = await this.helper.executeExtrinsic(1661      signer,1662      'api.tx.unique.createCollectionEx', [collectionOptions],1663      true, errorLabel,1664    );1665    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1666  }16671668  /**1669   * Mint tokens1670   * @param signer keyring of signer1671   * @param collectionId ID of collection1672   * @param owner address owner of new tokens1673   * @param amount amount of tokens to be meanted1674   * @param label 1675   * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1676   * @returns ```true``` if extrinsic success, otherwise ```false``` 1677   */1678  async mintTokens(signer: TSigner, collectionId: number, owner: ICrossAccountId | string, amount: bigint, label?: string): Promise<boolean> {1679    if(typeof label === 'undefined') label = `collection #${collectionId}`;1680    const creationResult = await this.helper.executeExtrinsic(1681      signer,1682      'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1683        fungible: {1684          value: amount,1685        },1686      }],1687      true, `Unable to mint fungible tokens for ${label}`,1688    );1689    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1690  }16911692  /**1693   * Mint multiple Fungible tokens with one owner1694   * @param signer keyring of signer1695   * @param collectionId ID of collection1696   * @param owner tokens owner1697   * @param tokens array of tokens with properties and pieces1698   * @param label 1699   * @returns ```true``` if extrinsic success, otherwise ```false``` 1700   */1701  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string): Promise<boolean> {1702    if(typeof label === 'undefined') label = `collection #${collectionId}`;1703    const rawTokens = [];1704    for (const token of tokens) {1705      const raw = {Fungible: {Value: token.value}};1706      rawTokens.push(raw);1707    }1708    const creationResult = await this.helper.executeExtrinsic(1709      signer,1710      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1711      true, `Unable to mint RFT tokens for ${label}`,1712    );1713    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1714  }17151716  /**1717   * Get the top 10 owners with the largest balance for the Fungible collection 1718   * @param collectionId ID of collection1719   * @example getTop10Owners(10);1720   * @returns array of ```ICrossAccountId```1721   */1722  async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1723    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1724  }17251726  /**1727   * Get account balance1728   * @param collectionId ID of collection1729   * @param addressObj address of owner1730   * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1731   * @returns amount of fungible tokens owned by address1732   */1733  async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1734    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1735  }17361737  /**1738   * Transfer tokens to address1739   * @param signer keyring of signer1740   * @param collectionId ID of collection1741   * @param toAddressObj address recepient1742   * @param amount amount of tokens to be sent1743   * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1744   * @returns ```true``` if extrinsic success, otherwise ```false``` 1745   */1746  async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount: bigint) {1747    return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1748  }17491750  /**1751   * Transfer some tokens on behalf of the owner.1752   * @param signer keyring of signer1753   * @param collectionId ID of collection1754   * @param fromAddressObj address on behalf of which tokens will be sent1755   * @param toAddressObj address where token to be sent1756   * @param amount number of tokens to be sent1757   * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1758   * @returns ```true``` if extrinsic success, otherwise ```false``` 1759   */1760  async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {1761    return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1762  }17631764  /**1765   * Destroy some amount of tokens1766   * @param signer keyring of signer1767   * @param collectionId ID of collection1768   * @param amount amount of tokens to be destroyed1769   * @param label 1770   * @example burnTokens(aliceKeyring, 10, 1000n);1771   * @returns ```true``` if extrinsic success, otherwise ```false``` 1772   */1773  async burnTokens(signer: IKeyringPair, collectionId: number, amount=100n, label?: string): Promise<boolean> {1774    return (await super.burnToken(signer, collectionId, 0, label, amount)).success;1775  }17761777  /**1778   * Burn some tokens on behalf of the owner.1779   * @param signer keyring of signer1780   * @param collectionId ID of collection1781   * @param fromAddressObj address on behalf of which tokens will be burnt1782   * @param amount amount of tokens to be burnt1783   * @param label 1784   * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1785   * @returns ```true``` if extrinsic success, otherwise ```false``` 1786   */1787  async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=100n, label?: string): Promise<boolean> {1788    return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, label, amount);1789  }17901791  /**1792   * Get total collection supply1793   * @param collectionId 1794   * @returns 1795   */1796  async getTotalPieces(collectionId: number): Promise<bigint> {1797    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1798  }17991800  /**1801   * Set, change, or remove approved address to transfer tokens.1802   * 1803   * @param signer keyring of signer1804   * @param collectionId ID of collection1805   * @param toAddressObj address to be approved1806   * @param amount amount of tokens to be approved1807   * @param label 1808   * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1809   * @returns ```true``` if extrinsic success, otherwise ```false``` 1810   */1811  async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {1812    return super.approveToken(signer, collectionId, 0, toAddressObj, label, amount);1813  }18141815  /**1816   * Get amount of fungible tokens approved to transfer1817   * @param collectionId ID of collection1818   * @param fromAddressObj owner of tokens1819   * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1820   * @returns number of tokens approved for the transfer1821   */1822  async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1823    return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1824  }1825}182618271828class ChainGroup extends HelperGroup {1829  /**1830   * Get system properties of a chain1831   * @example getChainProperties();1832   * @returns ss58Format, token decimals, and token symbol1833   */1834  getChainProperties(): IChainProperties {1835    const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1836    return {1837      ss58Format: properties.ss58Format.toJSON(),1838      tokenDecimals: properties.tokenDecimals.toJSON(),1839      tokenSymbol: properties.tokenSymbol.toJSON(),1840    };1841  }18421843  /**1844   * Get chain header1845   * @example getLatestBlockNumber();1846   * @returns the number of the last block1847   */1848  async getLatestBlockNumber(): Promise<number> {1849    return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1850  }18511852  /**1853   * Get block hash by block number1854   * @param blockNumber number of block1855   * @example getBlockHashByNumber(12345);1856   * @returns hash of a block1857   */1858  async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1859    const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1860    if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1861    return blockHash;1862  }18631864  /**1865   * Get account nonce1866   * @param address substrate address1867   * @example getNonce("5GrwvaEF5zXb26Fz...");1868   * @returns number, account's nonce1869   */1870  async getNonce(address: TSubstrateAccount): Promise<number> {1871    return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1872  }1873}187418751876class BalanceGroup extends HelperGroup {1877  /**1878   * Representation of the native token in the smallest unit1879   * @example getOneTokenNominal()1880   * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.1881   */1882  getOneTokenNominal(): bigint {1883    const chainProperties = this.helper.chain.getChainProperties();1884    return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1885  }18861887  /**1888   * Get substrate address balance1889   * @param address substrate address1890   * @example getSubstrate("5GrwvaEF5zXb26Fz...")1891   * @returns amount of tokens on address1892   */1893  async getSubstrate(address: TSubstrateAccount): Promise<bigint> {1894    return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();1895  }18961897  /**1898   * Get ethereum address balance1899   * @param address ethereum address1900   * @example getEthereum("0x9F0583DbB855d...")1901   * @returns amount of tokens on address1902   */1903  async getEthereum(address: TEthereumAccount): Promise<bigint> {1904    return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();1905  }19061907  /**1908   * Transfer tokens to substrate address1909   * @param signer keyring of signer1910   * @param address substrate address of a recepient1911   * @param amount amount of tokens to be transfered1912   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);1913   * @returns ```true``` if extrinsic success, otherwise ```false```1914   */1915  async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {1916    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}`);19171918    let transfer = {from: null, to: null, amount: 0n} as any;1919    result.result.events.forEach(({event: {data, method, section}}) => {1920      if ((section === 'balances') && (method === 'Transfer')) {1921        transfer = {1922          from: this.helper.address.normalizeSubstrate(data[0]),1923          to: this.helper.address.normalizeSubstrate(data[1]),1924          amount: BigInt(data[2]),1925        };1926      }1927    });1928    let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;1929    isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;1930    isSuccess = isSuccess && BigInt(amount) === transfer.amount;1931    return isSuccess;1932  }1933}193419351936class AddressGroup extends HelperGroup {1937  /**1938   * Normalizes the address to the specified ss58 format, by default ```42```.1939   * @param address substrate address1940   * @param ss58Format format for address conversion, by default ```42```1941   * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY1942   * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation1943   */1944  normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {1945    return this.helper.util.normalizeSubstrateAddress(address, ss58Format);1946  }19471948  /**1949   * Get address in the connected chain format1950   * @param address substrate address1951   * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network1952   * @returns address in chain format1953   */1954  async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {1955    const info = this.helper.chain.getChainProperties();1956    return encodeAddress(decodeAddress(address), info.ss58Format);1957  }19581959  /**1960   * Get substrate mirror of an ethereum address1961   * @param ethAddress ethereum address1962   * @param toChainFormat false for normalized account1963   * @example ethToSubstrate('0x9F0583DbB855d...')1964   * @returns substrate mirror of a provided ethereum address1965   */1966  async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {1967    if(!toChainFormat) return evmToAddress(ethAddress);1968    const info = this.helper.chain.getChainProperties();1969    return evmToAddress(ethAddress, info.ss58Format);1970  }19711972  /**1973   * Get ethereum mirror of a substrate address1974   * @param subAddress substrate account1975   * @example substrateToEth("5DnSF6RRjwteE3BrC...")1976   * @returns ethereum mirror of a provided substrate address1977   */1978  substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {1979    return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));1980  }1981}198219831984export class UniqueHelper extends ChainHelperBase {1985  chain: ChainGroup;1986  balance: BalanceGroup;1987  address: AddressGroup;1988  collection: CollectionGroup;1989  nft: NFTGroup;1990  rft: RFTGroup;1991  ft: FTGroup;19921993  constructor(logger?: ILogger) {1994    super(logger);1995    this.chain = new ChainGroup(this);1996    this.balance = new BalanceGroup(this);1997    this.address = new AddressGroup(this);1998    this.collection = new CollectionGroup(this);1999    this.nft = new NFTGroup(this);2000    this.rft = new RFTGroup(this);2001    this.ft = new FTGroup(this);2002  }  2003}200420052006class UniqueCollectionBase {2007  helper: UniqueHelper;2008  collectionId: number;20092010  constructor(collectionId: number, uniqueHelper: UniqueHelper) {2011    this.collectionId = collectionId;2012    this.helper = uniqueHelper;2013  }20142015  async getData() {2016    return await this.helper.collection.getData(this.collectionId);2017  }20182019  async getLastTokenId() {2020    return await this.helper.collection.getLastTokenId(this.collectionId);2021  }20222023  async isTokenExists(tokenId: number) {2024    return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2025  }20262027  async getAdmins() {2028    return await this.helper.collection.getAdmins(this.collectionId);2029  }20302031  async getAllowList() {2032    return await this.helper.collection.getAllowList(this.collectionId);2033  }20342035  async getEffectiveLimits() {2036    return await this.helper.collection.getEffectiveLimits(this.collectionId);2037  }20382039  async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount, label?: string) {2040    return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress, label);2041  }20422043  async confirmSponsorship(signer: TSigner, label?: string) {2044    return await this.helper.collection.confirmSponsorship(signer, this.collectionId, label);2045  }20462047  async setLimits(signer: TSigner, limits: ICollectionLimits, label?: string) {2048    return await this.helper.collection.setLimits(signer, this.collectionId, limits, label);2049  }20502051  async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount, label?: string) {2052    return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress, label);2053  }20542055  async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {2056    return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj, label);2057  }20582059  async addToAllowList(signer: TSigner, addressObj: ICrossAccountId, label?: string) {2060    return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj, label);2061  }20622063  async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {2064    return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj, label);2065  }20662067  async setProperties(signer: TSigner, properties: IProperty[], label?: string) {2068    return await this.helper.collection.setProperties(signer, this.collectionId, properties, label);2069  }20702071  async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {2072    return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys, label);2073  }20742075  async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2076    return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2077  }20782079  async setPermissions(signer: TSigner, permissions: ICollectionPermissions, label?: string) {2080    return await this.helper.collection.setPermissions(signer, this.collectionId, permissions, label);2081  }20822083  async enableNesting(signer: TSigner, permissions: INestingPermissions, label?: string) {2084    return await this.helper.collection.enableNesting(signer, this.collectionId, permissions, label);2085  }20862087  async disableNesting(signer: TSigner, label?: string) {2088    return await this.helper.collection.disableNesting(signer, this.collectionId, label);2089  }20902091  async burn(signer: TSigner, label?: string) {2092    return await this.helper.collection.burn(signer, this.collectionId, label);2093  }2094}209520962097class UniqueNFTCollection extends UniqueCollectionBase {2098  getTokenObject(tokenId: number) {2099    return new UniqueNFTToken(tokenId, this);2100  }21012102  async getTokensByAddress(addressObj: ICrossAccountId) {2103    return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2104  }21052106  async getToken(tokenId: number, blockHashAt?: string) {2107    return await this.helper.nft.getToken(this.collectionId, tokenId, blockHashAt);2108  }21092110  async getTokenOwner(tokenId: number, blockHashAt?: string) {2111    return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2112  }21132114  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2115    return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2116  }21172118  async getTokenChildren(tokenId: number, blockHashAt?: string) {2119    return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2120  }21212122  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2123    return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2124  }21252126  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2127    return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2128  }21292130  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {2131    return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label);2132  }21332134  async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2135    return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2136  }21372138  async mintToken(signer: TSigner, owner: ICrossAccountId, properties?: IProperty[], label?: string) {2139    return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties}, label);2140  }21412142  async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string) {2143    return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens, label);2144  }21452146  async burnToken(signer: TSigner, tokenId: number, label?: string) {2147    return await this.helper.nft.burnToken(signer, this.collectionId, tokenId, label);2148  }21492150  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {2151    return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);2152  }21532154  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {2155    return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);2156  }21572158  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {2159    return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);2160  }21612162  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken, label?: string) {2163    return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj, label);2164  }21652166  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {2167    return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj, label);2168  }2169}217021712172class UniqueRFTCollection extends UniqueCollectionBase {2173  getTokenObject(tokenId: number) {2174    return new UniqueRFTToken(tokenId, this);2175  }21762177  async getTokensByAddress(addressObj: ICrossAccountId) {2178    return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2179  }21802181  async getTop10TokenOwners(tokenId: number) {2182    return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2183  }21842185  async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2186    return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2187  }21882189  async getTokenTotalPieces(tokenId: number) {2190    return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2191  }21922193  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=100n) {2194    return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2195  }21962197  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {2198    return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2199  }22002201  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2202    return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label, amount);2203  }22042205  async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2206    return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2207  }22082209  async repartitionToken(signer: TSigner, tokenId: number, amount: bigint, label?: string) {2210    return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount, label);2211  }22122213  async mintToken(signer: TSigner, owner: ICrossAccountId, pieces=100n, properties?: IProperty[], label?: string) {2214    return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties}, label);2215  }22162217  async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string) {2218    return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens, label);2219  }22202221  async burnToken(signer: TSigner, tokenId: number, amount=100n, label?: string) {2222    return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, label, amount);2223  }22242225  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {2226    return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);2227  }22282229  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {2230    return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);2231  }22322233  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {2234    return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);2235  }2236}223722382239class UniqueFTCollection extends UniqueCollectionBase {2240  async mint(signer: TSigner, owner: ICrossAccountId, amount: bigint, label?: string) {2241    return await this.helper.ft.mintTokens(signer, this.collectionId, owner, amount, label);2242  }22432244  async mintWithOneOwner(signer: TSigner, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string) {2245    return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, owner, tokens, label);2246  }22472248  async getBalance(addressObj: ICrossAccountId) {2249    return await this.helper.ft.getBalance(this.collectionId, addressObj);2250  }22512252  async getTop10Owners() {2253    return await this.helper.ft.getTop10Owners(this.collectionId);2254  }22552256  async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount: bigint) {2257    return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2258  }22592260  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {2261    return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2262  }22632264  async burnTokens(signer: TSigner, amount: bigint, label?: string) {2265    return await this.helper.ft.burnTokens(signer, this.collectionId, amount, label);2266  }22672268  async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount: bigint, label?: string) {2269    return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount, label);2270  }22712272  async getTotalPieces() {2273    return await this.helper.ft.getTotalPieces(this.collectionId);2274  }22752276  async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2277    return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount, label);2278  }22792280  async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2281    return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2282  }2283}228422852286class UniqueTokenBase implements IToken {2287  collection: UniqueNFTCollection | UniqueRFTCollection;2288  collectionId: number;2289  tokenId: number;22902291  constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2292    this.collection = collection;2293    this.collectionId = collection.collectionId;2294    this.tokenId = tokenId;2295  }22962297  async getNextSponsored(addressObj: ICrossAccountId) {2298    return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2299  }23002301  async setProperties(signer: TSigner, properties: IProperty[], label?: string) {2302    return await this.collection.setTokenProperties(signer, this.tokenId, properties, label);2303  }23042305  async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {2306    return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys, label);2307  }2308}230923102311class UniqueNFTToken extends UniqueTokenBase {2312  collection: UniqueNFTCollection;23132314  constructor(tokenId: number, collection: UniqueNFTCollection) {2315    super(tokenId, collection);2316    this.collection = collection;2317  }23182319  async getData(blockHashAt?: string) {2320    return await this.collection.getToken(this.tokenId, blockHashAt);2321  }23222323  async getOwner(blockHashAt?: string) {2324    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2325  }23262327  async getTopmostOwner(blockHashAt?: string) {2328    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2329  }23302331  async getChildren(blockHashAt?: string) {2332    return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2333  }23342335  async nest(signer: TSigner, toTokenObj: IToken, label?: string) {2336    return await this.collection.nestToken(signer, this.tokenId, toTokenObj, label);2337  }23382339  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {2340    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj, label);2341  }23422343  async transfer(signer: TSigner, addressObj: ICrossAccountId) {2344    return await this.collection.transferToken(signer, this.tokenId, addressObj);2345  }23462347  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2348    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2349  }23502351  async approve(signer: TSigner, toAddressObj: ICrossAccountId, label?: string) {2352    return await this.collection.approveToken(signer, this.tokenId, toAddressObj, label);2353  }23542355  async isApproved(toAddressObj: ICrossAccountId) {2356    return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2357  }23582359  async burn(signer: TSigner, label?: string) {2360    return await this.collection.burnToken(signer, this.tokenId, label);2361  }2362}23632364class UniqueRFTToken extends UniqueTokenBase {2365  collection: UniqueRFTCollection;23662367  constructor(tokenId: number, collection: UniqueRFTCollection) {2368    super(tokenId, collection);2369    this.collection = collection;2370  }23712372  async getTop10Owners() {2373    return await this.collection.getTop10TokenOwners(this.tokenId);2374  }23752376  async getBalance(addressObj: ICrossAccountId) {2377    return await this.collection.getTokenBalance(this.tokenId, addressObj);2378  }23792380  async getTotalPieces() {2381    return await this.collection.getTokenTotalPieces(this.tokenId);2382  }23832384  async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=100n) {2385    return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2386  }23872388  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {2389    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2390  }23912392  async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2393    return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount, label);2394  }23952396  async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2397    return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2398  }23992400  async repartition(signer: TSigner, amount: bigint, label?: string) {2401    return await this.collection.repartitionToken(signer, this.tokenId, amount, label);2402  }24032404  async burn(signer: TSigner, amount=100n, label?: string) {2405    return await this.collection.burnToken(signer, this.tokenId, amount, label);2406  }2407}