12345678import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {SignerOptions} from '@polkadot/api/types/submittable';10import '../../interfaces/augment-api';11import {AugmentedSubmittables} from '@polkadot/api-base/types/submittable';12import {ApiInterfaceEvents} from '@polkadot/api/types';13import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';14import {IKeyringPair} from '@polkadot/types/types';15import {hexToU8a} from '@polkadot/util/hex';16import {u8aConcat} from '@polkadot/util/u8a';17import {18 IApiListeners,19 IBlock,20 IEvent,21 IChainProperties,22 ICollectionCreationOptions,23 ICollectionLimits,24 ICollectionPermissions,25 ICrossAccountId,26 ICrossAccountIdLower,27 ILogger,28 INestingPermissions,29 IProperty,30 IStakingInfo,31 ISchedulerOptions,32 ISubstrateBalance,33 IToken,34 ITokenPropertyPermission,35 ITransactionResult,36 IUniqueHelperLog,37 TApiAllowedListeners,38 TEthereumAccount,39 TSigner,40 TSubstrateAccount,41 TNetworks,42 IForeignAssetMetadata,43 AcalaAssetMetadata,44 MoonbeamAssetInfo,45 DemocracyStandardAccountVote,46 IEthCrossAccountId,47} from './types';48import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';49import type {Vec} from '@polkadot/types-codec';50import {FrameSystemEventRecord, PalletBalancesIdAmount} from '@polkadot/types/lookup';5152export class CrossAccountId {53 Substrate!: TSubstrateAccount;54 Ethereum!: TEthereumAccount;5556 constructor(account: ICrossAccountId) {57 if ('Substrate' in account) this.Substrate = account.Substrate;58 else this.Ethereum = account.Ethereum;59 }6061 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {62 switch (domain) {63 case 'Substrate': return new CrossAccountId({Substrate: account.address});64 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();65 }66 }6768 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {69 if ('substrate' in address) return new CrossAccountId({Substrate: address.substrate});70 else return new CrossAccountId({Ethereum: address.ethereum});71 }7273 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {74 return encodeAddress(decodeAddress(address), ss58Format);75 }7677 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {78 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});79 }8081 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {82 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);83 return this;84 }8586 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {87 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));88 }8990 toEthereum(): CrossAccountId {91 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});92 return this;93 }9495 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {96 return evmToAddress(address, ss58Format);97 }9899 toSubstrate(ss58Format?: number): CrossAccountId {100 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});101 return this;102 }103104 toLowerCase(): CrossAccountId {105 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();106 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();107 return this;108 }109}110111const nesting = {112 toChecksumAddress(address: string): string {113 if (typeof address === 'undefined') return '';114115 if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);116117 address = address.toLowerCase().replace(/^0x/i, '');118 const addressHash = keccakAsHex(address).replace(/^0x/i, '');119 const checksumAddress = ['0x'];120121 for (let i = 0; i < address.length; i++) {122 123 if (parseInt(addressHash[i], 16) > 7) {124 checksumAddress.push(address[i].toUpperCase());125 } else {126 checksumAddress.push(address[i]);127 }128 }129 return checksumAddress.join('');130 },131 tokenIdToAddress(collectionId: number, tokenId: number) {132 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);133 },134};135136class UniqueUtil {137 static transactionStatus = {138 NOT_READY: 'NotReady',139 FAIL: 'Fail',140 SUCCESS: 'Success',141 };142143 static chainLogType = {144 EXTRINSIC: 'extrinsic',145 RPC: 'rpc',146 };147148 static getTokenAccount(token: IToken): CrossAccountId {149 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});150 }151152 static getTokenAddress(token: IToken): string {153 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);154 }155156 static getDefaultLogger(): ILogger {157 return {158 log(msg: any, level = 'INFO') {159 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));160 },161 level: {162 ERROR: 'ERROR',163 WARNING: 'WARNING',164 INFO: 'INFO',165 },166 };167 }168169 static vec2str(arr: string[] | number[]) {170 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');171 }172173 static str2vec(string: string) {174 if (typeof string !== 'string') return string;175 return Array.from(string).map(x => x.charCodeAt(0));176 }177178 static fromSeed(seed: string, ss58Format = 42) {179 const keyring = new Keyring({type: 'sr25519', ss58Format});180 return keyring.addFromUri(seed);181 }182183 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {184 if (creationResult.status !== this.transactionStatus.SUCCESS) {185 throw Error('Unable to create collection!');186 }187188 let collectionId = null;189 creationResult.result.events.forEach(({event: {data, method, section}}) => {190 if ((section === 'common') && (method === 'CollectionCreated')) {191 collectionId = parseInt(data[0].toString(), 10);192 }193 });194195 if (collectionId === null) {196 throw Error('No CollectionCreated event was found!');197 }198199 return collectionId;200 }201202 static extractTokensFromCreationResult(creationResult: ITransactionResult): {203 success: boolean,204 tokens: { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[],205 } {206 if (creationResult.status !== this.transactionStatus.SUCCESS) {207 throw Error('Unable to create tokens!');208 }209 let success = false;210 const tokens = [] as { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[];211 creationResult.result.events.forEach(({event: {data, method, section}}) => {212 if (method === 'ExtrinsicSuccess') {213 success = true;214 } else if ((section === 'common') && (method === 'ItemCreated')) {215 tokens.push({216 collectionId: parseInt(data[0].toString(), 10),217 tokenId: parseInt(data[1].toString(), 10),218 owner: data[2].toHuman(),219 amount: data[3].toBigInt(),220 });221 }222 });223 return {success, tokens};224 }225226 static extractTokensFromBurnResult(burnResult: ITransactionResult): {227 success: boolean,228 tokens: { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[],229 } {230 if (burnResult.status !== this.transactionStatus.SUCCESS) {231 throw Error('Unable to burn tokens!');232 }233 let success = false;234 const tokens = [] as { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[];235 burnResult.result.events.forEach(({event: {data, method, section}}) => {236 if (method === 'ExtrinsicSuccess') {237 success = true;238 } else if ((section === 'common') && (method === 'ItemDestroyed')) {239 tokens.push({240 collectionId: parseInt(data[0].toString(), 10),241 tokenId: parseInt(data[1].toString(), 10),242 owner: data[2].toHuman(),243 amount: data[3].toBigInt(),244 });245 }246 });247 return {success, tokens};248 }249250 static findCollectionInEvents(events: { event: IEvent }[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {251 let eventId = null;252 events.forEach(({event: {data, method, section}}) => {253 if ((section === expectedSection) && (method === expectedMethod)) {254 eventId = parseInt(data[0].toString(), 10);255 }256 });257258 if (eventId === null) {259 throw Error(`No ${expectedMethod} event was found!`);260 }261 return eventId === collectionId;262 }263264 static isTokenTransferSuccess(events: { event: IEvent }[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {265 const normalizeAddress = (address: string | ICrossAccountId) => {266 if (typeof address === 'string') return address;267 const obj = {} as any;268 Object.keys(address).forEach(k => {269 obj[k.toLocaleLowerCase()] = (address as any)[k];270 });271 if (obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);272 if (obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();273 return address;274 };275 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;276 events.forEach(({event: {data, method, section}}) => {277 if ((section === 'common') && (method === 'Transfer')) {278 const hData = (data as any).toJSON();279 transfer = {280 collectionId: hData[0],281 tokenId: hData[1],282 from: normalizeAddress(hData[2]),283 to: normalizeAddress(hData[3]),284 amount: BigInt(hData[4]),285 };286 }287 });288 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;289 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);290 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);291 isSuccess = isSuccess && amount === transfer.amount;292 return isSuccess;293 }294295 static bigIntToDecimals(number: bigint, decimals = 18) {296 const numberStr = number.toString();297 const dotPos = numberStr.length - decimals;298299 if (dotPos <= 0) {300 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;301 } else {302 const intPart = numberStr.substring(0, dotPos);303 const fractPart = numberStr.substring(dotPos);304 return intPart + '.' + fractPart;305 }306 }307}308309class UniqueEventHelper {310 private static extractIndex(index: any): [number, number] | string {311 if (index.toRawType() === '[u8;2]') return [index[0], index[1]];312 return index.toJSON();313 }314315 private static extractSub(data: any, subTypes: any): { [key: string]: any } {316 let obj: any = {};317 let index = 0;318319 if (data.entries) {320 for (const [key, value] of data.entries()) {321 obj[key] = this.extractData(value, subTypes[index]);322 index++;323 }324 } else obj = data.toJSON();325326 return obj;327 }328329 private static toHuman(data: any) {330 return data && data.toHuman ? data.toHuman() : `${data}`;331 }332333 private static extractData(data: any, type: any): any {334 if (!type) return this.toHuman(data);335 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();336 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();337 if (type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);338 return this.toHuman(data);339 }340341 public static extractEvents(events: { event: any, phase: any }[]): IEvent[] {342 const parsedEvents: IEvent[] = [];343344 events.forEach((record) => {345 const {event, phase} = record;346 const types = event.typeDef;347348 const eventData: IEvent = {349 section: event.section.toString(),350 method: event.method.toString(),351 index: this.extractIndex(event.index),352 data: [],353 phase: phase.toJSON(),354 };355356 event.data.forEach((val: any, index: number) => {357 eventData.data.push(this.extractData(val, types[index]));358 });359360 parsedEvents.push(eventData);361 });362363 return parsedEvents;364 }365}366const InvalidTypeSymbol = Symbol('Invalid type');367368export type Invalid<ErrorMessage> =369 | ((370 invalidType: typeof InvalidTypeSymbol,371 ..._: typeof InvalidTypeSymbol[]372 ) => typeof InvalidTypeSymbol)373 | null374 | undefined;375376type Get2<T, P extends string, E> =377 P extends `${infer Key}.${infer Key2}` ? Key extends keyof T ? Key2 extends keyof T[Key] ? T[Key][Key2] : E : E : E;378type ForceFunction<T> = T extends (...args: any) => any ? T : (...args: any) => Invalid<'not a function'>;379380export class ChainHelperBase {381 helperBase: any;382383 transactionStatus = UniqueUtil.transactionStatus;384 chainLogType = UniqueUtil.chainLogType;385 util: typeof UniqueUtil;386 eventHelper: typeof UniqueEventHelper;387 logger: ILogger;388 api: ApiPromise | null;389 forcedNetwork: TNetworks | null;390 network: TNetworks | null;391 wsEndpoint: string | null;392 chainLog: IUniqueHelperLog[];393 children: ChainHelperBase[];394 address: AddressGroup;395 chain: ChainGroup;396397 constructor(logger?: ILogger, helperBase?: any) {398 this.helperBase = helperBase;399400 this.util = UniqueUtil;401 this.eventHelper = UniqueEventHelper;402 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();403 this.logger = logger;404 this.api = null;405 this.forcedNetwork = null;406 this.network = null;407 this.wsEndpoint = null;408 this.chainLog = [];409 this.children = [];410 this.address = new AddressGroup(this);411 this.chain = new ChainGroup(this);412 }413414 clone(helperCls: ChainHelperBaseConstructor, options: { [key: string]: any } = {}) {415 Object.setPrototypeOf(helperCls.prototype, this);416 const newHelper = new helperCls(this.logger, options);417418 newHelper.api = this.api;419 newHelper.network = this.network;420 newHelper.forceNetwork = this.forceNetwork;421422 this.children.push(newHelper);423424 return newHelper;425 }426427 getEndpoint(): string {428 if (this.wsEndpoint === null) throw Error('No connection was established');429 return this.wsEndpoint;430 }431432 getApi(): ApiPromise {433 if (this.api === null) throw Error('API not initialized');434 return this.api;435 }436437 async subscribeEvents(expectedEvents: { section: string, names: string[] }[]) {438 const collectedEvents: IEvent[] = [];439 const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {440 const ievents = this.eventHelper.extractEvents(events);441 ievents.forEach((event) => {442 expectedEvents.forEach((e => {443 if (event.section === e.section && e.names.includes(event.method)) {444 collectedEvents.push(event);445 }446 }));447 });448 });449 return {unsubscribe: unsubscribe as any, collectedEvents};450 }451452 clearChainLog(): void {453 this.chainLog = [];454 }455456 forceNetwork(value: TNetworks): void {457 this.forcedNetwork = value;458 }459460 async connect(wsEndpoint: string, listeners?: IApiListeners) {461 if (this.api !== null) throw Error('Already connected');462 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);463 this.wsEndpoint = wsEndpoint;464 this.api = api;465 this.network = network;466 }467468 async disconnect() {469 for (const child of this.children) {470 child.clearApi();471 }472473 if (this.api === null) return;474 await this.api.disconnect();475 this.clearApi();476 }477478 clearApi() {479 this.api = null;480 this.network = null;481 }482483 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {484 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;485 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];486487 if (xcmChains.indexOf(spec.specName) > -1) return spec.specName;488489 if (['quartz', 'unique', 'sapphire'].indexOf(spec.specName) > -1) return spec.specName;490 return 'opal';491 }492493 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {494 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});495 await api.isReady;496497 const network = await this.detectNetwork(api);498499 await api.disconnect();500501 return network;502 }503504 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{505 api: ApiPromise;506 network: TNetworks;507 }> {508 if (typeof network === 'undefined' || network === null) network = 'opal';509 const supportedRPC = {510 opal: {511 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,512 },513 quartz: {514 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,515 },516 unique: {517 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,518 },519 rococo: {},520 westend: {},521 moonbeam: {},522 moonriver: {},523 acala: {},524 karura: {},525 westmint: {},526 };527 if (!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);528 const rpc = supportedRPC[network];529530 531 532533 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});534535 await api.isReadyOrError;536537 if (typeof listeners === 'undefined') listeners = {};538 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {539 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;540 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);541 }542543 return {api, network};544 }545546 getTransactionStatus(data: { events: { event: IEvent }[], status: any }) {547 const {events, status} = data;548 if (status.isReady) {549 return this.transactionStatus.NOT_READY;550 }551 if (status.isBroadcast) {552 return this.transactionStatus.NOT_READY;553 }554 if (status.isInBlock || status.isFinalized) {555 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');556 if (errors.length > 0) {557 return this.transactionStatus.FAIL;558 }559 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {560 return this.transactionStatus.SUCCESS;561 }562 }563564 return this.transactionStatus.FAIL;565 }566567 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {568 const sign = (callback: any) => {569 if (options !== null) return transaction.signAndSend(sender, options, callback);570 return transaction.signAndSend(sender, callback);571 };572 573 return new Promise(async (resolve, reject) => {574 try {575 const unsub = await sign((result: any) => {576 const status = this.getTransactionStatus(result);577578 if (status === this.transactionStatus.SUCCESS) {579 this.logger.log(`${label} successful`);580 unsub();581 resolve({result, status, blockHash: result.status.asInBlock.toHuman()});582 } else if (status === this.transactionStatus.FAIL) {583 let moduleError = null;584585 if (result.hasOwnProperty('dispatchError')) {586 const dispatchError = result['dispatchError'];587588 if (dispatchError) {589 if (dispatchError.isModule) {590 const modErr = dispatchError.asModule;591 const errorMeta = dispatchError.registry.findMetaError(modErr);592593 moduleError = `${errorMeta.section}.${errorMeta.name}`;594 } else {595 moduleError = dispatchError.toHuman();596 }597 } else {598 this.logger.log(result, this.logger.level.ERROR);599 }600 }601602 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);603 unsub();604 reject({status, moduleError, result});605 }606 });607 } catch (e) {608 this.logger.log(e, this.logger.level.ERROR);609 reject(e);610 }611 });612 }613614 async signTransactionWithoutSending(signer: TSigner, tx: any) {615 const api = this.getApi();616 const signingInfo = await api.derive.tx.signingInfo(signer.address);617618 tx.sign(signer, {619 blockHash: api.genesisHash,620 genesisHash: api.genesisHash,621 runtimeVersion: api.runtimeVersion,622 nonce: signingInfo.nonce,623 });624625 return tx.toHex();626 }627628 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {629 const api = this.getApi();630 const signingInfo = await api.derive.tx.signingInfo(signer.address);631632 633 634 tx.sign(signer, {635 blockHash: api.genesisHash,636 genesisHash: api.genesisHash,637 runtimeVersion: api.runtimeVersion,638 nonce: signingInfo.nonce,639 });640641 if (len === null) {642 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;643 } else {644 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;645 }646 }647648 constructApiCall(apiCall: string, params: any[]) {649 if (!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);650 let call = this.getApi() as any;651 for (const part of apiCall.slice(4).split('.')) {652 call = call[part];653 if (!call) {654 const advice = part.includes('_') ? ' Looks like it needs to be converted to camel case.' : '';655 throw Error(`Function ${part} of api call ${apiCall} not found.${advice}`);656 }657 }658 return call(...params);659 }660661 encodeApiCall(apiCall: string, params: any[]) {662 return this.constructApiCall(apiCall, params).method.toHex();663 }664665 async executeExtrinsic<666 E extends string,667 V extends (668 ...args: any) => any = ForceFunction<669 Get2<670 AugmentedSubmittables<'promise'>,671 E, (...args: any) => Invalid<'not found'>672 >673 >674 >(675 sender: TSigner,676 extrinsic: `api.tx.${E}`,677 params: Parameters<V>,678 expectSuccess = true,679 options: Partial<SignerOptions> | null = null,680 ): Promise<ITransactionResult> {681 if (this.api === null) throw Error('API not initialized');682 if (!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);683684 const startTime = (new Date()).getTime();685 let result: ITransactionResult;686 let events: IEvent[] = [];687 try {688 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;689 events = this.eventHelper.extractEvents(result.result.events);690 const errorEvent = events.find((event) => event.method == 'ExecutedFailed' || event.method == 'CreatedFailed');691 if (errorEvent)692 throw Error(errorEvent.method + ': ' + extrinsic);693 }694 catch (e) {695 if (!(e as object).hasOwnProperty('status')) throw e;696 result = e as ITransactionResult;697 }698699 const endTime = (new Date()).getTime();700701 const log = {702 executedAt: endTime,703 executionTime: endTime - startTime,704 type: this.chainLogType.EXTRINSIC,705 status: result.status,706 call: extrinsic,707 signer: this.getSignerAddress(sender),708 params,709 } as IUniqueHelperLog;710711 let errorMessage = '';712713 if (result.status !== this.transactionStatus.SUCCESS) {714 if (result.moduleError) {715 errorMessage = typeof result.moduleError === 'string'716 ? result.moduleError717 : `${Object.keys(result.moduleError)[0]}: ${Object.values(result.moduleError)[0]}`;718 log.moduleError = errorMessage;719 }720 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;721 }722 if (events.length > 0) log.events = events;723724 this.chainLog.push(log);725726 if (expectSuccess && result.status !== this.transactionStatus.SUCCESS) {727 if (result.moduleError) throw Error(`${errorMessage}`);728 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));729 }730 return result as any;731 }732733 async callRpc734 735 736 737 738 739 740 741 742 743 744 745 (rpc: string, params?: any[]): Promise<any> {746747 if (typeof params === 'undefined') params = [] as any;748 if (this.api === null) throw Error('API not initialized');749 if (!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);750751 const startTime = (new Date()).getTime();752 let result;753 let error = null;754 const log = {755 type: this.chainLogType.RPC,756 call: rpc,757 params,758 } as any as IUniqueHelperLog;759760 try {761 result = await this.constructApiCall(rpc, params as any);762 }763 catch (e) {764 error = e;765 }766767 const endTime = (new Date()).getTime();768769 log.executedAt = endTime;770 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';771 log.executionTime = endTime - startTime;772773 this.chainLog.push(log);774775 if (error !== null) throw error;776777 return result;778 }779780 getSignerAddress(signer: IKeyringPair | string): string {781 if (typeof signer === 'string') return signer;782 return signer.address;783 }784785 fetchAllPalletNames(): string[] {786 if (this.api === null) throw Error('API not initialized');787 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase()).sort();788 }789790 fetchMissingPalletNames(requiredPallets: readonly string[]): string[] {791 const palletNames = this.fetchAllPalletNames();792 return requiredPallets.filter(p => !palletNames.includes(p));793 }794}795796797class HelperGroup<T extends ChainHelperBase> {798 helper: T;799800 constructor(uniqueHelper: T) {801 this.helper = uniqueHelper;802 }803}804805806class CollectionGroup extends HelperGroup<UniqueHelper> {807 808809810811812813814815816 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {817 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();818 }819820 821822823824825 async getTotalCount(): Promise<number> {826 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();827 }828829 830831832833834835836837838 async getData(collectionId: number): Promise<{839 id: number;840 name: string;841 description: string;842 tokensCount: number;843 admins: CrossAccountId[];844 normalizedOwner: TSubstrateAccount;845 raw: any846 } | null> {847 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);848 const humanCollection = collection.toHuman(), collectionData = {849 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],850 raw: humanCollection,851 } as any, jsonCollection = collection.toJSON();852 if (humanCollection === null) return null;853 collectionData.raw.limits = jsonCollection.limits;854 collectionData.raw.permissions = jsonCollection.permissions;855 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);856 for (const key of ['name', 'description']) {857 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);858 }859860 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))861 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)862 : 0;863 collectionData.admins = await this.getAdmins(collectionId);864865 return collectionData;866 }867868 869870871872873874875876 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {877 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();878879 return normalize880 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())881 : admins;882 }883884 885886887888889890891 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {892 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();893 return normalize894 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())895 : allowListed;896 }897898 899900901902903904905 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {906 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();907 }908909 910911912913914915916917 async burn(signer: TSigner, collectionId: number): Promise<boolean> {918 const result = await this.helper.executeExtrinsic(919 signer,920 'api.tx.unique.destroyCollection', [collectionId],921 true,922 );923924 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');925 }926927 928929930931932933934935936 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {937 const result = await this.helper.executeExtrinsic(938 signer,939 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],940 true,941 );942943 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');944 }945946 947948949950951952953954 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {955 const result = await this.helper.executeExtrinsic(956 signer,957 'api.tx.unique.confirmSponsorship', [collectionId],958 true,959 );960961 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');962 }963964 965966967968969970971972 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {973 const result = await this.helper.executeExtrinsic(974 signer,975 'api.tx.unique.removeCollectionSponsor', [collectionId],976 true,977 );978979 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');980 }981982 983984985986987988989990991992993994995996997998999 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {1000 const result = await this.helper.executeExtrinsic(1001 signer,1002 'api.tx.unique.setCollectionLimits', [collectionId, limits],1003 true,1004 );10051006 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');1007 }10081009 101010111012101310141015101610171018 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {1019 const result = await this.helper.executeExtrinsic(1020 signer,1021 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],1022 true,1023 );10241025 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');1026 }10271028 102910301031103210331034103510361037 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1038 const result = await this.helper.executeExtrinsic(1039 signer,1040 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],1041 true,1042 );10431044 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');1045 }10461047 104810491050105110521053105410551056 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1057 const result = await this.helper.executeExtrinsic(1058 signer,1059 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],1060 true,1061 );10621063 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');1064 }10651066 10671068106910701071107210731074 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {1075 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();1076 }10771078 1079108010811082108310841085 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1086 const result = await this.helper.executeExtrinsic(1087 signer,1088 'api.tx.unique.addToAllowList', [collectionId, addressObj],1089 true,1090 );10911092 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1093 }10941095 10961097109810991100110111021103 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1104 const result = await this.helper.executeExtrinsic(1105 signer,1106 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1107 true,1108 );11091110 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1111 }11121113 111411151116111711181119112011211122 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1123 const result = await this.helper.executeExtrinsic(1124 signer,1125 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1126 true,1127 );11281129 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1130 }11311132 113311341135113611371138113911401141 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1142 return await this.setPermissions(signer, collectionId, {nesting: permissions});1143 }11441145 11461147114811491150115111521153 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1154 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1155 }11561157 115811591160116111621163116411651166 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1167 const result = await this.helper.executeExtrinsic(1168 signer,1169 'api.tx.unique.setCollectionProperties', [collectionId, properties],1170 true,1171 );11721173 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1174 }11751176 11771178117911801181118211831184 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1185 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1186 }11871188 async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1189 const api = this.helper.getApi();1190 const props = (await api.query.common.collectionProperties(collectionId)).toJSON();11911192 return (props! as any).consumedSpace;1193 }11941195 async getCollectionOptions(collectionId: number) {1196 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1197 }11981199 120012011202120312041205120612071208 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1209 const result = await this.helper.executeExtrinsic(1210 signer,1211 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1212 true,1213 );12141215 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1216 }12171218 12191220122112221223122412251226122712281229 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1230 const result = await this.helper.executeExtrinsic(1231 signer,1232 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1233 true, 1234 );12351236 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1237 }12381239 1240124112421243124412451246124712481249125012511252 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1253 const result = await this.helper.executeExtrinsic(1254 signer,1255 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1256 true, 1257 );1258 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1259 }12601261 12621263126412651266126712681269127012711272 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount = 1n): Promise<boolean> {1273 const burnResult = await this.helper.executeExtrinsic(1274 signer,1275 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1276 true, 1277 );1278 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1279 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1280 return burnedTokens.success;1281 }12821283 12841285128612871288128912901291129212931294 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1295 const burnResult = await this.helper.executeExtrinsic(1296 signer,1297 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1298 true, 1299 );1300 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1301 return burnedTokens.success && burnedTokens.tokens.length > 0;1302 }13031304 1305130613071308130913101311131213131314 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1315 const approveResult = await this.helper.executeExtrinsic(1316 signer,1317 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1318 true, 1319 );13201321 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1322 }13231324 13251326132713281329133013311332133313341335 async approveTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {1336 const approveResult = await this.helper.executeExtrinsic(1337 signer,1338 'api.tx.unique.approveFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1339 true, 1340 );13411342 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1343 }13441345 1346134713481349135013511352135313541355 async approveTokenFromEth(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1356 const ethMirror = CrossAccountId.fromKeyring(signer).toEthereum();1357 return await this.approveTokenFrom(signer, collectionId, tokenId, ethMirror, toAddressObj, amount);1358 }13591360 1361136213631364136513661367136813691370 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1371 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1372 }13731374 1375137613771378137913801381 async getLastTokenId(collectionId: number): Promise<number> {1382 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1383 }13841385 13861387138813891390139113921393 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1394 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1395 }1396}13971398class NFTnRFT extends CollectionGroup {1399 14001401140214031404140514061407 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1408 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1409 }14101411 1412141314141415141614171418141914201421 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1422 properties: IProperty[];1423 owner: CrossAccountId;1424 normalizedOwner: CrossAccountId;1425 } | null> {1426 let tokenData;1427 if (typeof blockHashAt === 'undefined') {1428 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1429 }1430 else {1431 if (propertyKeys.length == 0) {1432 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1433 if (!collection) return null;1434 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1435 }1436 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1437 }1438 tokenData = tokenData.toHuman();1439 if (tokenData === null || tokenData.owner === null) return null;1440 const owner = {} as any;1441 for (const key of Object.keys(tokenData.owner)) {1442 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1443 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1444 : tokenData.owner[key];1445 }1446 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1447 return tokenData;1448 }14491450 14511452145314541455145614571458 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1459 let owner;1460 if (typeof blockHashAt === 'undefined') {1461 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1462 } else {1463 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1464 }1465 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1466 }14671468 14691470147114721473147414751476 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1477 let owner;1478 if (typeof blockHashAt === 'undefined') {1479 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1480 } else {1481 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1482 }14831484 if (owner === null) return null;14851486 return owner.toHuman();1487 }14881489 14901491149214931494149514961497 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1498 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1499 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1500 if (!result) {1501 throw Error('Unable to nest token!');1502 }1503 return result;1504 }15051506 150715081509151015111512151315141515 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1516 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1517 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1518 if (!result) {1519 throw Error('Unable to unnest token!');1520 }1521 return result;1522 }15231524 15251526152715281529153015311532153315341535 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1536 const result = await this.helper.executeExtrinsic(1537 signer,1538 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1539 true,1540 );15411542 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1543 }15441545 15461547154815491550155115521553 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1554 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1555 }15561557 1558155915601561156215631564156515661567 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1568 const result = await this.helper.executeExtrinsic(1569 signer,1570 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1571 true,1572 );15731574 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1575 }15761577 157815791580158115821583158415851586 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1587 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1588 }15891590 159115921593159415951596159715981599 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1600 const result = await this.helper.executeExtrinsic(1601 signer,1602 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1603 true,1604 );16051606 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1607 }16081609 161016111612161316141615161616171618 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1619 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1620 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1621 for (const key of ['name', 'description', 'tokenPrefix']) {1622 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);1623 }1624 const creationResult = await this.helper.executeExtrinsic(1625 signer,1626 'api.tx.unique.createCollectionEx', [collectionOptions],1627 true, 1628 );1629 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1630 }16311632 getCollectionObject(_collectionId: number): any {1633 return null;1634 }16351636 getTokenObject(_collectionId: number, _tokenId: number): any {1637 return null;1638 }16391640 1641164216431644164516461647 async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1648 return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1649 }16501651 165216531654165516561657 async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1658 const result = await this.helper.executeExtrinsic(1659 signer,1660 'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1661 true,1662 );1663 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1664 }1665}166616671668class NFTGroup extends NFTnRFT {1669 167016711672167316741675 getCollectionObject(collectionId: number): UniqueNFTCollection {1676 return new UniqueNFTCollection(collectionId, this.helper);1677 }16781679 1680168116821683168416851686 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1687 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1688 }16891690 1691169216931694169516961697 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1698 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1699 }17001701 1702170317041705170617071708170917101711 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1712 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1713 }17141715 171617171718171917201721172217231724172517261727 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1728 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1729 }17301731 17321733173417351736173717381739 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1740 let children;1741 if (typeof blockHashAt === 'undefined') {1742 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1743 } else {1744 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1745 }17461747 return children.toJSON().map((x: any) => ({collectionId: x.collection, tokenId: x.token}));1748 }17491750 175117521753175417551756175717581759176017611762 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1763 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1764 }17651766 176717681769177017711772 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1773 const creationResult = await this.helper.executeExtrinsic(1774 signer,1775 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1776 NFT: {1777 properties: data.properties,1778 },1779 }],1780 true,1781 );1782 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1783 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1784 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1785 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1786 }17871788 178917901791179217931794179517961797179817991800180118021803 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: { owner: ICrossAccountId, properties?: IProperty[] }[]): Promise<UniqueNFToken[]> {1804 const creationResult = await this.helper.executeExtrinsic(1805 signer,1806 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1807 true,1808 );1809 const collection = this.getCollectionObject(collectionId);1810 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1811 }18121813 181418151816181718181819182018211822182318241825182618271828182918301831 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: { properties?: IProperty[] }[]): Promise<UniqueNFToken[]> {1832 const rawTokens = [];1833 for (const token of tokens) {1834 const raw = {NFT: {properties: token.properties}};1835 rawTokens.push(raw);1836 }1837 const creationResult = await this.helper.executeExtrinsic(1838 signer,1839 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1840 true,1841 );1842 const collection = this.getCollectionObject(collectionId);1843 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1844 }18451846 1847184818491850185118521853185418551856 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1857 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1858 }1859}186018611862class RFTGroup extends NFTnRFT {1863 186418651866186718681869 getCollectionObject(collectionId: number): UniqueRFTCollection {1870 return new UniqueRFTCollection(collectionId, this.helper);1871 }18721873 1874187518761877187818791880 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1881 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1882 }18831884 1885188618871888188918901891 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1892 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1893 }18941895 18961897189818991900190119021903 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1904 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1905 }19061907 1908190919101911191219131914191519161917 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1918 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1919 }19201921 19221923192419251926192719281929193019311932 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1933 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1934 }19351936 193719381939194019411942194319441945194619471948 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1949 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1950 }19511952 1953195419551956195719581959 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1960 const creationResult = await this.helper.executeExtrinsic(1961 signer,1962 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1963 ReFungible: {1964 pieces: data.pieces,1965 properties: data.properties,1966 },1967 }],1968 true,1969 );1970 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1971 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1972 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1973 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1974 }19751976 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: { owner: ICrossAccountId, pieces: bigint, properties?: IProperty[] }[]): Promise<UniqueRFToken[]> {1977 throw Error('Not implemented');1978 const creationResult = await this.helper.executeExtrinsic(1979 signer,1980 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1981 true, 1982 );1983 const collection = this.getCollectionObject(collectionId);1984 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1985 }19861987 198819891990199119921993199419951996 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: { pieces: bigint, properties?: IProperty[] }[]): Promise<UniqueRFToken[]> {1997 const rawTokens = [];1998 for (const token of tokens) {1999 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};2000 rawTokens.push(raw);2001 }2002 const creationResult = await this.helper.executeExtrinsic(2003 signer,2004 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2005 true,2006 );2007 const collection = this.getCollectionObject(collectionId);2008 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));2009 }20102011 201220132014201520162017201820192020 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount = 1n): Promise<boolean> {2021 return await super.burnToken(signer, collectionId, tokenId, amount);2022 }20232024 2025202620272028202920302031203220332034 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {2035 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);2036 }20372038 20392040204120422043204420452046204720482049 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {2050 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);2051 }20522053 2054205520562057205820592060 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {2061 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();2062 }20632064 206520662067206820692070207120722073 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {2074 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);2075 const repartitionResult = await this.helper.executeExtrinsic(2076 signer,2077 'api.tx.unique.repartition', [collectionId, tokenId, amount],2078 true,2079 );2080 if (currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');2081 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');2082 }2083}208420852086class FTGroup extends CollectionGroup {2087 208820892090209120922093 getCollectionObject(collectionId: number): UniqueFTCollection {2094 return new UniqueFTCollection(collectionId, this.helper);2095 }20962097 2098209921002101210221032104210521062107210821092110 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {2111 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 2112 if (collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');2113 collectionOptions.mode = {fungible: decimalPoints};2114 for (const key of ['name', 'description', 'tokenPrefix']) {2115 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);2116 }2117 const creationResult = await this.helper.executeExtrinsic(2118 signer,2119 'api.tx.unique.createCollectionEx', [collectionOptions],2120 true,2121 );2122 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2123 }21242125 212621272128212921302131213221332134 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2135 const creationResult = await this.helper.executeExtrinsic(2136 signer,2137 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2138 Fungible: {2139 value: amount,2140 },2141 }],2142 true, 2143 );2144 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2145 }21462147 21482149215021512152215321542155 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: { value: bigint }[], owner: ICrossAccountId): Promise<boolean> {2156 const rawTokens = [];2157 for (const token of tokens) {2158 const raw = {Fungible: {Value: token.value}};2159 rawTokens.push(raw);2160 }2161 const creationResult = await this.helper.executeExtrinsic(2162 signer,2163 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2164 true,2165 );2166 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2167 }21682169 217021712172217321742175 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2176 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2177 }21782179 2180218121822183218421852186 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2187 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2188 }21892190 219121922193219421952196219721982199 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount = 1n) {2200 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2201 }22022203 2204220522062207220822092210221122122213 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {2214 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2215 }22162217 22182219222022212222222322242225 async burnTokens(signer: IKeyringPair, collectionId: number, amount = 1n): Promise<boolean> {2226 return await super.burnToken(signer, collectionId, 0, amount);2227 }22282229 223022312232223322342235223622372238 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {2239 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2240 }22412242 22432244224522462247 async getTotalPieces(collectionId: number): Promise<bigint> {2248 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2249 }22502251 2252225322542255225622572258225922602261 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount = 1n) {2262 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2263 }22642265 2266226722682269227022712272 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2273 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2274 }2275}227622772278class ChainGroup extends HelperGroup<ChainHelperBase> {2279 22802281228222832284 getChainProperties(): IChainProperties {2285 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2286 return {2287 ss58Format: properties.ss58Format.toJSON(),2288 tokenDecimals: properties.tokenDecimals.toJSON(),2289 tokenSymbol: properties.tokenSymbol.toJSON(),2290 };2291 }22922293 22942295229622972298 async getLatestBlockNumber(): Promise<number> {2299 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2300 }23012302 230323042305230623072308 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2309 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2310 if (blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2311 return blockHash;2312 }23132314 2315 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2316 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2317 if (!blockHash) return null;2318 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2319 }23202321 2322232323242325 async getRelayBlockNumber(): Promise<bigint> {2326 const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2327 return BigInt(blockNumber);2328 }23292330 233123322333233423352336 async getNonce(address: TSubstrateAccount): Promise<number> {2337 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2338 }2339}23402341class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2342 234323442345234623472348 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2349 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2350 }23512352 23532354235523562357235823592360 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2361 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);23622363 let transfer = {from: null, to: null, amount: 0n} as any;2364 result.result.events.forEach(({event: {data, method, section}}) => {2365 if ((section === 'balances') && (method === 'Transfer')) {2366 transfer = {2367 from: this.helper.address.normalizeSubstrate(data[0]),2368 to: this.helper.address.normalizeSubstrate(data[1]),2369 amount: BigInt(data[2]),2370 };2371 }2372 });2373 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2374 && this.helper.address.normalizeSubstrate(address) === transfer.to2375 && BigInt(amount) === transfer.amount;2376 return isSuccess;2377 }23782379 23802381238223832384 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2385 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2386 return {free: accountInfo.free.toBigInt(), frozen: accountInfo.frozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2387 }23882389 2390239123922393 async getTotalIssuance(): Promise<bigint> {2394 const total = (await this.helper.callRpc('api.query.balances.totalIssuance', []));2395 return total.toBigInt();2396 }23972398 async getLocked(address: TSubstrateAccount): Promise<[{ id: string, amount: bigint, reason: string }]> {2399 const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2400 return locks.map((lock: any) => ({id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons}));2401 }2402 async getFrozen(address: TSubstrateAccount): Promise<{ id: string, amount: bigint }[]> {2403 const locks = await this.helper.api!.query.balances.freezes(address);2404 return locks.map(lock => ({id: lock.id.toString(), amount: lock.amount.toBigInt()}));2405 }2406}24072408class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2409 241024112412241324142415 async getEthereum(address: TEthereumAccount): Promise<bigint> {2416 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2417 }24182419 24202421242224232424242524262427 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2428 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);24292430 let transfer = {from: null, to: null, amount: 0n} as any;2431 result.result.events.forEach(({event: {data, method, section}}) => {2432 if ((section === 'balances') && (method === 'Transfer')) {2433 transfer = {2434 from: data[0].toString(),2435 to: data[1].toString(),2436 amount: BigInt(data[2]),2437 };2438 }2439 });2440 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2441 && address === transfer.to2442 && BigInt(amount) === transfer.amount;2443 return isSuccess;2444 }2445}24462447class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2448 subBalanceGroup: SubstrateBalanceGroup<T>;2449 ethBalanceGroup: EthereumBalanceGroup<T>;24502451 constructor(helper: T) {2452 super(helper);2453 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2454 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2455 }24562457 getCollectionCreationPrice(): bigint {2458 return 2n * this.getOneTokenNominal();2459 }2460 24612462246324642465 getOneTokenNominal(): bigint {2466 const chainProperties = this.helper.chain.getChainProperties();2467 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2468 }24692470 247124722473247424752476 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2477 return this.subBalanceGroup.getSubstrate(address);2478 }24792480 24812482248324842485 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2486 return this.subBalanceGroup.getSubstrateFull(address);2487 }24882489 2490249124922493 getTotalIssuance(): Promise<bigint> {2494 return this.subBalanceGroup.getTotalIssuance();2495 }24962497 249824992500250125022503 getLocked(address: TSubstrateAccount) {2504 return this.subBalanceGroup.getLocked(address);2505 }25062507 25082509251025112512 getFrozen(address: TSubstrateAccount) {2513 return this.subBalanceGroup.getFrozen(address);2514 }25152516 251725182519252025212522 getEthereum(address: TEthereumAccount): Promise<bigint> {2523 return this.ethBalanceGroup.getEthereum(address);2524 }25252526 async setBalanceSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint, reservedAmount = 0n) {2527 await this.helper.executeExtrinsic(signer, 'api.tx.balances.setBalance', [address, amount, reservedAmount], true);2528 }25292530 25312532253325342535253625372538 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2539 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2540 }25412542 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2543 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);25442545 let transfer = {from: null, to: null, amount: 0n} as any;2546 result.result.events.forEach(({event: {data, method, section}}) => {2547 if ((section === 'balances') && (method === 'Transfer')) {2548 transfer = {2549 from: this.helper.address.normalizeSubstrate(data[0]),2550 to: this.helper.address.normalizeSubstrate(data[1]),2551 amount: BigInt(data[2]),2552 };2553 }2554 });2555 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2556 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2557 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2558 return isSuccess;2559 }25602561 2562256325642565256625672568 async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: { start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint }): Promise<void> {2569 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2570 const event = result.result.events2571 .find(e => e.event.section === 'vesting' &&2572 e.event.method === 'VestingScheduleAdded' &&2573 e.event.data[0].toHuman() === signer.address);2574 if (!event) throw Error('Cannot find transfer in events');2575 }25762577 25782579258025812582 async getVestingSchedules(address: TSubstrateAccount): Promise<{ start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint }[]> {2583 const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2584 return schedule.map((schedule: any) => {2585 return {2586 start: BigInt(schedule.start),2587 period: BigInt(schedule.period),2588 periodCount: BigInt(schedule.periodCount),2589 perPeriod: BigInt(schedule.perPeriod),2590 };2591 });2592 }25932594 2595259625972598 async claim(signer: TSigner) {2599 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2600 const event = result.result.events2601 .find(e => e.event.section === 'vesting' &&2602 e.event.method === 'Claimed' &&2603 e.event.data[0].toHuman() === signer.address);2604 if (!event) throw Error('Cannot find claim in events');2605 }2606}26072608class AddressGroup extends HelperGroup<ChainHelperBase> {2609 2610261126122613261426152616 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2617 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2618 }26192620 262126222623262426252626 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2627 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2628 }26292630 2631263226332634263526362637 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat = false): TSubstrateAccount {2638 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2639 }26402641 264226432644264526462647 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2648 return CrossAccountId.translateSubToEth(subAddress);2649 }26502651 265226532654265526562657 encodeSubstrateAddress(key: Uint8Array | string | bigint, ss58Format = 42): string {2658 const u8a: Uint8Array = typeof key === 'string'2659 ? hexToU8a(key)2660 : typeof key === 'bigint'2661 ? hexToU8a(key.toString(16))2662 : key;26632664 if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2665 throw new Error(`ss58Format is not valid, received ${typeof ss58Format} "${ss58Format}"`);2666 }26672668 const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2669 if (!allowedDecodedLengths.includes(u8a.length)) {2670 throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2671 }26722673 const u8aPrefix = ss58Format < 642674 ? new Uint8Array([ss58Format])2675 : new Uint8Array([2676 ((ss58Format & 0xfc) >> 2) | 0x40,2677 (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2678 ]);26792680 const input = u8aConcat(u8aPrefix, u8a);26812682 return base58Encode(u8aConcat(2683 input,2684 blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2685 ));2686 }26872688 26892690269126922693 restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2694 if (this.helper.api === null) {2695 throw 'Not connected';2696 }2697 const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2698 if (res === undefined || res === null) {2699 throw 'Restore address error';2700 }2701 return res.toString();2702 }27032704 27052706270727082709 convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2710 if (ethCrossAccount.sub === '0') {2711 return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2712 }27132714 const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2715 return {Substrate: ss58};2716 }27172718 paraSiblingSovereignAccount(paraid: number) {2719 2720 2721 const siblingPrefix = '0x7369626c';27222723 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2724 const suffix = '000000000000000000000000000000000000000000000000';27252726 return siblingPrefix + encodedParaId + suffix;2727 }2728}27292730class StakingGroup extends HelperGroup<UniqueHelper> {2731 2732273327342735273627372738 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2739 if (typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2740 const _stakeResult = await this.helper.executeExtrinsic(2741 signer, 'api.tx.appPromotion.stake',2742 [amountToStake], true,2743 );2744 2745 return true;2746 }27472748 2749275027512752275327542755 async unstakeAll(signer: TSigner, label?: string): Promise<string> {2756 if (typeof label === 'undefined') label = `${signer.address}`;2757 const unstakeResult = await this.helper.executeExtrinsic(2758 signer, 'api.tx.appPromotion.unstakeAll',2759 [], true,2760 );2761 return unstakeResult.blockHash;2762 }27632764 2765276627672768276927702771 async unstakePartial(signer: TSigner, amount: bigint, label?: string): Promise<string> {2772 if (typeof label === 'undefined') label = `${signer.address}`;2773 const unstakeResult = await this.helper.executeExtrinsic(2774 signer, 'api.tx.appPromotion.unstakePartial',2775 [amount], true,2776 );2777 return unstakeResult.blockHash;2778 }27792780 27812782278327842785 async getStakesNumber(address: ICrossAccountId): Promise<number> {2786 if ('Ethereum' in address) throw Error('only substrate address');2787 return (await this.helper.callRpc('api.query.appPromotion.stakesPerAccount', [address.Substrate])).toNumber();2788 }27892790 27912792279327942795 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2796 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2797 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2798 }27992800 28012802280328042805 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2806 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2807 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2808 return {2809 block: block.toBigInt(),2810 amount: amount.toBigInt(),2811 };2812 });2813 }28142815 28162817281828192820 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2821 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2822 }28232824 28252826282728282829 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2830 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2831 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2832 return {2833 block: block.toBigInt(),2834 amount: amount.toBigInt(),2835 };2836 });2837 return result;2838 }2839}28402841class SchedulerGroup extends HelperGroup<UniqueHelper> {2842 constructor(helper: UniqueHelper) {2843 super(helper);2844 }28452846 cancelScheduled(signer: TSigner, scheduledId: string) {2847 return this.helper.executeExtrinsic(2848 signer,2849 'api.tx.scheduler.cancelNamed',2850 [scheduledId],2851 true,2852 );2853 }28542855 changePriority(signer: TSigner, scheduledId: string, priority: number) {2856 return this.helper.executeExtrinsic(2857 signer,2858 'api.tx.scheduler.changeNamedPriority',2859 [scheduledId, priority],2860 true,2861 );2862 }28632864 scheduleAt<T extends UniqueHelper>(2865 executionBlockNumber: number,2866 options: ISchedulerOptions = {},2867 ) {2868 return this.schedule<T>('schedule', executionBlockNumber, options);2869 }28702871 scheduleAfter<T extends UniqueHelper>(2872 blocksBeforeExecution: number,2873 options: ISchedulerOptions = {},2874 ) {2875 return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2876 }28772878 schedule<T extends UniqueHelper>(2879 scheduleFn: 'schedule' | 'scheduleAfter',2880 blocksNum: number,2881 options: ISchedulerOptions = {},2882 ) {2883 2884 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2885 return this.helper.clone(ScheduledHelperType, {2886 scheduleFn,2887 blocksNum,2888 options,2889 }) as T;2890 }2891}28922893class CollatorSelectionGroup extends HelperGroup<UniqueHelper> {2894 2895 addInvulnerable(signer: TSigner, address: string) {2896 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.addInvulnerable', [address]);2897 }28982899 removeInvulnerable(signer: TSigner, address: string) {2900 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.removeInvulnerable', [address]);2901 }29022903 async getInvulnerables(): Promise<string[]> {2904 return (await this.helper.callRpc('api.query.collatorSelection.invulnerables')).map((x: any) => x.toHuman());2905 }29062907 2908 maxCollators(): number {2909 return (this.helper.getApi().consts.configuration.defaultCollatorSelectionMaxCollators.toJSON() as number);2910 }29112912 async getDesiredCollators(): Promise<number> {2913 return (await this.helper.callRpc('api.query.configuration.collatorSelectionDesiredCollatorsOverride')).toNumber();2914 }29152916 setLicenseBond(signer: TSigner, amount: bigint) {2917 return this.helper.executeExtrinsic(signer, 'api.tx.configuration.setCollatorSelectionLicenseBond', [amount]);2918 }29192920 async getLicenseBond(): Promise<bigint> {2921 return (await this.helper.callRpc('api.query.configuration.collatorSelectionLicenseBondOverride')).toBigInt();2922 }29232924 obtainLicense(signer: TSigner) {2925 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.getLicense', []);2926 }29272928 releaseLicense(signer: TSigner) {2929 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.releaseLicense', []);2930 }29312932 forceReleaseLicense(signer: TSigner, released: string) {2933 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.forceReleaseLicense', [released]);2934 }29352936 async hasLicense(address: string): Promise<bigint> {2937 return (await this.helper.callRpc('api.query.collatorSelection.licenseDepositOf', [address])).toBigInt();2938 }29392940 onboard(signer: TSigner) {2941 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.onboard', []);2942 }29432944 offboard(signer: TSigner) {2945 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.offboard', []);2946 }29472948 async getCandidates(): Promise<string[]> {2949 return (await this.helper.callRpc('api.query.collatorSelection.candidates')).map((x: any) => x.toHuman());2950 }2951}29522953class PreimageGroup extends HelperGroup<UniqueHelper> {2954 async getPreimageInfo(h256: string) {2955 return (await this.helper.callRpc('api.query.preimage.statusFor', [h256])).toJSON();2956 }29572958 295929602961296229632964296529662967 notePreimage(signer: TSigner, bytes: string | Uint8Array) {2968 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.notePreimage', [bytes]);2969 }29702971 297229732974297529762977 unnotePreimage(signer: TSigner, h256: string) {2978 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unnotePreimage', [h256]);2979 }29802981 298229832984298529862987 requestPreimage(signer: TSigner, h256: string) {2988 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.requestPreimage', [h256]);2989 }29902991 299229932994299529962997 unrequestPreimage(signer: TSigner, h256: string) {2998 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unrequestPreimage', [h256]);2999 }3000}30013002class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {3003 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {3004 await this.helper.executeExtrinsic(3005 signer,3006 'api.tx.foreignAssets.registerForeignAsset',3007 [ownerAddress, location, metadata],3008 true,3009 );3010 }30113012 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {3013 await this.helper.executeExtrinsic(3014 signer,3015 'api.tx.foreignAssets.updateForeignAsset',3016 [foreignAssetId, location, metadata],3017 true,3018 );3019 }3020}30213022class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {3023 palletName: string;30243025 constructor(helper: T, palletName: string) {3026 super(helper);30273028 this.palletName = palletName;3029 }30303031 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {3032 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);3033 }30343035 async setSafeXcmVersion(signer: TSigner, version: number) {3036 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.forceDefaultXcmVersion`, [version], true);3037 }30383039 async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {3040 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);3041 }30423043 async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint, xcmVersion = 3) {3044 const destinationContent = {3045 parents: 0,3046 interior: {3047 X1: {3048 Parachain: destinationParaId,3049 },3050 },3051 };30523053 const beneficiaryContent = {3054 parents: 0,3055 interior: {3056 X1: {3057 AccountId32: {3058 network: 'Any',3059 id: targetAccount,3060 },3061 },3062 },3063 };30643065 const assetsContent = [3066 {3067 id: {3068 Concrete: {3069 parents: 0,3070 interior: 'Here',3071 },3072 },3073 fun: {3074 Fungible: amount,3075 },3076 },3077 ];30783079 let destination;3080 let beneficiary;3081 let assets;30823083 if (xcmVersion == 2) {3084 destination = {V1: destinationContent};3085 beneficiary = {V1: beneficiaryContent};3086 assets = {V1: assetsContent};30873088 } else if (xcmVersion == 3) {3089 destination = {V2: destinationContent};3090 beneficiary = {V2: beneficiaryContent};3091 assets = {V2: assetsContent};30923093 } else {3094 throw Error('Unknown XCM version: ' + xcmVersion);3095 }30963097 const feeAssetItem = 0;30983099 await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);3100 }31013102 async send(signer: IKeyringPair, destination: any, message: any) {3103 await this.helper.executeExtrinsic(3104 signer,3105 `api.tx.${this.palletName}.send`,3106 [3107 destination,3108 message,3109 ],3110 true,3111 );3112 }3113}31143115class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {3116 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {3117 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);3118 }31193120 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {3121 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);3122 }31233124 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {3125 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);3126 }3127}31283129class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {3130 async accounts(address: string, currencyId: any) {3131 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;3132 return BigInt(free);3133 }3134}31353136class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {3137 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {3138 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);3139 }31403141 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {3142 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);3143 }31443145 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {3146 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);3147 }31483149 async account(assetId: string | number, address: string) {3150 const accountAsset = (3151 await this.helper.callRpc('api.query.assets.account', [assetId, address])3152 ).toJSON()! as any;31533154 if (accountAsset !== null) {3155 return BigInt(accountAsset['balance']);3156 } else {3157 return null;3158 }3159 }3160}31613162class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {3163 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {3164 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);3165 }3166}31673168class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {3169 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {3170 const apiPrefix = 'api.tx.assetManager.';31713172 const registerTx = this.helper.constructApiCall(3173 apiPrefix + 'registerForeignAsset',3174 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],3175 );31763177 const setUnitsTx = this.helper.constructApiCall(3178 apiPrefix + 'setAssetUnitsPerSecond',3179 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],3180 );31813182 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);3183 const encodedProposal = batchCall?.method.toHex() || '';3184 return encodedProposal;3185 }31863187 async assetTypeId(location: any) {3188 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);3189 }3190}31913192class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {3193 notePreimagePallet: string;31943195 constructor(helper: MoonbeamHelper, options: { [key: string]: any } = {}) {3196 super(helper);3197 this.notePreimagePallet = options.notePreimagePallet;3198 }31993200 async notePreimage(signer: TSigner, encodedProposal: string) {3201 await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);3202 }32033204 externalProposeMajority(proposal: any) {3205 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);3206 }32073208 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {3209 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);3210 }32113212 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {3213 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);3214 }3215}32163217class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {3218 collective: string;32193220 constructor(helper: MoonbeamHelper, collective: string) {3221 super(helper);32223223 this.collective = collective;3224 }32253226 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {3227 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);3228 }32293230 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {3231 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);3232 }32333234 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {3235 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);3236 }32373238 async proposalCount() {3239 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));3240 }3241}32423243export type ChainHelperBaseConstructor = new (...args: any[]) => ChainHelperBase;3244export type UniqueHelperConstructor = new (...args: any[]) => UniqueHelper;32453246export class UniqueHelper extends ChainHelperBase {3247 balance: BalanceGroup<UniqueHelper>;3248 collection: CollectionGroup;3249 nft: NFTGroup;3250 rft: RFTGroup;3251 ft: FTGroup;3252 staking: StakingGroup;3253 scheduler: SchedulerGroup;3254 collatorSelection: CollatorSelectionGroup;3255 preimage: PreimageGroup;3256 foreignAssets: ForeignAssetsGroup;3257 xcm: XcmGroup<UniqueHelper>;3258 xTokens: XTokensGroup<UniqueHelper>;3259 tokens: TokensGroup<UniqueHelper>;32603261 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3262 super(logger, options.helperBase ?? UniqueHelper);32633264 this.balance = new BalanceGroup(this);3265 this.collection = new CollectionGroup(this);3266 this.nft = new NFTGroup(this);3267 this.rft = new RFTGroup(this);3268 this.ft = new FTGroup(this);3269 this.staking = new StakingGroup(this);3270 this.scheduler = new SchedulerGroup(this);3271 this.collatorSelection = new CollatorSelectionGroup(this);3272 this.preimage = new PreimageGroup(this);3273 this.foreignAssets = new ForeignAssetsGroup(this);3274 this.xcm = new XcmGroup(this, 'polkadotXcm');3275 this.xTokens = new XTokensGroup(this);3276 this.tokens = new TokensGroup(this);3277 }32783279 getSudo<T extends UniqueHelper>() {3280 3281 const SudoHelperType = SudoHelper(this.helperBase);3282 return this.clone(SudoHelperType) as T;3283 }3284}32853286export class XcmChainHelper extends ChainHelperBase {3287 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {3288 const wsProvider = new WsProvider(wsEndpoint);3289 this.api = new ApiPromise({3290 provider: wsProvider,3291 });3292 await this.api.isReadyOrError;3293 this.network = await UniqueHelper.detectNetwork(this.api);3294 }3295}32963297export class RelayHelper extends XcmChainHelper {3298 balance: SubstrateBalanceGroup<RelayHelper>;3299 xcm: XcmGroup<RelayHelper>;33003301 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3302 super(logger, options.helperBase ?? RelayHelper);33033304 this.balance = new SubstrateBalanceGroup(this);3305 this.xcm = new XcmGroup(this, 'xcmPallet');3306 }3307}33083309export class WestmintHelper extends XcmChainHelper {3310 balance: SubstrateBalanceGroup<WestmintHelper>;3311 xcm: XcmGroup<WestmintHelper>;3312 assets: AssetsGroup<WestmintHelper>;3313 xTokens: XTokensGroup<WestmintHelper>;33143315 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3316 super(logger, options.helperBase ?? WestmintHelper);33173318 this.balance = new SubstrateBalanceGroup(this);3319 this.xcm = new XcmGroup(this, 'polkadotXcm');3320 this.assets = new AssetsGroup(this);3321 this.xTokens = new XTokensGroup(this);3322 }3323}33243325export class MoonbeamHelper extends XcmChainHelper {3326 balance: EthereumBalanceGroup<MoonbeamHelper>;3327 assetManager: MoonbeamAssetManagerGroup;3328 assets: AssetsGroup<MoonbeamHelper>;3329 xTokens: XTokensGroup<MoonbeamHelper>;3330 democracy: MoonbeamDemocracyGroup;3331 collective: {3332 council: MoonbeamCollectiveGroup,3333 techCommittee: MoonbeamCollectiveGroup,3334 };33353336 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3337 super(logger, options.helperBase ?? MoonbeamHelper);33383339 this.balance = new EthereumBalanceGroup(this);3340 this.assetManager = new MoonbeamAssetManagerGroup(this);3341 this.assets = new AssetsGroup(this);3342 this.xTokens = new XTokensGroup(this);3343 this.democracy = new MoonbeamDemocracyGroup(this, options);3344 this.collective = {3345 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),3346 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),3347 };3348 }3349}33503351export class AstarHelper extends XcmChainHelper {3352 balance: SubstrateBalanceGroup<AstarHelper>;3353 assets: AssetsGroup<AstarHelper>;3354 xcm: XcmGroup<AstarHelper>;33553356 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3357 super(logger, options.helperBase ?? AstarHelper);33583359 this.balance = new SubstrateBalanceGroup(this);3360 this.assets = new AssetsGroup(this);3361 this.xcm = new XcmGroup(this, 'polkadotXcm');3362 }33633364 getSudo<T extends UniqueHelper>() {3365 3366 const SudoHelperType = SudoHelper(this.helperBase);3367 return this.clone(SudoHelperType) as T;3368 }3369}33703371export class AcalaHelper extends XcmChainHelper {3372 balance: SubstrateBalanceGroup<AcalaHelper>;3373 assetRegistry: AcalaAssetRegistryGroup;3374 xTokens: XTokensGroup<AcalaHelper>;3375 tokens: TokensGroup<AcalaHelper>;3376 xcm: XcmGroup<AcalaHelper>;33773378 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3379 super(logger, options.helperBase ?? AcalaHelper);33803381 this.balance = new SubstrateBalanceGroup(this);3382 this.assetRegistry = new AcalaAssetRegistryGroup(this);3383 this.xTokens = new XTokensGroup(this);3384 this.tokens = new TokensGroup(this);3385 this.xcm = new XcmGroup(this, 'polkadotXcm');3386 }33873388 getSudo<T extends AcalaHelper>() {3389 3390 const SudoHelperType = SudoHelper(this.helperBase);3391 return this.clone(SudoHelperType) as T;3392 }3393}339433953396function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3397 return class extends Base {3398 scheduleFn: 'schedule' | 'scheduleAfter';3399 blocksNum: number;3400 options: ISchedulerOptions;34013402 constructor(...args: any[]) {3403 const logger = args[0] as ILogger;3404 const options = args[1] as {3405 scheduleFn: 'schedule' | 'scheduleAfter',3406 blocksNum: number,3407 options: ISchedulerOptions3408 };34093410 super(logger);34113412 this.scheduleFn = options.scheduleFn;3413 this.blocksNum = options.blocksNum;3414 this.options = options.options;3415 }34163417 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3418 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);34193420 const mandatorySchedArgs = [3421 this.blocksNum,3422 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3423 this.options.priority ?? null,3424 scheduledTx,3425 ];34263427 let schedArgs;3428 let scheduleFn;34293430 if (this.options.scheduledId) {3431 schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];34323433 if (this.scheduleFn == 'schedule') {3434 scheduleFn = 'scheduleNamed';3435 } else if (this.scheduleFn == 'scheduleAfter') {3436 scheduleFn = 'scheduleNamedAfter';3437 }3438 } else {3439 schedArgs = mandatorySchedArgs;3440 scheduleFn = this.scheduleFn;3441 }34423443 const extrinsic = 'api.tx.scheduler.' + scheduleFn;34443445 return super.executeExtrinsic(3446 sender,3447 extrinsic as any,3448 schedArgs,3449 expectSuccess,3450 );3451 }3452 };3453}345434553456function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3457 return class extends Base {3458 constructor(...args: any[]) {3459 super(...args);3460 }34613462 async executeExtrinsic(3463 sender: IKeyringPair,3464 extrinsic: string,3465 params: any[],3466 expectSuccess?: boolean,3467 options: Partial<SignerOptions> | null = null,3468 ): Promise<ITransactionResult> {3469 const call = this.constructApiCall(extrinsic, params);3470 const result = await super.executeExtrinsic(3471 sender,3472 'api.tx.sudo.sudo',3473 [call],3474 expectSuccess,3475 options,3476 );34773478 if (result.status === 'Fail') return result;34793480 const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;3481 if (data.isErr) {3482 if (data.asErr.isModule) {3483 const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;3484 const metaError = super.getApi()?.registry.findMetaError(error);3485 throw new Error(`${metaError.section}.${metaError.name}`);3486 } else if (data.asErr.isToken) {3487 throw new Error(`Token: ${data.asErr.asToken}`);3488 }3489 }3490 return result;3491 }3492 };3493}34943495export class UniqueBaseCollection {3496 helper: UniqueHelper;3497 collectionId: number;34983499 constructor(collectionId: number, uniqueHelper: UniqueHelper) {3500 this.collectionId = collectionId;3501 this.helper = uniqueHelper;3502 }35033504 async getData() {3505 return await this.helper.collection.getData(this.collectionId);3506 }35073508 async getLastTokenId() {3509 return await this.helper.collection.getLastTokenId(this.collectionId);3510 }35113512 async doesTokenExist(tokenId: number) {3513 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3514 }35153516 async getAdmins() {3517 return await this.helper.collection.getAdmins(this.collectionId);3518 }35193520 async getAllowList() {3521 return await this.helper.collection.getAllowList(this.collectionId);3522 }35233524 async getEffectiveLimits() {3525 return await this.helper.collection.getEffectiveLimits(this.collectionId);3526 }35273528 async getProperties(propertyKeys?: string[] | null) {3529 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3530 }35313532 async getPropertiesConsumedSpace() {3533 return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3534 }35353536 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3537 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3538 }35393540 async getOptions() {3541 return await this.helper.collection.getCollectionOptions(this.collectionId);3542 }35433544 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3545 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3546 }35473548 async confirmSponsorship(signer: TSigner) {3549 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3550 }35513552 async removeSponsor(signer: TSigner) {3553 return await this.helper.collection.removeSponsor(signer, this.collectionId);3554 }35553556 async setLimits(signer: TSigner, limits: ICollectionLimits) {3557 return await this.helper.collection.setLimits(signer, this.collectionId, limits);3558 }35593560 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3561 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3562 }35633564 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3565 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3566 }35673568 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3569 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3570 }35713572 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3573 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3574 }35753576 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3577 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3578 }35793580 async setProperties(signer: TSigner, properties: IProperty[]) {3581 return await this.helper.collection.setProperties(signer, this.collectionId, properties);3582 }35833584 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3585 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3586 }35873588 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3589 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3590 }35913592 async enableNesting(signer: TSigner, permissions: INestingPermissions) {3593 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3594 }35953596 async disableNesting(signer: TSigner) {3597 return await this.helper.collection.disableNesting(signer, this.collectionId);3598 }35993600 async burn(signer: TSigner) {3601 return await this.helper.collection.burn(signer, this.collectionId);3602 }36033604 scheduleAt<T extends UniqueHelper>(3605 executionBlockNumber: number,3606 options: ISchedulerOptions = {},3607 ) {3608 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3609 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3610 }36113612 scheduleAfter<T extends UniqueHelper>(3613 blocksBeforeExecution: number,3614 options: ISchedulerOptions = {},3615 ) {3616 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3617 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3618 }36193620 getSudo<T extends UniqueHelper>() {3621 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3622 }3623}362436253626export class UniqueNFTCollection extends UniqueBaseCollection {3627 getTokenObject(tokenId: number) {3628 return new UniqueNFToken(tokenId, this);3629 }36303631 async getTokensByAddress(addressObj: ICrossAccountId) {3632 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3633 }36343635 async getToken(tokenId: number, blockHashAt?: string) {3636 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3637 }36383639 async getTokenOwner(tokenId: number, blockHashAt?: string) {3640 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3641 }36423643 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3644 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3645 }36463647 async getTokenChildren(tokenId: number, blockHashAt?: string) {3648 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3649 }36503651 async getPropertyPermissions(propertyKeys: string[] | null = null) {3652 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3653 }36543655 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3656 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3657 }36583659 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3660 const api = this.helper.getApi();3661 const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();36623663 return (props! as any).consumedSpace;3664 }36653666 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3667 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3668 }36693670 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3671 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3672 }36733674 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3675 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3676 }36773678 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3679 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3680 }36813682 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3683 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3684 }36853686 async mintMultipleTokens(signer: TSigner, tokens: { owner: ICrossAccountId, properties?: IProperty[] }[]) {3687 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3688 }36893690 async burnToken(signer: TSigner, tokenId: number) {3691 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3692 }36933694 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3695 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3696 }36973698 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3699 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3700 }37013702 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3703 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3704 }37053706 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3707 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3708 }37093710 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3711 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3712 }37133714 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3715 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3716 }37173718 scheduleAt<T extends UniqueHelper>(3719 executionBlockNumber: number,3720 options: ISchedulerOptions = {},3721 ) {3722 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3723 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3724 }37253726 scheduleAfter<T extends UniqueHelper>(3727 blocksBeforeExecution: number,3728 options: ISchedulerOptions = {},3729 ) {3730 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3731 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3732 }37333734 getSudo<T extends UniqueHelper>() {3735 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3736 }3737}373837393740export class UniqueRFTCollection extends UniqueBaseCollection {3741 getTokenObject(tokenId: number) {3742 return new UniqueRFToken(tokenId, this);3743 }37443745 async getToken(tokenId: number, blockHashAt?: string) {3746 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3747 }37483749 async getTokenOwner(tokenId: number, blockHashAt?: string) {3750 return await this.helper.rft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3751 }37523753 async getTokensByAddress(addressObj: ICrossAccountId) {3754 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3755 }37563757 async getTop10TokenOwners(tokenId: number) {3758 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3759 }37603761 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3762 return await this.helper.rft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3763 }37643765 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3766 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3767 }37683769 async getTokenTotalPieces(tokenId: number) {3770 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3771 }37723773 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3774 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3775 }37763777 async getPropertyPermissions(propertyKeys: string[] | null = null) {3778 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3779 }37803781 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3782 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3783 }37843785 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3786 const api = this.helper.getApi();3787 const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();37883789 return (props! as any).consumedSpace;3790 }37913792 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount = 1n) {3793 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3794 }37953796 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {3797 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3798 }37993800 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {3801 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3802 }38033804 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3805 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3806 }38073808 async mintToken(signer: TSigner, pieces = 1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3809 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3810 }38113812 async mintMultipleTokens(signer: TSigner, tokens: { pieces: bigint, owner: ICrossAccountId, properties?: IProperty[] }[]) {3813 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3814 }38153816 async burnToken(signer: TSigner, tokenId: number, amount = 1n) {3817 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3818 }38193820 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n) {3821 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3822 }38233824 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3825 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3826 }38273828 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3829 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3830 }38313832 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3833 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3834 }38353836 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3837 return await this.helper.rft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3838 }38393840 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3841 return await this.helper.rft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3842 }38433844 scheduleAt<T extends UniqueHelper>(3845 executionBlockNumber: number,3846 options: ISchedulerOptions = {},3847 ) {3848 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3849 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3850 }38513852 scheduleAfter<T extends UniqueHelper>(3853 blocksBeforeExecution: number,3854 options: ISchedulerOptions = {},3855 ) {3856 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3857 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3858 }38593860 getSudo<T extends UniqueHelper>() {3861 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3862 }3863}386438653866export class UniqueFTCollection extends UniqueBaseCollection {3867 async getBalance(addressObj: ICrossAccountId) {3868 return await this.helper.ft.getBalance(this.collectionId, addressObj);3869 }38703871 async getTotalPieces() {3872 return await this.helper.ft.getTotalPieces(this.collectionId);3873 }38743875 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3876 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3877 }38783879 async getTop10Owners() {3880 return await this.helper.ft.getTop10Owners(this.collectionId);3881 }38823883 async mint(signer: TSigner, amount = 1n, owner: ICrossAccountId = {Substrate: signer.address}) {3884 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3885 }38863887 async mintWithOneOwner(signer: TSigner, tokens: { value: bigint }[], owner: ICrossAccountId = {Substrate: signer.address}) {3888 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3889 }38903891 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {3892 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3893 }38943895 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {3896 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3897 }38983899 async burnTokens(signer: TSigner, amount = 1n) {3900 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3901 }39023903 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount = 1n) {3904 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3905 }39063907 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {3908 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3909 }39103911 scheduleAt<T extends UniqueHelper>(3912 executionBlockNumber: number,3913 options: ISchedulerOptions = {},3914 ) {3915 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3916 return new UniqueFTCollection(this.collectionId, scheduledHelper);3917 }39183919 scheduleAfter<T extends UniqueHelper>(3920 blocksBeforeExecution: number,3921 options: ISchedulerOptions = {},3922 ) {3923 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3924 return new UniqueFTCollection(this.collectionId, scheduledHelper);3925 }39263927 getSudo<T extends UniqueHelper>() {3928 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3929 }3930}393139323933export class UniqueBaseToken {3934 collection: UniqueNFTCollection | UniqueRFTCollection;3935 collectionId: number;3936 tokenId: number;39373938 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3939 this.collection = collection;3940 this.collectionId = collection.collectionId;3941 this.tokenId = tokenId;3942 }39433944 async getNextSponsored(addressObj: ICrossAccountId) {3945 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3946 }39473948 async getProperties(propertyKeys?: string[] | null) {3949 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3950 }39513952 async getTokenPropertiesConsumedSpace() {3953 return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3954 }39553956 async setProperties(signer: TSigner, properties: IProperty[]) {3957 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3958 }39593960 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3961 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3962 }39633964 async doesExist() {3965 return await this.collection.doesTokenExist(this.tokenId);3966 }39673968 nestingAccount() {3969 return this.collection.helper.util.getTokenAccount(this);3970 }39713972 scheduleAt<T extends UniqueHelper>(3973 executionBlockNumber: number,3974 options: ISchedulerOptions = {},3975 ) {3976 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3977 return new UniqueBaseToken(this.tokenId, scheduledCollection);3978 }39793980 scheduleAfter<T extends UniqueHelper>(3981 blocksBeforeExecution: number,3982 options: ISchedulerOptions = {},3983 ) {3984 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3985 return new UniqueBaseToken(this.tokenId, scheduledCollection);3986 }39873988 getSudo<T extends UniqueHelper>() {3989 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3990 }3991}399239933994export class UniqueNFToken extends UniqueBaseToken {3995 collection: UniqueNFTCollection;39963997 constructor(tokenId: number, collection: UniqueNFTCollection) {3998 super(tokenId, collection);3999 this.collection = collection;4000 }40014002 async getData(blockHashAt?: string) {4003 return await this.collection.getToken(this.tokenId, blockHashAt);4004 }40054006 async getOwner(blockHashAt?: string) {4007 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);4008 }40094010 async getTopmostOwner(blockHashAt?: string) {4011 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);4012 }40134014 async getChildren(blockHashAt?: string) {4015 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);4016 }40174018 async nest(signer: TSigner, toTokenObj: IToken) {4019 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);4020 }40214022 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {4023 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);4024 }40254026 async transfer(signer: TSigner, addressObj: ICrossAccountId) {4027 return await this.collection.transferToken(signer, this.tokenId, addressObj);4028 }40294030 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {4031 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);4032 }40334034 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {4035 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);4036 }40374038 async isApproved(toAddressObj: ICrossAccountId) {4039 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);4040 }40414042 async burn(signer: TSigner) {4043 return await this.collection.burnToken(signer, this.tokenId);4044 }40454046 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {4047 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);4048 }40494050 scheduleAt<T extends UniqueHelper>(4051 executionBlockNumber: number,4052 options: ISchedulerOptions = {},4053 ) {4054 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);4055 return new UniqueNFToken(this.tokenId, scheduledCollection);4056 }40574058 scheduleAfter<T extends UniqueHelper>(4059 blocksBeforeExecution: number,4060 options: ISchedulerOptions = {},4061 ) {4062 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);4063 return new UniqueNFToken(this.tokenId, scheduledCollection);4064 }40654066 getSudo<T extends UniqueHelper>() {4067 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());4068 }4069}40704071export class UniqueRFToken extends UniqueBaseToken {4072 collection: UniqueRFTCollection;40734074 constructor(tokenId: number, collection: UniqueRFTCollection) {4075 super(tokenId, collection);4076 this.collection = collection;4077 }40784079 async getData(blockHashAt?: string) {4080 return await this.collection.getToken(this.tokenId, blockHashAt);4081 }40824083 async getOwner(blockHashAt?: string) {4084 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);4085 }40864087 async getTop10Owners() {4088 return await this.collection.getTop10TokenOwners(this.tokenId);4089 }40904091 async getTopmostOwner(blockHashAt?: string) {4092 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);4093 }40944095 async nest(signer: TSigner, toTokenObj: IToken) {4096 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);4097 }40984099 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {4100 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);4101 }41024103 async getBalance(addressObj: ICrossAccountId) {4104 return await this.collection.getTokenBalance(this.tokenId, addressObj);4105 }41064107 async getTotalPieces() {4108 return await this.collection.getTokenTotalPieces(this.tokenId);4109 }41104111 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {4112 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);4113 }41144115 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount = 1n) {4116 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);4117 }41184119 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {4120 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);4121 }41224123 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {4124 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);4125 }41264127 async repartition(signer: TSigner, amount: bigint) {4128 return await this.collection.repartitionToken(signer, this.tokenId, amount);4129 }41304131 async burn(signer: TSigner, amount = 1n) {4132 return await this.collection.burnToken(signer, this.tokenId, amount);4133 }41344135 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount = 1n) {4136 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);4137 }41384139 scheduleAt<T extends UniqueHelper>(4140 executionBlockNumber: number,4141 options: ISchedulerOptions = {},4142 ) {4143 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);4144 return new UniqueRFToken(this.tokenId, scheduledCollection);4145 }41464147 scheduleAfter<T extends UniqueHelper>(4148 blocksBeforeExecution: number,4149 options: ISchedulerOptions = {},4150 ) {4151 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);4152 return new UniqueRFToken(this.tokenId, scheduledCollection);4153 }41544155 getSudo<T extends UniqueHelper>() {4156 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());4157 }4158}