12345678import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {SignerOptions} from '@polkadot/api/types/submittable';10import '../../interfaces/augment-api-tx';11import {AugmentedSubmittables} from '@polkadot/api-base/types/submittable';12import {RpcInterface} from '@polkadot/rpc-core/types';13import {QueryableStorage} from '@polkadot/api-base/types/storage';14import {DecoratedRpc} from '@polkadot/api-base/types/rpc';15import {ApiInterfaceEvents} from '@polkadot/api/types';16import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';17import {IKeyringPair} from '@polkadot/types/types';18import {hexToU8a} from '@polkadot/util/hex';19import {u8aConcat} from '@polkadot/util/u8a';20import {21 IApiListeners,22 IBlock,23 IEvent,24 IChainProperties,25 ICollectionCreationOptions,26 ICollectionLimits,27 ICollectionPermissions,28 ICrossAccountId,29 ICrossAccountIdLower,30 ILogger,31 INestingPermissions,32 IProperty,33 IStakingInfo,34 ISchedulerOptions,35 ISubstrateBalance,36 IToken,37 ITokenPropertyPermission,38 ITransactionResult,39 IUniqueHelperLog,40 TApiAllowedListeners,41 TEthereumAccount,42 TSigner,43 TSubstrateAccount,44 TNetworks,45 IForeignAssetMetadata,46 AcalaAssetMetadata,47 MoonbeamAssetInfo,48 DemocracyStandardAccountVote,49 IEthCrossAccountId,50} from './types';51import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';52import type {Vec} from '@polkadot/types-codec';53import {FrameSystemEventRecord} from '@polkadot/types/lookup';5455export class CrossAccountId {56 Substrate!: TSubstrateAccount;57 Ethereum!: TEthereumAccount;5859 constructor(account: ICrossAccountId) {60 if ('Substrate' in account) this.Substrate = account.Substrate;61 else this.Ethereum = account.Ethereum;62 }6364 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {65 switch (domain) {66 case 'Substrate': return new CrossAccountId({Substrate: account.address});67 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();68 }69 }7071 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {72 if ('substrate' in address) return new CrossAccountId({Substrate: address.substrate});73 else return new CrossAccountId({Ethereum: address.ethereum});74 }7576 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {77 return encodeAddress(decodeAddress(address), ss58Format);78 }7980 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {81 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});82 }8384 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {85 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);86 return this;87 }8889 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {90 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));91 }9293 toEthereum(): CrossAccountId {94 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});95 return this;96 }9798 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {99 return evmToAddress(address, ss58Format);100 }101102 toSubstrate(ss58Format?: number): CrossAccountId {103 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});104 return this;105 }106107 toLowerCase(): CrossAccountId {108 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();109 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();110 return this;111 }112}113114const nesting = {115 toChecksumAddress(address: string): string {116 if (typeof address === 'undefined') return '';117118 if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);119120 address = address.toLowerCase().replace(/^0x/i, '');121 const addressHash = keccakAsHex(address).replace(/^0x/i, '');122 const checksumAddress = ['0x'];123124 for (let i = 0; i < address.length; i++) {125 126 if (parseInt(addressHash[i], 16) > 7) {127 checksumAddress.push(address[i].toUpperCase());128 } else {129 checksumAddress.push(address[i]);130 }131 }132 return checksumAddress.join('');133 },134 tokenIdToAddress(collectionId: number, tokenId: number) {135 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);136 },137};138139class UniqueUtil {140 static transactionStatus = {141 NOT_READY: 'NotReady',142 FAIL: 'Fail',143 SUCCESS: 'Success',144 };145146 static chainLogType = {147 EXTRINSIC: 'extrinsic',148 RPC: 'rpc',149 };150151 static getTokenAccount(token: IToken): CrossAccountId {152 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});153 }154155 static getTokenAddress(token: IToken): string {156 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);157 }158159 static getDefaultLogger(): ILogger {160 return {161 log(msg: any, level = 'INFO') {162 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));163 },164 level: {165 ERROR: 'ERROR',166 WARNING: 'WARNING',167 INFO: 'INFO',168 },169 };170 }171172 static vec2str(arr: string[] | number[]) {173 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');174 }175176 static str2vec(string: string) {177 if (typeof string !== 'string') return string;178 return Array.from(string).map(x => x.charCodeAt(0));179 }180181 static fromSeed(seed: string, ss58Format = 42) {182 const keyring = new Keyring({type: 'sr25519', ss58Format});183 return keyring.addFromUri(seed);184 }185186 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {187 if (creationResult.status !== this.transactionStatus.SUCCESS) {188 throw Error('Unable to create collection!');189 }190191 let collectionId = null;192 creationResult.result.events.forEach(({event: {data, method, section}}) => {193 if ((section === 'common') && (method === 'CollectionCreated')) {194 collectionId = parseInt(data[0].toString(), 10);195 }196 });197198 if (collectionId === null) {199 throw Error('No CollectionCreated event was found!');200 }201202 return collectionId;203 }204205 static extractTokensFromCreationResult(creationResult: ITransactionResult): {206 success: boolean,207 tokens: { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[],208 } {209 if (creationResult.status !== this.transactionStatus.SUCCESS) {210 throw Error('Unable to create tokens!');211 }212 let success = false;213 const tokens = [] as { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[];214 creationResult.result.events.forEach(({event: {data, method, section}}) => {215 if (method === 'ExtrinsicSuccess') {216 success = true;217 } else if ((section === 'common') && (method === 'ItemCreated')) {218 tokens.push({219 collectionId: parseInt(data[0].toString(), 10),220 tokenId: parseInt(data[1].toString(), 10),221 owner: data[2].toHuman(),222 amount: data[3].toBigInt(),223 });224 }225 });226 return {success, tokens};227 }228229 static extractTokensFromBurnResult(burnResult: ITransactionResult): {230 success: boolean,231 tokens: { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[],232 } {233 if (burnResult.status !== this.transactionStatus.SUCCESS) {234 throw Error('Unable to burn tokens!');235 }236 let success = false;237 const tokens = [] as { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[];238 burnResult.result.events.forEach(({event: {data, method, section}}) => {239 if (method === 'ExtrinsicSuccess') {240 success = true;241 } else if ((section === 'common') && (method === 'ItemDestroyed')) {242 tokens.push({243 collectionId: parseInt(data[0].toString(), 10),244 tokenId: parseInt(data[1].toString(), 10),245 owner: data[2].toHuman(),246 amount: data[3].toBigInt(),247 });248 }249 });250 return {success, tokens};251 }252253 static findCollectionInEvents(events: { event: IEvent }[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {254 let eventId = null;255 events.forEach(({event: {data, method, section}}) => {256 if ((section === expectedSection) && (method === expectedMethod)) {257 eventId = parseInt(data[0].toString(), 10);258 }259 });260261 if (eventId === null) {262 throw Error(`No ${expectedMethod} event was found!`);263 }264 return eventId === collectionId;265 }266267 static isTokenTransferSuccess(events: { event: IEvent }[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {268 const normalizeAddress = (address: string | ICrossAccountId) => {269 if (typeof address === 'string') return address;270 const obj = {} as any;271 Object.keys(address).forEach(k => {272 obj[k.toLocaleLowerCase()] = (address as any)[k];273 });274 if (obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);275 if (obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();276 return address;277 };278 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;279 events.forEach(({event: {data, method, section}}) => {280 if ((section === 'common') && (method === 'Transfer')) {281 const hData = (data as any).toJSON();282 transfer = {283 collectionId: hData[0],284 tokenId: hData[1],285 from: normalizeAddress(hData[2]),286 to: normalizeAddress(hData[3]),287 amount: BigInt(hData[4]),288 };289 }290 });291 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;292 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);293 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);294 isSuccess = isSuccess && amount === transfer.amount;295 return isSuccess;296 }297298 static bigIntToDecimals(number: bigint, decimals = 18) {299 const numberStr = number.toString();300 const dotPos = numberStr.length - decimals;301302 if (dotPos <= 0) {303 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;304 } else {305 const intPart = numberStr.substring(0, dotPos);306 const fractPart = numberStr.substring(dotPos);307 return intPart + '.' + fractPart;308 }309 }310}311312class UniqueEventHelper {313 private static extractIndex(index: any): [number, number] | string {314 if (index.toRawType() === '[u8;2]') return [index[0], index[1]];315 return index.toJSON();316 }317318 private static extractSub(data: any, subTypes: any): { [key: string]: any } {319 let obj: any = {};320 let index = 0;321322 if (data.entries) {323 for (const [key, value] of data.entries()) {324 obj[key] = this.extractData(value, subTypes[index]);325 index++;326 }327 } else obj = data.toJSON();328329 return obj;330 }331332 private static toHuman(data: any) {333 return data && data.toHuman ? data.toHuman() : `${data}`;334 }335336 private static extractData(data: any, type: any): any {337 if (!type) return this.toHuman(data);338 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();339 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();340 if (type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);341 return this.toHuman(data);342 }343344 public static extractEvents(events: { event: any, phase: any }[]): IEvent[] {345 const parsedEvents: IEvent[] = [];346347 events.forEach((record) => {348 const {event, phase} = record;349 const types = event.typeDef;350351 const eventData: IEvent = {352 section: event.section.toString(),353 method: event.method.toString(),354 index: this.extractIndex(event.index),355 data: [],356 phase: phase.toJSON(),357 };358359 event.data.forEach((val: any, index: number) => {360 eventData.data.push(this.extractData(val, types[index]));361 });362363 parsedEvents.push(eventData);364 });365366 return parsedEvents;367 }368}369const InvalidTypeSymbol = Symbol('Invalid type');370371export type Invalid<ErrorMessage> =372 | ((373 invalidType: typeof InvalidTypeSymbol,374 ..._: typeof InvalidTypeSymbol[]375 ) => typeof InvalidTypeSymbol)376 | null377 | undefined;378379type Get2<T, P extends string, E> =380 P extends `${infer Key}.${infer Key2}` ? Key extends keyof T ? Key2 extends keyof T[Key] ? T[Key][Key2] : E : E : E;381type ForceFunction<T> = T extends (...args: any) => any ? T : (...args: any) => Invalid<'not a function'>;382type ReturnTypeWithArgs<T extends (...args: any[]) => any, ARGS_T> =383 Extract<384 T extends { (...args: infer A1): infer R1; (...args: infer A2): infer R2; (...args: infer A3): infer R3; (...args: infer A4): infer R4; } ? [A1, R1] | [A2, R2] | [A3, R3] | [A4, R4] :385 T extends { (...args: infer A1): infer R1; (...args: infer A2): infer R2; (...args: infer A3): infer R3; } ? [A1, R1] | [A2, R2] | [A3, R3] :386 T extends { (...args: infer A1): infer R1; (...args: infer A2): infer R2; } ? [A1, R1] | [A2, R2] :387 T extends { (...args: infer A1): infer R1; } ? [A1, R1] :388 never,389 [ARGS_T, any]390 >[1]391392export class ChainHelperBase {393 helperBase: any;394395 transactionStatus = UniqueUtil.transactionStatus;396 chainLogType = UniqueUtil.chainLogType;397 util: typeof UniqueUtil;398 eventHelper: typeof UniqueEventHelper;399 logger: ILogger;400 api: ApiPromise | null;401 forcedNetwork: TNetworks | null;402 network: TNetworks | null;403 wsEndpoint: string | null;404 chainLog: IUniqueHelperLog[];405 children: ChainHelperBase[];406 address: AddressGroup;407 chain: ChainGroup;408409 constructor(logger?: ILogger, helperBase?: any) {410 this.helperBase = helperBase;411412 this.util = UniqueUtil;413 this.eventHelper = UniqueEventHelper;414 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();415 this.logger = logger;416 this.api = null;417 this.forcedNetwork = null;418 this.network = null;419 this.wsEndpoint = null;420 this.chainLog = [];421 this.children = [];422 this.address = new AddressGroup(this);423 this.chain = new ChainGroup(this);424 }425426 clone(helperCls: ChainHelperBaseConstructor, options: { [key: string]: any } = {}) {427 Object.setPrototypeOf(helperCls.prototype, this);428 const newHelper = new helperCls(this.logger, options);429430 newHelper.api = this.api;431 newHelper.network = this.network;432 newHelper.forceNetwork = this.forceNetwork;433434 this.children.push(newHelper);435436 return newHelper;437 }438439 getEndpoint(): string {440 if (this.wsEndpoint === null) throw Error('No connection was established');441 return this.wsEndpoint;442 }443444 getApi(): ApiPromise {445 if (this.api === null) throw Error('API not initialized');446 return this.api;447 }448449 async subscribeEvents(expectedEvents: { section: string, names: string[] }[]) {450 const collectedEvents: IEvent[] = [];451 const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {452 const ievents = this.eventHelper.extractEvents(events);453 ievents.forEach((event) => {454 expectedEvents.forEach((e => {455 if (event.section === e.section && e.names.includes(event.method)) {456 collectedEvents.push(event);457 }458 }));459 });460 });461 return {unsubscribe: unsubscribe as any, collectedEvents};462 }463464 clearChainLog(): void {465 this.chainLog = [];466 }467468 forceNetwork(value: TNetworks): void {469 this.forcedNetwork = value;470 }471472 async connect(wsEndpoint: string, listeners?: IApiListeners) {473 if (this.api !== null) throw Error('Already connected');474 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);475 this.wsEndpoint = wsEndpoint;476 this.api = api;477 this.network = network;478 }479480 async disconnect() {481 for (const child of this.children) {482 child.clearApi();483 }484485 if (this.api === null) return;486 await this.api.disconnect();487 this.clearApi();488 }489490 clearApi() {491 this.api = null;492 this.network = null;493 }494495 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {496 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;497 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];498499 if (xcmChains.indexOf(spec.specName) > -1) return spec.specName;500501 if (['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;502 return 'opal';503 }504505 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {506 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});507 await api.isReady;508509 const network = await this.detectNetwork(api);510511 await api.disconnect();512513 return network;514 }515516 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{517 api: ApiPromise;518 network: TNetworks;519 }> {520 if (typeof network === 'undefined' || network === null) network = 'opal';521 const supportedRPC = {522 opal: {523 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,524 },525 quartz: {526 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,527 },528 unique: {529 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,530 },531 rococo: {},532 westend: {},533 moonbeam: {},534 moonriver: {},535 acala: {},536 karura: {},537 westmint: {},538 };539 if (!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);540 const rpc = supportedRPC[network];541542 543 544545 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});546547 await api.isReadyOrError;548549 if (typeof listeners === 'undefined') listeners = {};550 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {551 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;552 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);553 }554555 return {api, network};556 }557558 getTransactionStatus(data: { events: { event: IEvent }[], status: any }) {559 const {events, status} = data;560 if (status.isReady) {561 return this.transactionStatus.NOT_READY;562 }563 if (status.isBroadcast) {564 return this.transactionStatus.NOT_READY;565 }566 if (status.isInBlock || status.isFinalized) {567 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');568 if (errors.length > 0) {569 return this.transactionStatus.FAIL;570 }571 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {572 return this.transactionStatus.SUCCESS;573 }574 }575576 return this.transactionStatus.FAIL;577 }578579 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {580 const sign = (callback: any) => {581 if (options !== null) return transaction.signAndSend(sender, options, callback);582 return transaction.signAndSend(sender, callback);583 };584 585 return new Promise(async (resolve, reject) => {586 try {587 const unsub = await sign((result: any) => {588 const status = this.getTransactionStatus(result);589590 if (status === this.transactionStatus.SUCCESS) {591 this.logger.log(`${label} successful`);592 unsub();593 resolve({result, status, blockHash: result.status.asInBlock.toHuman()});594 } else if (status === this.transactionStatus.FAIL) {595 let moduleError = null;596597 if (result.hasOwnProperty('dispatchError')) {598 const dispatchError = result['dispatchError'];599600 if (dispatchError) {601 if (dispatchError.isModule) {602 const modErr = dispatchError.asModule;603 const errorMeta = dispatchError.registry.findMetaError(modErr);604605 moduleError = `${errorMeta.section}.${errorMeta.name}`;606 } else {607 moduleError = dispatchError.toHuman();608 }609 } else {610 this.logger.log(result, this.logger.level.ERROR);611 }612 }613614 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);615 unsub();616 reject({status, moduleError, result});617 }618 });619 } catch (e) {620 this.logger.log(e, this.logger.level.ERROR);621 reject(e);622 }623 });624 }625626 async signTransactionWithoutSending(signer: TSigner, tx: any) {627 const api = this.getApi();628 const signingInfo = await api.derive.tx.signingInfo(signer.address);629630 tx.sign(signer, {631 blockHash: api.genesisHash,632 genesisHash: api.genesisHash,633 runtimeVersion: api.runtimeVersion,634 nonce: signingInfo.nonce,635 });636637 return tx.toHex();638 }639640 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {641 const api = this.getApi();642 const signingInfo = await api.derive.tx.signingInfo(signer.address);643644 645 646 tx.sign(signer, {647 blockHash: api.genesisHash,648 genesisHash: api.genesisHash,649 runtimeVersion: api.runtimeVersion,650 nonce: signingInfo.nonce,651 });652653 if (len === null) {654 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;655 } else {656 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;657 }658 }659660 constructApiCall(apiCall: string, params: any[]) {661 if (!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);662 let call = this.getApi() as any;663 for (const part of apiCall.slice(4).split('.')) {664 call = call[part];665 if (!call) {666 const advice = part.includes('_') ? ' Looks like it needs to be converted to camel case.' : '';667 throw Error(`Function ${part} of api call ${apiCall} not found.${advice}`);668 }669 }670 return call(...params);671 }672673 encodeApiCall(apiCall: string, params: any[]) {674 return this.constructApiCall(apiCall, params).method.toHex();675 }676677 async executeExtrinsic<678 E extends string,679 V extends (680...args: any) => any = ForceFunction<681 Get2<682 AugmentedSubmittables<'promise'>,683 E, (...args: any) => Invalid<'not found'>684 >685 >686 >(687 sender: TSigner,688 extrinsic: `api.tx.${E}`,689 params: Parameters<V>,690 expectSuccess = true,691 options: Partial<SignerOptions> | null = null,692 ): Promise<ITransactionResult> {693 if (this.api === null) throw Error('API not initialized');694 if (!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);695696 const startTime = (new Date()).getTime();697 let result: ITransactionResult;698 let events: IEvent[] = [];699 try {700 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;701 events = this.eventHelper.extractEvents(result.result.events);702 const errorEvent = events.find((event) => event.method == 'ExecutedFailed' || event.method == 'CreatedFailed');703 if (errorEvent)704 throw Error(errorEvent.method + ': ' + extrinsic);705 }706 catch (e) {707 if (!(e as object).hasOwnProperty('status')) throw e;708 result = e as ITransactionResult;709 }710711 const endTime = (new Date()).getTime();712713 const log = {714 executedAt: endTime,715 executionTime: endTime - startTime,716 type: this.chainLogType.EXTRINSIC,717 status: result.status,718 call: extrinsic,719 signer: this.getSignerAddress(sender),720 params,721 } as IUniqueHelperLog;722723 let errorMessage = '';724725 if (result.status !== this.transactionStatus.SUCCESS) {726 if (result.moduleError) {727 errorMessage = typeof result.moduleError === 'string'728 ? result.moduleError729 : `${Object.keys(result.moduleError)[0]}: ${Object.values(result.moduleError)[0]}`;730 log.moduleError = errorMessage;731 }732 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;733 }734 if (events.length > 0) log.events = events;735736 this.chainLog.push(log);737738 if (expectSuccess && result.status !== this.transactionStatus.SUCCESS) {739 if (result.moduleError) throw Error(`${errorMessage}`);740 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));741 }742 return result as any;743 }744745 async callRpc746 747 748 749 750 751 752 753 754 755 756 757 (rpc: string, params?: any[]): Promise<any> {758759 if (typeof params === 'undefined') params = [] as any;760 if (this.api === null) throw Error('API not initialized');761 if (!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);762763 const startTime = (new Date()).getTime();764 let result;765 let error = null;766 const log = {767 type: this.chainLogType.RPC,768 call: rpc,769 params,770 } as any as IUniqueHelperLog;771772 try {773 result = await this.constructApiCall(rpc, params as any);774 }775 catch (e) {776 error = e;777 }778779 const endTime = (new Date()).getTime();780781 log.executedAt = endTime;782 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';783 log.executionTime = endTime - startTime;784785 this.chainLog.push(log);786787 if (error !== null) throw error;788789 return result;790 }791792 getSignerAddress(signer: IKeyringPair | string): string {793 if (typeof signer === 'string') return signer;794 return signer.address;795 }796797 fetchAllPalletNames(): string[] {798 if (this.api === null) throw Error('API not initialized');799 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase()).sort();800 }801802 fetchMissingPalletNames(requiredPallets: readonly string[]): string[] {803 const palletNames = this.fetchAllPalletNames();804 return requiredPallets.filter(p => !palletNames.includes(p));805 }806}807808809class HelperGroup<T extends ChainHelperBase> {810 helper: T;811812 constructor(uniqueHelper: T) {813 this.helper = uniqueHelper;814 }815}816817818class CollectionGroup extends HelperGroup<UniqueHelper> {819 820821822823824825826827828 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {829 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();830 }831832 833834835836837 async getTotalCount(): Promise<number> {838 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();839 }840841 842843844845846847848849850 async getData(collectionId: number): Promise<{851 id: number;852 name: string;853 description: string;854 tokensCount: number;855 admins: CrossAccountId[];856 normalizedOwner: TSubstrateAccount;857 raw: any858 } | null> {859 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);860 const humanCollection = collection.toHuman(), collectionData = {861 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],862 raw: humanCollection,863 } as any, jsonCollection = collection.toJSON();864 if (humanCollection === null) return null;865 collectionData.raw.limits = jsonCollection.limits;866 collectionData.raw.permissions = jsonCollection.permissions;867 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);868 for (const key of ['name', 'description']) {869 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);870 }871872 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))873 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)874 : 0;875 collectionData.admins = await this.getAdmins(collectionId);876877 return collectionData;878 }879880 881882883884885886887888 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {889 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();890891 return normalize892 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())893 : admins;894 }895896 897898899900901902903 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {904 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();905 return normalize906 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())907 : allowListed;908 }909910 911912913914915916917 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {918 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();919 }920921 922923924925926927928929 async burn(signer: TSigner, collectionId: number): Promise<boolean> {930 const result = await this.helper.executeExtrinsic(931 signer,932 'api.tx.unique.destroyCollection', [collectionId],933 true,934 );935936 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');937 }938939 940941942943944945946947948 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {949 const result = await this.helper.executeExtrinsic(950 signer,951 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],952 true,953 );954955 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');956 }957958 959960961962963964965966 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {967 const result = await this.helper.executeExtrinsic(968 signer,969 'api.tx.unique.confirmSponsorship', [collectionId],970 true,971 );972973 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');974 }975976 977978979980981982983984 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {985 const result = await this.helper.executeExtrinsic(986 signer,987 'api.tx.unique.removeCollectionSponsor', [collectionId],988 true,989 );990991 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');992 }993994 995996997998999100010011002100310041005100610071008100910101011 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {1012 const result = await this.helper.executeExtrinsic(1013 signer,1014 'api.tx.unique.setCollectionLimits', [collectionId, limits],1015 true,1016 );10171018 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');1019 }10201021 102210231024102510261027102810291030 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {1031 const result = await this.helper.executeExtrinsic(1032 signer,1033 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],1034 true,1035 );10361037 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');1038 }10391040 104110421043104410451046104710481049 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1050 const result = await this.helper.executeExtrinsic(1051 signer,1052 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],1053 true,1054 );10551056 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');1057 }10581059 106010611062106310641065106610671068 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1069 const result = await this.helper.executeExtrinsic(1070 signer,1071 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],1072 true,1073 );10741075 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');1076 }10771078 10791080108110821083108410851086 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {1087 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();1088 }10891090 1091109210931094109510961097 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1098 const result = await this.helper.executeExtrinsic(1099 signer,1100 'api.tx.unique.addToAllowList', [collectionId, addressObj],1101 true,1102 );11031104 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1105 }11061107 11081109111011111112111311141115 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1116 const result = await this.helper.executeExtrinsic(1117 signer,1118 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1119 true,1120 );11211122 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1123 }11241125 112611271128112911301131113211331134 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1135 const result = await this.helper.executeExtrinsic(1136 signer,1137 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1138 true,1139 );11401141 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1142 }11431144 114511461147114811491150115111521153 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1154 return await this.setPermissions(signer, collectionId, {nesting: permissions});1155 }11561157 11581159116011611162116311641165 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1166 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1167 }11681169 117011711172117311741175117611771178 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1179 const result = await this.helper.executeExtrinsic(1180 signer,1181 'api.tx.unique.setCollectionProperties', [collectionId, properties],1182 true,1183 );11841185 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1186 }11871188 11891190119111921193119411951196 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1197 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1198 }11991200 async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1201 const api = this.helper.getApi();1202 const props = (await api.query.common.collectionProperties(collectionId)).toJSON();12031204 return (props! as any).consumedSpace;1205 }12061207 async getCollectionOptions(collectionId: number) {1208 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1209 }12101211 121212131214121512161217121812191220 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1221 const result = await this.helper.executeExtrinsic(1222 signer,1223 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1224 true,1225 );12261227 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1228 }12291230 12311232123312341235123612371238123912401241 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1242 const result = await this.helper.executeExtrinsic(1243 signer,1244 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1245 true, 1246 );12471248 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1249 }12501251 1252125312541255125612571258125912601261126212631264 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1265 const result = await this.helper.executeExtrinsic(1266 signer,1267 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1268 true, 1269 );1270 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1271 }12721273 12741275127612771278127912801281128212831284 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount = 1n): Promise<boolean> {1285 const burnResult = await this.helper.executeExtrinsic(1286 signer,1287 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1288 true, 1289 );1290 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1291 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1292 return burnedTokens.success;1293 }12941295 12961297129812991300130113021303130413051306 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1307 const burnResult = await this.helper.executeExtrinsic(1308 signer,1309 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1310 true, 1311 );1312 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1313 return burnedTokens.success && burnedTokens.tokens.length > 0;1314 }13151316 1317131813191320132113221323132413251326 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1327 const approveResult = await this.helper.executeExtrinsic(1328 signer,1329 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1330 true, 1331 );13321333 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1334 }13351336 13371338133913401341134213431344134513461347 async approveTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {1348 const approveResult = await this.helper.executeExtrinsic(1349 signer,1350 'api.tx.unique.approveFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1351 true, 1352 );13531354 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1355 }13561357 1358135913601361136213631364136513661367 async approveTokenFromEth(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1368 const ethMirror = CrossAccountId.fromKeyring(signer).toEthereum();1369 return await this.approveTokenFrom(signer, collectionId, tokenId, ethMirror, toAddressObj, amount);1370 }13711372 1373137413751376137713781379138013811382 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1383 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1384 }13851386 1387138813891390139113921393 async getLastTokenId(collectionId: number): Promise<number> {1394 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1395 }13961397 13981399140014011402140314041405 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1406 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1407 }1408}14091410class NFTnRFT extends CollectionGroup {1411 14121413141414151416141714181419 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1420 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1421 }14221423 1424142514261427142814291430143114321433 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1434 properties: IProperty[];1435 owner: CrossAccountId;1436 normalizedOwner: CrossAccountId;1437 } | null> {1438 let tokenData;1439 if (typeof blockHashAt === 'undefined') {1440 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1441 }1442 else {1443 if (propertyKeys.length == 0) {1444 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1445 if (!collection) return null;1446 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1447 }1448 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1449 }1450 tokenData = tokenData.toHuman();1451 if (tokenData === null || tokenData.owner === null) return null;1452 const owner = {} as any;1453 for (const key of Object.keys(tokenData.owner)) {1454 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1455 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1456 : tokenData.owner[key];1457 }1458 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1459 return tokenData;1460 }14611462 14631464146514661467146814691470 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1471 let owner;1472 if (typeof blockHashAt === 'undefined') {1473 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1474 } else {1475 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1476 }1477 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1478 }14791480 14811482148314841485148614871488 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1489 let owner;1490 if (typeof blockHashAt === 'undefined') {1491 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1492 } else {1493 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1494 }14951496 if (owner === null) return null;14971498 return owner.toHuman();1499 }15001501 15021503150415051506150715081509 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1510 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1511 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1512 if (!result) {1513 throw Error('Unable to nest token!');1514 }1515 return result;1516 }15171518 151915201521152215231524152515261527 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1528 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1529 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1530 if (!result) {1531 throw Error('Unable to unnest token!');1532 }1533 return result;1534 }15351536 15371538153915401541154215431544154515461547 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1548 const result = await this.helper.executeExtrinsic(1549 signer,1550 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1551 true,1552 );15531554 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1555 }15561557 15581559156015611562156315641565 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1566 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1567 }15681569 1570157115721573157415751576157715781579 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1580 const result = await this.helper.executeExtrinsic(1581 signer,1582 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1583 true,1584 );15851586 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1587 }15881589 159015911592159315941595159615971598 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1599 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1600 }16011602 160316041605160616071608160916101611 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1612 const result = await this.helper.executeExtrinsic(1613 signer,1614 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1615 true,1616 );16171618 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1619 }16201621 162216231624162516261627162816291630 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1631 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1632 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1633 for (const key of ['name', 'description', 'tokenPrefix']) {1634 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);1635 }1636 const creationResult = await this.helper.executeExtrinsic(1637 signer,1638 'api.tx.unique.createCollectionEx', [collectionOptions],1639 true, 1640 );1641 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1642 }16431644 getCollectionObject(_collectionId: number): any {1645 return null;1646 }16471648 getTokenObject(_collectionId: number, _tokenId: number): any {1649 return null;1650 }16511652 1653165416551656165716581659 async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1660 return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1661 }16621663 166416651666166716681669 async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1670 const result = await this.helper.executeExtrinsic(1671 signer,1672 'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1673 true,1674 );1675 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1676 }1677}167816791680class NFTGroup extends NFTnRFT {1681 168216831684168516861687 getCollectionObject(collectionId: number): UniqueNFTCollection {1688 return new UniqueNFTCollection(collectionId, this.helper);1689 }16901691 1692169316941695169616971698 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1699 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1700 }17011702 1703170417051706170717081709 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1710 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1711 }17121713 1714171517161717171817191720172117221723 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1724 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1725 }17261727 172817291730173117321733173417351736173717381739 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1740 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1741 }17421743 17441745174617471748174917501751 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1752 let children;1753 if (typeof blockHashAt === 'undefined') {1754 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1755 } else {1756 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1757 }17581759 return children.toJSON().map((x: any) => {1760 return {collectionId: x.collection, tokenId: x.token};1761 });1762 }17631764 176517661767176817691770177117721773177417751776 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1777 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1778 }17791780 178117821783178417851786 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1787 const creationResult = await this.helper.executeExtrinsic(1788 signer,1789 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1790 NFT: {1791 properties: data.properties,1792 },1793 }],1794 true,1795 );1796 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1797 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1798 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1799 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1800 }18011802 180318041805180618071808180918101811181218131814181518161817 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: { owner: ICrossAccountId, properties?: IProperty[] }[]): Promise<UniqueNFToken[]> {1818 const creationResult = await this.helper.executeExtrinsic(1819 signer,1820 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1821 true,1822 );1823 const collection = this.getCollectionObject(collectionId);1824 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1825 }18261827 182818291830183118321833183418351836183718381839184018411842184318441845 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: { properties?: IProperty[] }[]): Promise<UniqueNFToken[]> {1846 const rawTokens = [];1847 for (const token of tokens) {1848 const raw = {NFT: {properties: token.properties}};1849 rawTokens.push(raw);1850 }1851 const creationResult = await this.helper.executeExtrinsic(1852 signer,1853 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1854 true,1855 );1856 const collection = this.getCollectionObject(collectionId);1857 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1858 }18591860 1861186218631864186518661867186818691870 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1871 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1872 }1873}187418751876class RFTGroup extends NFTnRFT {1877 187818791880188118821883 getCollectionObject(collectionId: number): UniqueRFTCollection {1884 return new UniqueRFTCollection(collectionId, this.helper);1885 }18861887 1888188918901891189218931894 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1895 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1896 }18971898 1899190019011902190319041905 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1906 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1907 }19081909 19101911191219131914191519161917 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1918 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1919 }19201921 1922192319241925192619271928192919301931 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1932 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1933 }19341935 19361937193819391940194119421943194419451946 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1947 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1948 }19491950 195119521953195419551956195719581959196019611962 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1963 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1964 }19651966 1967196819691970197119721973 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1974 const creationResult = await this.helper.executeExtrinsic(1975 signer,1976 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1977 ReFungible: {1978 pieces: data.pieces,1979 properties: data.properties,1980 },1981 }],1982 true,1983 );1984 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1985 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1986 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1987 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1988 }19891990 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: { owner: ICrossAccountId, pieces: bigint, properties?: IProperty[] }[]): Promise<UniqueRFToken[]> {1991 throw Error('Not implemented');1992 const creationResult = await this.helper.executeExtrinsic(1993 signer,1994 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1995 true, 1996 );1997 const collection = this.getCollectionObject(collectionId);1998 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1999 }20002001 200220032004200520062007200820092010 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: { pieces: bigint, properties?: IProperty[] }[]): Promise<UniqueRFToken[]> {2011 const rawTokens = [];2012 for (const token of tokens) {2013 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};2014 rawTokens.push(raw);2015 }2016 const creationResult = await this.helper.executeExtrinsic(2017 signer,2018 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2019 true,2020 );2021 const collection = this.getCollectionObject(collectionId);2022 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));2023 }20242025 202620272028202920302031203220332034 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount = 1n): Promise<boolean> {2035 return await super.burnToken(signer, collectionId, tokenId, amount);2036 }20372038 2039204020412042204320442045204620472048 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {2049 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);2050 }20512052 20532054205520562057205820592060206120622063 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {2064 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);2065 }20662067 2068206920702071207220732074 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {2075 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();2076 }20772078 207920802081208220832084208520862087 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {2088 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);2089 const repartitionResult = await this.helper.executeExtrinsic(2090 signer,2091 'api.tx.unique.repartition', [collectionId, tokenId, amount],2092 true,2093 );2094 if (currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');2095 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');2096 }2097}209820992100class FTGroup extends CollectionGroup {2101 210221032104210521062107 getCollectionObject(collectionId: number): UniqueFTCollection {2108 return new UniqueFTCollection(collectionId, this.helper);2109 }21102111 2112211321142115211621172118211921202121212221232124 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {2125 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 2126 if (collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');2127 collectionOptions.mode = {fungible: decimalPoints};2128 for (const key of ['name', 'description', 'tokenPrefix']) {2129 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);2130 }2131 const creationResult = await this.helper.executeExtrinsic(2132 signer,2133 'api.tx.unique.createCollectionEx', [collectionOptions],2134 true,2135 );2136 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2137 }21382139 214021412142214321442145214621472148 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2149 const creationResult = await this.helper.executeExtrinsic(2150 signer,2151 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2152 Fungible: {2153 value: amount,2154 },2155 }],2156 true, 2157 );2158 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2159 }21602161 21622163216421652166216721682169 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: { value: bigint }[], owner: ICrossAccountId): Promise<boolean> {2170 const rawTokens = [];2171 for (const token of tokens) {2172 const raw = {Fungible: {Value: token.value}};2173 rawTokens.push(raw);2174 }2175 const creationResult = await this.helper.executeExtrinsic(2176 signer,2177 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2178 true,2179 );2180 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2181 }21822183 218421852186218721882189 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2190 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2191 }21922193 2194219521962197219821992200 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2201 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2202 }22032204 220522062207220822092210221122122213 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount = 1n) {2214 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2215 }22162217 2218221922202221222222232224222522262227 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {2228 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2229 }22302231 22322233223422352236223722382239 async burnTokens(signer: IKeyringPair, collectionId: number, amount = 1n): Promise<boolean> {2240 return await super.burnToken(signer, collectionId, 0, amount);2241 }22422243 224422452246224722482249225022512252 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {2253 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2254 }22552256 22572258225922602261 async getTotalPieces(collectionId: number): Promise<bigint> {2262 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2263 }22642265 2266226722682269227022712272227322742275 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount = 1n) {2276 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2277 }22782279 2280228122822283228422852286 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2287 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2288 }2289}229022912292class ChainGroup extends HelperGroup<ChainHelperBase> {2293 22942295229622972298 getChainProperties(): IChainProperties {2299 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2300 return {2301 ss58Format: properties.ss58Format.toJSON(),2302 tokenDecimals: properties.tokenDecimals.toJSON(),2303 tokenSymbol: properties.tokenSymbol.toJSON(),2304 };2305 }23062307 23082309231023112312 async getLatestBlockNumber(): Promise<number> {2313 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2314 }23152316 231723182319232023212322 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2323 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2324 if (blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2325 return blockHash;2326 }23272328 2329 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2330 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2331 if (!blockHash) return null;2332 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2333 }23342335 2336233723382339 async getRelayBlockNumber(): Promise<bigint> {2340 const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2341 return BigInt(blockNumber);2342 }23432344 234523462347234823492350 async getNonce(address: TSubstrateAccount): Promise<number> {2351 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2352 }2353}23542355class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2356 235723582359236023612362 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2363 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2364 }23652366 23672368236923702371237223732374 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2375 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);23762377 let transfer = {from: null, to: null, amount: 0n} as any;2378 result.result.events.forEach(({event: {data, method, section}}) => {2379 if ((section === 'balances') && (method === 'Transfer')) {2380 transfer = {2381 from: this.helper.address.normalizeSubstrate(data[0]),2382 to: this.helper.address.normalizeSubstrate(data[1]),2383 amount: BigInt(data[2]),2384 };2385 }2386 });2387 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2388 && this.helper.address.normalizeSubstrate(address) === transfer.to2389 && BigInt(amount) === transfer.amount;2390 return isSuccess;2391 }23922393 23942395239623972398 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2399 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2400 return {free: accountInfo.free.toBigInt(), frozen: accountInfo.frozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2401 }24022403 async getLocked(address: TSubstrateAccount): Promise<[{ id: string, amount: bigint, reason: string }]> {2404 const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2405 return locks.map((lock: any) => { return {id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons}; });2406 }2407}24082409class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2410 241124122413241424152416 async getEthereum(address: TEthereumAccount): Promise<bigint> {2417 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2418 }24192420 24212422242324242425242624272428 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2429 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);24302431 let transfer = {from: null, to: null, amount: 0n} as any;2432 result.result.events.forEach(({event: {data, method, section}}) => {2433 if ((section === 'balances') && (method === 'Transfer')) {2434 transfer = {2435 from: data[0].toString(),2436 to: data[1].toString(),2437 amount: BigInt(data[2]),2438 };2439 }2440 });2441 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2442 && address === transfer.to2443 && BigInt(amount) === transfer.amount;2444 return isSuccess;2445 }2446}24472448class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2449 subBalanceGroup: SubstrateBalanceGroup<T>;2450 ethBalanceGroup: EthereumBalanceGroup<T>;24512452 constructor(helper: T) {2453 super(helper);2454 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2455 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2456 }24572458 getCollectionCreationPrice(): bigint {2459 return 2n * this.getOneTokenNominal();2460 }2461 24622463246424652466 getOneTokenNominal(): bigint {2467 const chainProperties = this.helper.chain.getChainProperties();2468 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2469 }24702471 247224732474247524762477 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2478 return this.subBalanceGroup.getSubstrate(address);2479 }24802481 24822483248424852486 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2487 return this.subBalanceGroup.getSubstrateFull(address);2488 }24892490 24912492249324942495 getLocked(address: TSubstrateAccount) {2496 return this.subBalanceGroup.getLocked(address);2497 }24982499 250025012502250325042505 getEthereum(address: TEthereumAccount): Promise<bigint> {2506 return this.ethBalanceGroup.getEthereum(address);2507 }25082509 async setBalanceSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint, reservedAmount = 0n) {2510 await this.helper.executeExtrinsic(signer, 'api.tx.balances.setBalance', [address, amount, reservedAmount], true);2511 }25122513 25142515251625172518251925202521 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2522 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2523 }25242525 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2526 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);25272528 let transfer = {from: null, to: null, amount: 0n} as any;2529 result.result.events.forEach(({event: {data, method, section}}) => {2530 if ((section === 'balances') && (method === 'Transfer')) {2531 transfer = {2532 from: this.helper.address.normalizeSubstrate(data[0]),2533 to: this.helper.address.normalizeSubstrate(data[1]),2534 amount: BigInt(data[2]),2535 };2536 }2537 });2538 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2539 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2540 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2541 return isSuccess;2542 }25432544 2545254625472548254925502551 async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: { start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint }): Promise<void> {2552 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2553 const event = result.result.events2554 .find(e => e.event.section === 'vesting' &&2555 e.event.method === 'VestingScheduleAdded' &&2556 e.event.data[0].toHuman() === signer.address);2557 if (!event) throw Error('Cannot find transfer in events');2558 }25592560 25612562256325642565 async getVestingSchedules(address: TSubstrateAccount): Promise<{ start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint }[]> {2566 const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2567 return schedule.map((schedule: any) => {2568 return {2569 start: BigInt(schedule.start),2570 period: BigInt(schedule.period),2571 periodCount: BigInt(schedule.periodCount),2572 perPeriod: BigInt(schedule.perPeriod),2573 };2574 });2575 }25762577 2578257925802581 async claim(signer: TSigner) {2582 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2583 const event = result.result.events2584 .find(e => e.event.section === 'vesting' &&2585 e.event.method === 'Claimed' &&2586 e.event.data[0].toHuman() === signer.address);2587 if (!event) throw Error('Cannot find claim in events');2588 }2589}25902591class AddressGroup extends HelperGroup<ChainHelperBase> {2592 2593259425952596259725982599 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2600 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2601 }26022603 260426052606260726082609 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2610 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2611 }26122613 2614261526162617261826192620 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat = false): TSubstrateAccount {2621 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2622 }26232624 262526262627262826292630 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2631 return CrossAccountId.translateSubToEth(subAddress);2632 }26332634 263526362637263826392640 encodeSubstrateAddress(key: Uint8Array | string | bigint, ss58Format = 42): string {2641 const u8a: Uint8Array = typeof key === 'string'2642 ? hexToU8a(key)2643 : typeof key === 'bigint'2644 ? hexToU8a(key.toString(16))2645 : key;26462647 if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2648 throw new Error(`ss58Format is not valid, received ${typeof ss58Format} "${ss58Format}"`);2649 }26502651 const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2652 if (!allowedDecodedLengths.includes(u8a.length)) {2653 throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2654 }26552656 const u8aPrefix = ss58Format < 642657 ? new Uint8Array([ss58Format])2658 : new Uint8Array([2659 ((ss58Format & 0xfc) >> 2) | 0x40,2660 (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2661 ]);26622663 const input = u8aConcat(u8aPrefix, u8a);26642665 return base58Encode(u8aConcat(2666 input,2667 blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2668 ));2669 }26702671 26722673267426752676 restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2677 if (this.helper.api === null) {2678 throw 'Not connected';2679 }2680 const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2681 if (res === undefined || res === null) {2682 throw 'Restore address error';2683 }2684 return res.toString();2685 }26862687 26882689269026912692 convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2693 if (ethCrossAccount.sub === '0') {2694 return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2695 }26962697 const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2698 return {Substrate: ss58};2699 }27002701 paraSiblingSovereignAccount(paraid: number) {2702 2703 2704 const siblingPrefix = '0x7369626c';27052706 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2707 const suffix = '000000000000000000000000000000000000000000000000';27082709 return siblingPrefix + encodedParaId + suffix;2710 }2711}27122713class StakingGroup extends HelperGroup<UniqueHelper> {2714 2715271627172718271927202721 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2722 if (typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2723 const _stakeResult = await this.helper.executeExtrinsic(2724 signer, 'api.tx.appPromotion.stake',2725 [amountToStake], true,2726 );2727 2728 return true;2729 }27302731 2732273327342735273627372738 async unstakeAll(signer: TSigner, label?: string): Promise<string> {2739 if (typeof label === 'undefined') label = `${signer.address}`;2740 const unstakeResult = await this.helper.executeExtrinsic(2741 signer, 'api.tx.appPromotion.unstakeAll',2742 [], true,2743 );2744 return unstakeResult.blockHash;2745 }27462747 2748274927502751275227532754 async unstakePartial(signer: TSigner, amount: bigint, label?: string): Promise<string> {2755 if (typeof label === 'undefined') label = `${signer.address}`;2756 const unstakeResult = await this.helper.executeExtrinsic(2757 signer, 'api.tx.appPromotion.unstakePartial',2758 [amount], true,2759 );2760 return unstakeResult.blockHash;2761 }27622763 27642765276627672768 async getStakesNumber(address: ICrossAccountId): Promise<number> {2769 if ('Ethereum' in address) throw Error('only substrate address');2770 return (await this.helper.callRpc('api.query.appPromotion.stakesPerAccount', [address.Substrate])).toNumber();2771 }27722773 27742775277627772778 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2779 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2780 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2781 }27822783 27842785278627872788 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2789 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2790 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2791 return {2792 block: block.toBigInt(),2793 amount: amount.toBigInt(),2794 };2795 });2796 }27972798 27992800280128022803 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2804 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2805 }28062807 28082809281028112812 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2813 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2814 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2815 return {2816 block: block.toBigInt(),2817 amount: amount.toBigInt(),2818 };2819 });2820 return result;2821 }2822}28232824class SchedulerGroup extends HelperGroup<UniqueHelper> {2825 constructor(helper: UniqueHelper) {2826 super(helper);2827 }28282829 cancelScheduled(signer: TSigner, scheduledId: string) {2830 return this.helper.executeExtrinsic(2831 signer,2832 'api.tx.scheduler.cancelNamed',2833 [scheduledId],2834 true,2835 );2836 }28372838 changePriority(signer: TSigner, scheduledId: string, priority: number) {2839 return this.helper.executeExtrinsic(2840 signer,2841 'api.tx.scheduler.changeNamedPriority',2842 [scheduledId, priority],2843 true,2844 );2845 }28462847 scheduleAt<T extends UniqueHelper>(2848 executionBlockNumber: number,2849 options: ISchedulerOptions = {},2850 ) {2851 return this.schedule<T>('schedule', executionBlockNumber, options);2852 }28532854 scheduleAfter<T extends UniqueHelper>(2855 blocksBeforeExecution: number,2856 options: ISchedulerOptions = {},2857 ) {2858 return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2859 }28602861 schedule<T extends UniqueHelper>(2862 scheduleFn: 'schedule' | 'scheduleAfter',2863 blocksNum: number,2864 options: ISchedulerOptions = {},2865 ) {2866 2867 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2868 return this.helper.clone(ScheduledHelperType, {2869 scheduleFn,2870 blocksNum,2871 options,2872 }) as T;2873 }2874}28752876class CollatorSelectionGroup extends HelperGroup<UniqueHelper> {2877 2878 addInvulnerable(signer: TSigner, address: string) {2879 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.addInvulnerable', [address]);2880 }28812882 removeInvulnerable(signer: TSigner, address: string) {2883 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.removeInvulnerable', [address]);2884 }28852886 async getInvulnerables(): Promise<string[]> {2887 return (await this.helper.callRpc('api.query.collatorSelection.invulnerables')).map((x: any) => x.toHuman());2888 }28892890 2891 maxCollators(): number {2892 return (this.helper.getApi().consts.configuration.defaultCollatorSelectionMaxCollators.toJSON() as number);2893 }28942895 async getDesiredCollators(): Promise<number> {2896 return (await this.helper.callRpc('api.query.configuration.collatorSelectionDesiredCollatorsOverride')).toNumber();2897 }28982899 setLicenseBond(signer: TSigner, amount: bigint) {2900 return this.helper.executeExtrinsic(signer, 'api.tx.configuration.setCollatorSelectionLicenseBond', [amount]);2901 }29022903 async getLicenseBond(): Promise<bigint> {2904 return (await this.helper.callRpc('api.query.configuration.collatorSelectionLicenseBondOverride')).toBigInt();2905 }29062907 obtainLicense(signer: TSigner) {2908 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.getLicense', []);2909 }29102911 releaseLicense(signer: TSigner) {2912 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.releaseLicense', []);2913 }29142915 forceReleaseLicense(signer: TSigner, released: string) {2916 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.forceReleaseLicense', [released]);2917 }29182919 async hasLicense(address: string): Promise<bigint> {2920 return (await this.helper.callRpc('api.query.collatorSelection.licenseDepositOf', [address])).toBigInt();2921 }29222923 onboard(signer: TSigner) {2924 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.onboard', []);2925 }29262927 offboard(signer: TSigner) {2928 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.offboard', []);2929 }29302931 async getCandidates(): Promise<string[]> {2932 return (await this.helper.callRpc('api.query.collatorSelection.candidates')).map((x: any) => x.toHuman());2933 }2934}29352936class PreimageGroup extends HelperGroup<UniqueHelper> {2937 async getPreimageInfo(h256: string) {2938 return (await this.helper.callRpc('api.query.preimage.statusFor', [h256])).toJSON();2939 }29402941 294229432944294529462947294829492950 notePreimage(signer: TSigner, bytes: string | Uint8Array) {2951 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.notePreimage', [bytes]);2952 }29532954 295529562957295829592960 unnotePreimage(signer: TSigner, h256: string) {2961 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unnotePreimage', [h256]);2962 }29632964 296529662967296829692970 requestPreimage(signer: TSigner, h256: string) {2971 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.requestPreimage', [h256]);2972 }29732974 297529762977297829792980 unrequestPreimage(signer: TSigner, h256: string) {2981 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unrequestPreimage', [h256]);2982 }2983}29842985class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2986 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2987 await this.helper.executeExtrinsic(2988 signer,2989 'api.tx.foreignAssets.registerForeignAsset',2990 [ownerAddress, location, metadata],2991 true,2992 );2993 }29942995 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2996 await this.helper.executeExtrinsic(2997 signer,2998 'api.tx.foreignAssets.updateForeignAsset',2999 [foreignAssetId, location, metadata],3000 true,3001 );3002 }3003}30043005class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {3006 palletName: string;30073008 constructor(helper: T, palletName: string) {3009 super(helper);30103011 this.palletName = palletName;3012 }30133014 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {3015 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);3016 }30173018 async setSafeXcmVersion(signer: TSigner, version: number) {3019 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.forceDefaultXcmVersion`, [version], true);3020 }30213022 async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {3023 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);3024 }30253026 async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint, xcmVersion = 3) {3027 const destinationContent = {3028 parents: 0,3029 interior: {3030 X1: {3031 Parachain: destinationParaId,3032 },3033 },3034 };30353036 const beneficiaryContent = {3037 parents: 0,3038 interior: {3039 X1: {3040 AccountId32: {3041 network: 'Any',3042 id: targetAccount,3043 },3044 },3045 },3046 };30473048 const assetsContent = [3049 {3050 id: {3051 Concrete: {3052 parents: 0,3053 interior: 'Here',3054 },3055 },3056 fun: {3057 Fungible: amount,3058 },3059 },3060 ];30613062 let destination;3063 let beneficiary;3064 let assets;30653066 if (xcmVersion == 2) {3067 destination = {V1: destinationContent};3068 beneficiary = {V1: beneficiaryContent};3069 assets = {V1: assetsContent};30703071 } else if (xcmVersion == 3) {3072 destination = {V2: destinationContent};3073 beneficiary = {V2: beneficiaryContent};3074 assets = {V2: assetsContent};30753076 } else {3077 throw Error('Unknown XCM version: ' + xcmVersion);3078 }30793080 const feeAssetItem = 0;30813082 await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);3083 }30843085 async send(signer: IKeyringPair, destination: any, message: any) {3086 await this.helper.executeExtrinsic(3087 signer,3088 `api.tx.${this.palletName}.send`,3089 [3090 destination,3091 message,3092 ],3093 true,3094 );3095 }3096}30973098class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {3099 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {3100 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);3101 }31023103 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {3104 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);3105 }31063107 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {3108 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);3109 }3110}31113112class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {3113 async accounts(address: string, currencyId: any) {3114 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;3115 return BigInt(free);3116 }3117}31183119class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {3120 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {3121 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);3122 }31233124 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {3125 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);3126 }31273128 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {3129 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);3130 }31313132 async account(assetId: string | number, address: string) {3133 const accountAsset = (3134 await this.helper.callRpc('api.query.assets.account', [assetId, address])3135 ).toJSON()! as any;31363137 if (accountAsset !== null) {3138 return BigInt(accountAsset['balance']);3139 } else {3140 return null;3141 }3142 }3143}31443145class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {3146 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {3147 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);3148 }3149}31503151class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {3152 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {3153 const apiPrefix = 'api.tx.assetManager.';31543155 const registerTx = this.helper.constructApiCall(3156 apiPrefix + 'registerForeignAsset',3157 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],3158 );31593160 const setUnitsTx = this.helper.constructApiCall(3161 apiPrefix + 'setAssetUnitsPerSecond',3162 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],3163 );31643165 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);3166 const encodedProposal = batchCall?.method.toHex() || '';3167 return encodedProposal;3168 }31693170 async assetTypeId(location: any) {3171 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);3172 }3173}31743175class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {3176 notePreimagePallet: string;31773178 constructor(helper: MoonbeamHelper, options: { [key: string]: any } = {}) {3179 super(helper);3180 this.notePreimagePallet = options.notePreimagePallet;3181 }31823183 async notePreimage(signer: TSigner, encodedProposal: string) {3184 await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);3185 }31863187 externalProposeMajority(proposal: any) {3188 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);3189 }31903191 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {3192 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);3193 }31943195 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {3196 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);3197 }3198}31993200class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {3201 collective: string;32023203 constructor(helper: MoonbeamHelper, collective: string) {3204 super(helper);32053206 this.collective = collective;3207 }32083209 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {3210 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);3211 }32123213 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {3214 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);3215 }32163217 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {3218 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);3219 }32203221 async proposalCount() {3222 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));3223 }3224}32253226export type ChainHelperBaseConstructor = new (...args: any[]) => ChainHelperBase;3227export type UniqueHelperConstructor = new (...args: any[]) => UniqueHelper;32283229export class UniqueHelper extends ChainHelperBase {3230 balance: BalanceGroup<UniqueHelper>;3231 collection: CollectionGroup;3232 nft: NFTGroup;3233 rft: RFTGroup;3234 ft: FTGroup;3235 staking: StakingGroup;3236 scheduler: SchedulerGroup;3237 collatorSelection: CollatorSelectionGroup;3238 preimage: PreimageGroup;3239 foreignAssets: ForeignAssetsGroup;3240 xcm: XcmGroup<UniqueHelper>;3241 xTokens: XTokensGroup<UniqueHelper>;3242 tokens: TokensGroup<UniqueHelper>;32433244 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3245 super(logger, options.helperBase ?? UniqueHelper);32463247 this.balance = new BalanceGroup(this);3248 this.collection = new CollectionGroup(this);3249 this.nft = new NFTGroup(this);3250 this.rft = new RFTGroup(this);3251 this.ft = new FTGroup(this);3252 this.staking = new StakingGroup(this);3253 this.scheduler = new SchedulerGroup(this);3254 this.collatorSelection = new CollatorSelectionGroup(this);3255 this.preimage = new PreimageGroup(this);3256 this.foreignAssets = new ForeignAssetsGroup(this);3257 this.xcm = new XcmGroup(this, 'polkadotXcm');3258 this.xTokens = new XTokensGroup(this);3259 this.tokens = new TokensGroup(this);3260 }32613262 getSudo<T extends UniqueHelper>() {3263 3264 const SudoHelperType = SudoHelper(this.helperBase);3265 return this.clone(SudoHelperType) as T;3266 }3267}32683269export class XcmChainHelper extends ChainHelperBase {3270 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {3271 const wsProvider = new WsProvider(wsEndpoint);3272 this.api = new ApiPromise({3273 provider: wsProvider,3274 });3275 await this.api.isReadyOrError;3276 this.network = await UniqueHelper.detectNetwork(this.api);3277 }3278}32793280export class RelayHelper extends XcmChainHelper {3281 balance: SubstrateBalanceGroup<RelayHelper>;3282 xcm: XcmGroup<RelayHelper>;32833284 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3285 super(logger, options.helperBase ?? RelayHelper);32863287 this.balance = new SubstrateBalanceGroup(this);3288 this.xcm = new XcmGroup(this, 'xcmPallet');3289 }3290}32913292export class WestmintHelper extends XcmChainHelper {3293 balance: SubstrateBalanceGroup<WestmintHelper>;3294 xcm: XcmGroup<WestmintHelper>;3295 assets: AssetsGroup<WestmintHelper>;3296 xTokens: XTokensGroup<WestmintHelper>;32973298 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3299 super(logger, options.helperBase ?? WestmintHelper);33003301 this.balance = new SubstrateBalanceGroup(this);3302 this.xcm = new XcmGroup(this, 'polkadotXcm');3303 this.assets = new AssetsGroup(this);3304 this.xTokens = new XTokensGroup(this);3305 }3306}33073308export class MoonbeamHelper extends XcmChainHelper {3309 balance: EthereumBalanceGroup<MoonbeamHelper>;3310 assetManager: MoonbeamAssetManagerGroup;3311 assets: AssetsGroup<MoonbeamHelper>;3312 xTokens: XTokensGroup<MoonbeamHelper>;3313 democracy: MoonbeamDemocracyGroup;3314 collective: {3315 council: MoonbeamCollectiveGroup,3316 techCommittee: MoonbeamCollectiveGroup,3317 };33183319 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3320 super(logger, options.helperBase ?? MoonbeamHelper);33213322 this.balance = new EthereumBalanceGroup(this);3323 this.assetManager = new MoonbeamAssetManagerGroup(this);3324 this.assets = new AssetsGroup(this);3325 this.xTokens = new XTokensGroup(this);3326 this.democracy = new MoonbeamDemocracyGroup(this, options);3327 this.collective = {3328 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),3329 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),3330 };3331 }3332}33333334export class AstarHelper extends XcmChainHelper {3335 balance: SubstrateBalanceGroup<AstarHelper>;3336 assets: AssetsGroup<AstarHelper>;3337 xcm: XcmGroup<AstarHelper>;33383339 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3340 super(logger, options.helperBase ?? AstarHelper);33413342 this.balance = new SubstrateBalanceGroup(this);3343 this.assets = new AssetsGroup(this);3344 this.xcm = new XcmGroup(this, 'polkadotXcm');3345 }33463347 getSudo<T extends UniqueHelper>() {3348 3349 const SudoHelperType = SudoHelper(this.helperBase);3350 return this.clone(SudoHelperType) as T;3351 }3352}33533354export class AcalaHelper extends XcmChainHelper {3355 balance: SubstrateBalanceGroup<AcalaHelper>;3356 assetRegistry: AcalaAssetRegistryGroup;3357 xTokens: XTokensGroup<AcalaHelper>;3358 tokens: TokensGroup<AcalaHelper>;3359 xcm: XcmGroup<AcalaHelper>;33603361 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3362 super(logger, options.helperBase ?? AcalaHelper);33633364 this.balance = new SubstrateBalanceGroup(this);3365 this.assetRegistry = new AcalaAssetRegistryGroup(this);3366 this.xTokens = new XTokensGroup(this);3367 this.tokens = new TokensGroup(this);3368 this.xcm = new XcmGroup(this, 'polkadotXcm');3369 }33703371 getSudo<T extends AcalaHelper>() {3372 3373 const SudoHelperType = SudoHelper(this.helperBase);3374 return this.clone(SudoHelperType) as T;3375 }3376}337733783379function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3380 return class extends Base {3381 scheduleFn: 'schedule' | 'scheduleAfter';3382 blocksNum: number;3383 options: ISchedulerOptions;33843385 constructor(...args: any[]) {3386 const logger = args[0] as ILogger;3387 const options = args[1] as {3388 scheduleFn: 'schedule' | 'scheduleAfter',3389 blocksNum: number,3390 options: ISchedulerOptions3391 };33923393 super(logger);33943395 this.scheduleFn = options.scheduleFn;3396 this.blocksNum = options.blocksNum;3397 this.options = options.options;3398 }33993400 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3401 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);34023403 const mandatorySchedArgs = [3404 this.blocksNum,3405 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3406 this.options.priority ?? null,3407 scheduledTx,3408 ];34093410 let schedArgs;3411 let scheduleFn;34123413 if (this.options.scheduledId) {3414 schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];34153416 if (this.scheduleFn == 'schedule') {3417 scheduleFn = 'scheduleNamed';3418 } else if (this.scheduleFn == 'scheduleAfter') {3419 scheduleFn = 'scheduleNamedAfter';3420 }3421 } else {3422 schedArgs = mandatorySchedArgs;3423 scheduleFn = this.scheduleFn;3424 }34253426 const extrinsic = 'api.tx.scheduler.' + scheduleFn;34273428 return super.executeExtrinsic(3429 sender,3430 extrinsic as any,3431 schedArgs,3432 expectSuccess,3433 );3434 }3435 };3436}343734383439function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3440 return class extends Base {3441 constructor(...args: any[]) {3442 super(...args);3443 }34443445 async executeExtrinsic(3446 sender: IKeyringPair,3447 extrinsic: string,3448 params: any[],3449 expectSuccess?: boolean,3450 options: Partial<SignerOptions> | null = null,3451 ): Promise<ITransactionResult> {3452 const call = this.constructApiCall(extrinsic, params);3453 const result = await super.executeExtrinsic(3454 sender,3455 'api.tx.sudo.sudo',3456 [call],3457 expectSuccess,3458 options,3459 );34603461 if (result.status === 'Fail') return result;34623463 const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;3464 if (data.isErr) {3465 if (data.asErr.isModule) {3466 const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;3467 const metaError = super.getApi()?.registry.findMetaError(error);3468 throw new Error(`${metaError.section}.${metaError.name}`);3469 } else if (data.asErr.isToken) {3470 throw new Error(`Token: ${data.asErr.asToken}`);3471 }3472 }3473 return result;3474 }3475 };3476}34773478export class UniqueBaseCollection {3479 helper: UniqueHelper;3480 collectionId: number;34813482 constructor(collectionId: number, uniqueHelper: UniqueHelper) {3483 this.collectionId = collectionId;3484 this.helper = uniqueHelper;3485 }34863487 async getData() {3488 return await this.helper.collection.getData(this.collectionId);3489 }34903491 async getLastTokenId() {3492 return await this.helper.collection.getLastTokenId(this.collectionId);3493 }34943495 async doesTokenExist(tokenId: number) {3496 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3497 }34983499 async getAdmins() {3500 return await this.helper.collection.getAdmins(this.collectionId);3501 }35023503 async getAllowList() {3504 return await this.helper.collection.getAllowList(this.collectionId);3505 }35063507 async getEffectiveLimits() {3508 return await this.helper.collection.getEffectiveLimits(this.collectionId);3509 }35103511 async getProperties(propertyKeys?: string[] | null) {3512 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3513 }35143515 async getPropertiesConsumedSpace() {3516 return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3517 }35183519 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3520 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3521 }35223523 async getOptions() {3524 return await this.helper.collection.getCollectionOptions(this.collectionId);3525 }35263527 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3528 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3529 }35303531 async confirmSponsorship(signer: TSigner) {3532 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3533 }35343535 async removeSponsor(signer: TSigner) {3536 return await this.helper.collection.removeSponsor(signer, this.collectionId);3537 }35383539 async setLimits(signer: TSigner, limits: ICollectionLimits) {3540 return await this.helper.collection.setLimits(signer, this.collectionId, limits);3541 }35423543 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3544 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3545 }35463547 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3548 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3549 }35503551 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3552 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3553 }35543555 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3556 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3557 }35583559 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3560 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3561 }35623563 async setProperties(signer: TSigner, properties: IProperty[]) {3564 return await this.helper.collection.setProperties(signer, this.collectionId, properties);3565 }35663567 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3568 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3569 }35703571 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3572 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3573 }35743575 async enableNesting(signer: TSigner, permissions: INestingPermissions) {3576 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3577 }35783579 async disableNesting(signer: TSigner) {3580 return await this.helper.collection.disableNesting(signer, this.collectionId);3581 }35823583 async burn(signer: TSigner) {3584 return await this.helper.collection.burn(signer, this.collectionId);3585 }35863587 scheduleAt<T extends UniqueHelper>(3588 executionBlockNumber: number,3589 options: ISchedulerOptions = {},3590 ) {3591 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3592 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3593 }35943595 scheduleAfter<T extends UniqueHelper>(3596 blocksBeforeExecution: number,3597 options: ISchedulerOptions = {},3598 ) {3599 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3600 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3601 }36023603 getSudo<T extends UniqueHelper>() {3604 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3605 }3606}360736083609export class UniqueNFTCollection extends UniqueBaseCollection {3610 getTokenObject(tokenId: number) {3611 return new UniqueNFToken(tokenId, this);3612 }36133614 async getTokensByAddress(addressObj: ICrossAccountId) {3615 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3616 }36173618 async getToken(tokenId: number, blockHashAt?: string) {3619 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3620 }36213622 async getTokenOwner(tokenId: number, blockHashAt?: string) {3623 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3624 }36253626 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3627 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3628 }36293630 async getTokenChildren(tokenId: number, blockHashAt?: string) {3631 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3632 }36333634 async getPropertyPermissions(propertyKeys: string[] | null = null) {3635 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3636 }36373638 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3639 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3640 }36413642 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3643 const api = this.helper.getApi();3644 const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();36453646 return (props! as any).consumedSpace;3647 }36483649 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3650 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3651 }36523653 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3654 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3655 }36563657 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3658 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3659 }36603661 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3662 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3663 }36643665 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3666 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3667 }36683669 async mintMultipleTokens(signer: TSigner, tokens: { owner: ICrossAccountId, properties?: IProperty[] }[]) {3670 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3671 }36723673 async burnToken(signer: TSigner, tokenId: number) {3674 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3675 }36763677 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3678 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3679 }36803681 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3682 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3683 }36843685 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3686 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3687 }36883689 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3690 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3691 }36923693 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3694 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3695 }36963697 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3698 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3699 }37003701 scheduleAt<T extends UniqueHelper>(3702 executionBlockNumber: number,3703 options: ISchedulerOptions = {},3704 ) {3705 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3706 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3707 }37083709 scheduleAfter<T extends UniqueHelper>(3710 blocksBeforeExecution: number,3711 options: ISchedulerOptions = {},3712 ) {3713 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3714 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3715 }37163717 getSudo<T extends UniqueHelper>() {3718 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3719 }3720}372137223723export class UniqueRFTCollection extends UniqueBaseCollection {3724 getTokenObject(tokenId: number) {3725 return new UniqueRFToken(tokenId, this);3726 }37273728 async getToken(tokenId: number, blockHashAt?: string) {3729 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3730 }37313732 async getTokenOwner(tokenId: number, blockHashAt?: string) {3733 return await this.helper.rft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3734 }37353736 async getTokensByAddress(addressObj: ICrossAccountId) {3737 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3738 }37393740 async getTop10TokenOwners(tokenId: number) {3741 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3742 }37433744 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3745 return await this.helper.rft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3746 }37473748 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3749 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3750 }37513752 async getTokenTotalPieces(tokenId: number) {3753 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3754 }37553756 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3757 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3758 }37593760 async getPropertyPermissions(propertyKeys: string[] | null = null) {3761 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3762 }37633764 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3765 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3766 }37673768 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3769 const api = this.helper.getApi();3770 const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();37713772 return (props! as any).consumedSpace;3773 }37743775 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount = 1n) {3776 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3777 }37783779 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {3780 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3781 }37823783 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {3784 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3785 }37863787 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3788 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3789 }37903791 async mintToken(signer: TSigner, pieces = 1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3792 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3793 }37943795 async mintMultipleTokens(signer: TSigner, tokens: { pieces: bigint, owner: ICrossAccountId, properties?: IProperty[] }[]) {3796 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3797 }37983799 async burnToken(signer: TSigner, tokenId: number, amount = 1n) {3800 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3801 }38023803 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n) {3804 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3805 }38063807 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3808 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3809 }38103811 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3812 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3813 }38143815 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3816 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3817 }38183819 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3820 return await this.helper.rft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3821 }38223823 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3824 return await this.helper.rft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3825 }38263827 scheduleAt<T extends UniqueHelper>(3828 executionBlockNumber: number,3829 options: ISchedulerOptions = {},3830 ) {3831 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3832 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3833 }38343835 scheduleAfter<T extends UniqueHelper>(3836 blocksBeforeExecution: number,3837 options: ISchedulerOptions = {},3838 ) {3839 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3840 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3841 }38423843 getSudo<T extends UniqueHelper>() {3844 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3845 }3846}384738483849export class UniqueFTCollection extends UniqueBaseCollection {3850 async getBalance(addressObj: ICrossAccountId) {3851 return await this.helper.ft.getBalance(this.collectionId, addressObj);3852 }38533854 async getTotalPieces() {3855 return await this.helper.ft.getTotalPieces(this.collectionId);3856 }38573858 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3859 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3860 }38613862 async getTop10Owners() {3863 return await this.helper.ft.getTop10Owners(this.collectionId);3864 }38653866 async mint(signer: TSigner, amount = 1n, owner: ICrossAccountId = {Substrate: signer.address}) {3867 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3868 }38693870 async mintWithOneOwner(signer: TSigner, tokens: { value: bigint }[], owner: ICrossAccountId = {Substrate: signer.address}) {3871 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3872 }38733874 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {3875 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3876 }38773878 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {3879 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3880 }38813882 async burnTokens(signer: TSigner, amount = 1n) {3883 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3884 }38853886 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount = 1n) {3887 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3888 }38893890 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {3891 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3892 }38933894 scheduleAt<T extends UniqueHelper>(3895 executionBlockNumber: number,3896 options: ISchedulerOptions = {},3897 ) {3898 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3899 return new UniqueFTCollection(this.collectionId, scheduledHelper);3900 }39013902 scheduleAfter<T extends UniqueHelper>(3903 blocksBeforeExecution: number,3904 options: ISchedulerOptions = {},3905 ) {3906 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3907 return new UniqueFTCollection(this.collectionId, scheduledHelper);3908 }39093910 getSudo<T extends UniqueHelper>() {3911 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3912 }3913}391439153916export class UniqueBaseToken {3917 collection: UniqueNFTCollection | UniqueRFTCollection;3918 collectionId: number;3919 tokenId: number;39203921 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3922 this.collection = collection;3923 this.collectionId = collection.collectionId;3924 this.tokenId = tokenId;3925 }39263927 async getNextSponsored(addressObj: ICrossAccountId) {3928 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3929 }39303931 async getProperties(propertyKeys?: string[] | null) {3932 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3933 }39343935 async getTokenPropertiesConsumedSpace() {3936 return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3937 }39383939 async setProperties(signer: TSigner, properties: IProperty[]) {3940 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3941 }39423943 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3944 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3945 }39463947 async doesExist() {3948 return await this.collection.doesTokenExist(this.tokenId);3949 }39503951 nestingAccount() {3952 return this.collection.helper.util.getTokenAccount(this);3953 }39543955 scheduleAt<T extends UniqueHelper>(3956 executionBlockNumber: number,3957 options: ISchedulerOptions = {},3958 ) {3959 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3960 return new UniqueBaseToken(this.tokenId, scheduledCollection);3961 }39623963 scheduleAfter<T extends UniqueHelper>(3964 blocksBeforeExecution: number,3965 options: ISchedulerOptions = {},3966 ) {3967 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3968 return new UniqueBaseToken(this.tokenId, scheduledCollection);3969 }39703971 getSudo<T extends UniqueHelper>() {3972 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3973 }3974}397539763977export class UniqueNFToken extends UniqueBaseToken {3978 collection: UniqueNFTCollection;39793980 constructor(tokenId: number, collection: UniqueNFTCollection) {3981 super(tokenId, collection);3982 this.collection = collection;3983 }39843985 async getData(blockHashAt?: string) {3986 return await this.collection.getToken(this.tokenId, blockHashAt);3987 }39883989 async getOwner(blockHashAt?: string) {3990 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3991 }39923993 async getTopmostOwner(blockHashAt?: string) {3994 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3995 }39963997 async getChildren(blockHashAt?: string) {3998 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3999 }40004001 async nest(signer: TSigner, toTokenObj: IToken) {4002 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);4003 }40044005 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {4006 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);4007 }40084009 async transfer(signer: TSigner, addressObj: ICrossAccountId) {4010 return await this.collection.transferToken(signer, this.tokenId, addressObj);4011 }40124013 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {4014 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);4015 }40164017 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {4018 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);4019 }40204021 async isApproved(toAddressObj: ICrossAccountId) {4022 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);4023 }40244025 async burn(signer: TSigner) {4026 return await this.collection.burnToken(signer, this.tokenId);4027 }40284029 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {4030 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);4031 }40324033 scheduleAt<T extends UniqueHelper>(4034 executionBlockNumber: number,4035 options: ISchedulerOptions = {},4036 ) {4037 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);4038 return new UniqueNFToken(this.tokenId, scheduledCollection);4039 }40404041 scheduleAfter<T extends UniqueHelper>(4042 blocksBeforeExecution: number,4043 options: ISchedulerOptions = {},4044 ) {4045 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);4046 return new UniqueNFToken(this.tokenId, scheduledCollection);4047 }40484049 getSudo<T extends UniqueHelper>() {4050 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());4051 }4052}40534054export class UniqueRFToken extends UniqueBaseToken {4055 collection: UniqueRFTCollection;40564057 constructor(tokenId: number, collection: UniqueRFTCollection) {4058 super(tokenId, collection);4059 this.collection = collection;4060 }40614062 async getData(blockHashAt?: string) {4063 return await this.collection.getToken(this.tokenId, blockHashAt);4064 }40654066 async getOwner(blockHashAt?: string) {4067 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);4068 }40694070 async getTop10Owners() {4071 return await this.collection.getTop10TokenOwners(this.tokenId);4072 }40734074 async getTopmostOwner(blockHashAt?: string) {4075 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);4076 }40774078 async nest(signer: TSigner, toTokenObj: IToken) {4079 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);4080 }40814082 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {4083 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);4084 }40854086 async getBalance(addressObj: ICrossAccountId) {4087 return await this.collection.getTokenBalance(this.tokenId, addressObj);4088 }40894090 async getTotalPieces() {4091 return await this.collection.getTokenTotalPieces(this.tokenId);4092 }40934094 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {4095 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);4096 }40974098 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount = 1n) {4099 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);4100 }41014102 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {4103 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);4104 }41054106 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {4107 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);4108 }41094110 async repartition(signer: TSigner, amount: bigint) {4111 return await this.collection.repartitionToken(signer, this.tokenId, amount);4112 }41134114 async burn(signer: TSigner, amount = 1n) {4115 return await this.collection.burnToken(signer, this.tokenId, amount);4116 }41174118 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount = 1n) {4119 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);4120 }41214122 scheduleAt<T extends UniqueHelper>(4123 executionBlockNumber: number,4124 options: ISchedulerOptions = {},4125 ) {4126 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);4127 return new UniqueRFToken(this.tokenId, scheduledCollection);4128 }41294130 scheduleAfter<T extends UniqueHelper>(4131 blocksBeforeExecution: number,4132 options: ISchedulerOptions = {},4133 ) {4134 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);4135 return new UniqueRFToken(this.tokenId, scheduledCollection);4136 }41374138 getSudo<T extends UniqueHelper>() {4139 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());4140 }4141}