12345678import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {hexToU8a} from '@polkadot/util/hex';13import {u8aConcat} from '@polkadot/util/u8a';14import {15 IApiListeners,16 IBlock,17 IEvent,18 IChainProperties,19 ICollectionCreationOptions,20 ICollectionLimits,21 ICollectionPermissions,22 ICrossAccountId,23 ICrossAccountIdLower,24 ILogger,25 INestingPermissions,26 IProperty,27 IStakingInfo,28 ISchedulerOptions,29 ISubstrateBalance,30 IToken,31 ITokenPropertyPermission,32 ITransactionResult,33 IUniqueHelperLog,34 TApiAllowedListeners,35 TEthereumAccount,36 TSigner,37 TSubstrateAccount,38 TNetworks,39 IForeignAssetMetadata,40 AcalaAssetMetadata,41 MoonbeamAssetInfo,42 DemocracyStandardAccountVote,43 IEthCrossAccountId,44} from './types';45import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';46import type {Vec} from '@polkadot/types-codec';47import {FrameSystemEventRecord} from '@polkadot/types/lookup';4849export class CrossAccountId implements ICrossAccountId {50 Substrate?: TSubstrateAccount;51 Ethereum?: TEthereumAccount;5253 constructor(account: ICrossAccountId) {54 if (account.Substrate) this.Substrate = account.Substrate;55 if (account.Ethereum) this.Ethereum = account.Ethereum;56 }5758 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {59 switch (domain) {60 case 'Substrate': return new CrossAccountId({Substrate: account.address});61 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();62 }63 }6465 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {66 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});67 }6869 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {70 return encodeAddress(decodeAddress(address), ss58Format);71 }7273 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {74 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});75 }7677 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {78 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);79 return this;80 }8182 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {83 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));84 }8586 toEthereum(): CrossAccountId {87 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});88 return this;89 }9091 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {92 return evmToAddress(address, ss58Format);93 }9495 toSubstrate(ss58Format?: number): CrossAccountId {96 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});97 return this;98 }99100 toLowerCase(): CrossAccountId {101 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();102 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();103 return this;104 }105}106107const nesting = {108 toChecksumAddress(address: string): string {109 if (typeof address === 'undefined') return '';110111 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);112113 address = address.toLowerCase().replace(/^0x/i,'');114 const addressHash = keccakAsHex(address).replace(/^0x/i,'');115 const checksumAddress = ['0x'];116117 for (let i = 0; i < address.length; i++) {118 119 if (parseInt(addressHash[i], 16) > 7) {120 checksumAddress.push(address[i].toUpperCase());121 } else {122 checksumAddress.push(address[i]);123 }124 }125 return checksumAddress.join('');126 },127 tokenIdToAddress(collectionId: number, tokenId: number) {128 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);129 },130};131132class UniqueUtil {133 static transactionStatus = {134 NOT_READY: 'NotReady',135 FAIL: 'Fail',136 SUCCESS: 'Success',137 };138139 static chainLogType = {140 EXTRINSIC: 'extrinsic',141 RPC: 'rpc',142 };143144 static getTokenAccount(token: IToken): CrossAccountId {145 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});146 }147148 static getTokenAddress(token: IToken): string {149 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);150 }151152 static getDefaultLogger(): ILogger {153 return {154 log(msg: any, level = 'INFO') {155 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));156 },157 level: {158 ERROR: 'ERROR',159 WARNING: 'WARNING',160 INFO: 'INFO',161 },162 };163 }164165 static vec2str(arr: string[] | number[]) {166 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');167 }168169 static str2vec(string: string) {170 if (typeof string !== 'string') return string;171 return Array.from(string).map(x => x.charCodeAt(0));172 }173174 static fromSeed(seed: string, ss58Format = 42) {175 const keyring = new Keyring({type: 'sr25519', ss58Format});176 return keyring.addFromUri(seed);177 }178179 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {180 if (creationResult.status !== this.transactionStatus.SUCCESS) {181 throw Error('Unable to create collection!');182 }183184 let collectionId = null;185 creationResult.result.events.forEach(({event: {data, method, section}}) => {186 if ((section === 'common') && (method === 'CollectionCreated')) {187 collectionId = parseInt(data[0].toString(), 10);188 }189 });190191 if (collectionId === null) {192 throw Error('No CollectionCreated event was found!');193 }194195 return collectionId;196 }197198 static extractTokensFromCreationResult(creationResult: ITransactionResult): {199 success: boolean,200 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],201 } {202 if (creationResult.status !== this.transactionStatus.SUCCESS) {203 throw Error('Unable to create tokens!');204 }205 let success = false;206 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];207 creationResult.result.events.forEach(({event: {data, method, section}}) => {208 if (method === 'ExtrinsicSuccess') {209 success = true;210 } else if ((section === 'common') && (method === 'ItemCreated')) {211 tokens.push({212 collectionId: parseInt(data[0].toString(), 10),213 tokenId: parseInt(data[1].toString(), 10),214 owner: data[2].toHuman(),215 amount: data[3].toBigInt(),216 });217 }218 });219 return {success, tokens};220 }221222 static extractTokensFromBurnResult(burnResult: ITransactionResult): {223 success: boolean,224 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],225 } {226 if (burnResult.status !== this.transactionStatus.SUCCESS) {227 throw Error('Unable to burn tokens!');228 }229 let success = false;230 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];231 burnResult.result.events.forEach(({event: {data, method, section}}) => {232 if (method === 'ExtrinsicSuccess') {233 success = true;234 } else if ((section === 'common') && (method === 'ItemDestroyed')) {235 tokens.push({236 collectionId: parseInt(data[0].toString(), 10),237 tokenId: parseInt(data[1].toString(), 10),238 owner: data[2].toHuman(),239 amount: data[3].toBigInt(),240 });241 }242 });243 return {success, tokens};244 }245246 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {247 let eventId = null;248 events.forEach(({event: {data, method, section}}) => {249 if ((section === expectedSection) && (method === expectedMethod)) {250 eventId = parseInt(data[0].toString(), 10);251 }252 });253254 if (eventId === null) {255 throw Error(`No ${expectedMethod} event was found!`);256 }257 return eventId === collectionId;258 }259260 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {261 const normalizeAddress = (address: string | ICrossAccountId) => {262 if(typeof address === 'string') return address;263 const obj = {} as any;264 Object.keys(address).forEach(k => {265 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];266 });267 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);268 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();269 return address;270 };271 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;272 events.forEach(({event: {data, method, section}}) => {273 if ((section === 'common') && (method === 'Transfer')) {274 const hData = (data as any).toJSON();275 transfer = {276 collectionId: hData[0],277 tokenId: hData[1],278 from: normalizeAddress(hData[2]),279 to: normalizeAddress(hData[3]),280 amount: BigInt(hData[4]),281 };282 }283 });284 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;285 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);286 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);287 isSuccess = isSuccess && amount === transfer.amount;288 return isSuccess;289 }290291 static bigIntToDecimals(number: bigint, decimals = 18) {292 const numberStr = number.toString();293 const dotPos = numberStr.length - decimals;294295 if (dotPos <= 0) {296 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;297 } else {298 const intPart = numberStr.substring(0, dotPos);299 const fractPart = numberStr.substring(dotPos);300 return intPart + '.' + fractPart;301 }302 }303}304305class UniqueEventHelper {306 private static extractIndex(index: any): [number, number] | string {307 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];308 return index.toJSON();309 }310311 private static extractSub(data: any, subTypes: any): {[key: string]: any} {312 let obj: any = {};313 let index = 0;314315 if (data.entries) {316 for(const [key, value] of data.entries()) {317 obj[key] = this.extractData(value, subTypes[index]);318 index++;319 }320 } else obj = data.toJSON();321322 return obj;323 }324325 private static toHuman(data: any) {326 return data && data.toHuman ? data.toHuman() : `${data}`;327 }328329 private static extractData(data: any, type: any): any {330 if(!type) return this.toHuman(data);331 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();332 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();333 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);334 return this.toHuman(data);335 }336337 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {338 const parsedEvents: IEvent[] = [];339340 events.forEach((record) => {341 const {event, phase} = record;342 const types = event.typeDef;343344 const eventData: IEvent = {345 section: event.section.toString(),346 method: event.method.toString(),347 index: this.extractIndex(event.index),348 data: [],349 phase: phase.toJSON(),350 };351352 event.data.forEach((val: any, index: number) => {353 eventData.data.push(this.extractData(val, types[index]));354 });355356 parsedEvents.push(eventData);357 });358359 return parsedEvents;360 }361}362363export class ChainHelperBase {364 helperBase: any;365366 transactionStatus = UniqueUtil.transactionStatus;367 chainLogType = UniqueUtil.chainLogType;368 util: typeof UniqueUtil;369 eventHelper: typeof UniqueEventHelper;370 logger: ILogger;371 api: ApiPromise | null;372 forcedNetwork: TNetworks | null;373 network: TNetworks | null;374 wsEndpoint: string | null;375 chainLog: IUniqueHelperLog[];376 children: ChainHelperBase[];377 address: AddressGroup;378 chain: ChainGroup;379380 constructor(logger?: ILogger, helperBase?: any) {381 this.helperBase = helperBase;382383 this.util = UniqueUtil;384 this.eventHelper = UniqueEventHelper;385 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();386 this.logger = logger;387 this.api = null;388 this.forcedNetwork = null;389 this.network = null;390 this.wsEndpoint = null;391 this.chainLog = [];392 this.children = [];393 this.address = new AddressGroup(this);394 this.chain = new ChainGroup(this);395 }396397 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {398 Object.setPrototypeOf(helperCls.prototype, this);399 const newHelper = new helperCls(this.logger, options);400401 newHelper.api = this.api;402 newHelper.network = this.network;403 newHelper.forceNetwork = this.forceNetwork;404405 this.children.push(newHelper);406407 return newHelper;408 }409410 getEndpoint(): string {411 if (this.wsEndpoint === null) throw Error('No connection was established');412 return this.wsEndpoint;413 }414415 getApi(): ApiPromise {416 if(this.api === null) throw Error('API not initialized');417 return this.api;418 }419420 async subscribeEvents(expectedEvents: {section: string, names: string[]}[]) {421 const collectedEvents: IEvent[] = [];422 const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {423 const ievents = this.eventHelper.extractEvents(events);424 ievents.forEach((event) => {425 expectedEvents.forEach((e => {426 if (event.section === e.section && e.names.includes(event.method)) {427 collectedEvents.push(event);428 }429 }));430 });431 });432 return {unsubscribe: unsubscribe as any, collectedEvents};433 }434435 clearChainLog(): void {436 this.chainLog = [];437 }438439 forceNetwork(value: TNetworks): void {440 this.forcedNetwork = value;441 }442443 async connect(wsEndpoint: string, listeners?: IApiListeners) {444 if (this.api !== null) throw Error('Already connected');445 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);446 this.wsEndpoint = wsEndpoint;447 this.api = api;448 this.network = network;449 }450451 async disconnect() {452 for (const child of this.children) {453 child.clearApi();454 }455456 if (this.api === null) return;457 await this.api.disconnect();458 this.clearApi();459 }460461 clearApi() {462 this.api = null;463 this.network = null;464 }465466 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {467 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;468 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];469470 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;471472 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;473 return 'opal';474 }475476 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {477 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});478 await api.isReady;479480 const network = await this.detectNetwork(api);481482 await api.disconnect();483484 return network;485 }486487 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{488 api: ApiPromise;489 network: TNetworks;490 }> {491 if(typeof network === 'undefined' || network === null) network = 'opal';492 const supportedRPC = {493 opal: {494 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,495 },496 quartz: {497 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,498 },499 unique: {500 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,501 },502 rococo: {},503 westend: {},504 moonbeam: {},505 moonriver: {},506 acala: {},507 karura: {},508 westmint: {},509 };510 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);511 const rpc = supportedRPC[network];512513 514 515516 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});517518 await api.isReadyOrError;519520 if (typeof listeners === 'undefined') listeners = {};521 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {522 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;523 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);524 }525526 return {api, network};527 }528529 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {530 const {events, status} = data;531 if (status.isReady) {532 return this.transactionStatus.NOT_READY;533 }534 if (status.isBroadcast) {535 return this.transactionStatus.NOT_READY;536 }537 if (status.isInBlock || status.isFinalized) {538 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');539 if (errors.length > 0) {540 return this.transactionStatus.FAIL;541 }542 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {543 return this.transactionStatus.SUCCESS;544 }545 }546547 return this.transactionStatus.FAIL;548 }549550 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {551 const sign = (callback: any) => {552 if(options !== null) return transaction.signAndSend(sender, options, callback);553 return transaction.signAndSend(sender, callback);554 };555 556 return new Promise(async (resolve, reject) => {557 try {558 const unsub = await sign((result: any) => {559 const status = this.getTransactionStatus(result);560561 if (status === this.transactionStatus.SUCCESS) {562 this.logger.log(`${label} successful`);563 unsub();564 resolve({result, status});565 } else if (status === this.transactionStatus.FAIL) {566 let moduleError = null;567568 if (result.hasOwnProperty('dispatchError')) {569 const dispatchError = result['dispatchError'];570571 if (dispatchError) {572 if (dispatchError.isModule) {573 const modErr = dispatchError.asModule;574 const errorMeta = dispatchError.registry.findMetaError(modErr);575576 moduleError = `${errorMeta.section}.${errorMeta.name}`;577 } else {578 moduleError = dispatchError.toHuman();579 }580 } else {581 this.logger.log(result, this.logger.level.ERROR);582 }583 }584585 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);586 unsub();587 reject({status, moduleError, result});588 }589 });590 } catch (e) {591 this.logger.log(e, this.logger.level.ERROR);592 reject(e);593 }594 });595 }596597 async signTransactionWithoutSending(signer: TSigner, tx: any) {598 const api = this.getApi();599 const signingInfo = await api.derive.tx.signingInfo(signer.address);600601 tx.sign(signer, {602 blockHash: api.genesisHash,603 genesisHash: api.genesisHash,604 runtimeVersion: api.runtimeVersion,605 nonce: signingInfo.nonce,606 });607608 return tx.toHex();609 }610611 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {612 const api = this.getApi();613 const signingInfo = await api.derive.tx.signingInfo(signer.address);614615 616 617 tx.sign(signer, {618 blockHash: api.genesisHash,619 genesisHash: api.genesisHash,620 runtimeVersion: api.runtimeVersion,621 nonce: signingInfo.nonce,622 });623624 if (len === null) {625 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;626 } else {627 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;628 }629 }630631 constructApiCall(apiCall: string, params: any[]) {632 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);633 let call = this.getApi() as any;634 for(const part of apiCall.slice(4).split('.')) {635 call = call[part];636 if (!call) {637 const advice = part.includes('_') ? ' Looks like it needs to be converted to camel case.' : '';638 throw Error(`Function ${part} of api call ${apiCall} not found.${advice}`);639 }640 }641 return call(...params);642 }643644 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null) {645 if(this.api === null) throw Error('API not initialized');646 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);647648 const startTime = (new Date()).getTime();649 let result: ITransactionResult;650 let events: IEvent[] = [];651 try {652 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;653 events = this.eventHelper.extractEvents(result.result.events);654 }655 catch(e) {656 if(!(e as object).hasOwnProperty('status')) throw e;657 result = e as ITransactionResult;658 }659660 const endTime = (new Date()).getTime();661662 const log = {663 executedAt: endTime,664 executionTime: endTime - startTime,665 type: this.chainLogType.EXTRINSIC,666 status: result.status,667 call: extrinsic,668 signer: this.getSignerAddress(sender),669 params,670 } as IUniqueHelperLog;671672 if(result.status !== this.transactionStatus.SUCCESS) {673 if (result.moduleError) log.moduleError = result.moduleError;674 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;675 }676 if(events.length > 0) log.events = events;677678 this.chainLog.push(log);679680 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {681 if (result.moduleError) throw Error(`${result.moduleError}`);682 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));683 }684 return result;685 }686687 async callRpc(rpc: string, params?: any[]) {688 if(typeof params === 'undefined') params = [];689 if(this.api === null) throw Error('API not initialized');690 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);691692 const startTime = (new Date()).getTime();693 let result;694 let error = null;695 const log = {696 type: this.chainLogType.RPC,697 call: rpc,698 params,699 } as IUniqueHelperLog;700701 try {702 result = await this.constructApiCall(rpc, params);703 }704 catch(e) {705 error = e;706 }707708 const endTime = (new Date()).getTime();709710 log.executedAt = endTime;711 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';712 log.executionTime = endTime - startTime;713714 this.chainLog.push(log);715716 if(error !== null) throw error;717718 return result;719 }720721 getSignerAddress(signer: IKeyringPair | string): string {722 if(typeof signer === 'string') return signer;723 return signer.address;724 }725726 fetchAllPalletNames(): string[] {727 if(this.api === null) throw Error('API not initialized');728 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());729 }730731 fetchMissingPalletNames(requiredPallets: string[]): string[] {732 const palletNames = this.fetchAllPalletNames();733 return requiredPallets.filter(p => !palletNames.includes(p));734 }735}736737738class HelperGroup<T extends ChainHelperBase> {739 helper: T;740741 constructor(uniqueHelper: T) {742 this.helper = uniqueHelper;743 }744}745746747class CollectionGroup extends HelperGroup<UniqueHelper> {748 749750751752753754755756757 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {758 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();759 }760761 762763764765766 async getTotalCount(): Promise<number> {767 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();768 }769770 771772773774775776777778779 async getData(collectionId: number): Promise<{780 id: number;781 name: string;782 description: string;783 tokensCount: number;784 admins: CrossAccountId[];785 normalizedOwner: TSubstrateAccount;786 raw: any787 } | null> {788 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);789 const humanCollection = collection.toHuman(), collectionData = {790 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],791 raw: humanCollection,792 } as any, jsonCollection = collection.toJSON();793 if (humanCollection === null) return null;794 collectionData.raw.limits = jsonCollection.limits;795 collectionData.raw.permissions = jsonCollection.permissions;796 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);797 for (const key of ['name', 'description']) {798 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);799 }800801 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))802 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)803 : 0;804 collectionData.admins = await this.getAdmins(collectionId);805806 return collectionData;807 }808809 810811812813814815816817 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {818 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();819820 return normalize821 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())822 : admins;823 }824825 826827828829830831832 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {833 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();834 return normalize835 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())836 : allowListed;837 }838839 840841842843844845846 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {847 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();848 }849850 851852853854855856857858 async burn(signer: TSigner, collectionId: number): Promise<boolean> {859 const result = await this.helper.executeExtrinsic(860 signer,861 'api.tx.unique.destroyCollection', [collectionId],862 true,863 );864865 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');866 }867868 869870871872873874875876877 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {878 const result = await this.helper.executeExtrinsic(879 signer,880 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],881 true,882 );883884 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');885 }886887 888889890891892893894895 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {896 const result = await this.helper.executeExtrinsic(897 signer,898 'api.tx.unique.confirmSponsorship', [collectionId],899 true,900 );901902 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');903 }904905 906907908909910911912913 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {914 const result = await this.helper.executeExtrinsic(915 signer,916 'api.tx.unique.removeCollectionSponsor', [collectionId],917 true,918 );919920 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');921 }922923 924925926927928929930931932933934935936937938939940 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {941 const result = await this.helper.executeExtrinsic(942 signer,943 'api.tx.unique.setCollectionLimits', [collectionId, limits],944 true,945 );946947 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');948 }949950 951952953954955956957958959 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {960 const result = await this.helper.executeExtrinsic(961 signer,962 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],963 true,964 );965966 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');967 }968969 970971972973974975976977978 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {979 const result = await this.helper.executeExtrinsic(980 signer,981 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],982 true,983 );984985 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');986 }987988 989990991992993994995996997 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {998 const result = await this.helper.executeExtrinsic(999 signer,1000 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],1001 true,1002 );10031004 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');1005 }10061007 10081009101010111012101310141015 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {1016 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();1017 }10181019 1020102110221023102410251026 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1027 const result = await this.helper.executeExtrinsic(1028 signer,1029 'api.tx.unique.addToAllowList', [collectionId, addressObj],1030 true,1031 );10321033 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1034 }10351036 10371038103910401041104210431044 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1045 const result = await this.helper.executeExtrinsic(1046 signer,1047 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1048 true,1049 );10501051 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1052 }10531054 105510561057105810591060106110621063 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1064 const result = await this.helper.executeExtrinsic(1065 signer,1066 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1067 true,1068 );10691070 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1071 }10721073 107410751076107710781079108010811082 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1083 return await this.setPermissions(signer, collectionId, {nesting: permissions});1084 }10851086 10871088108910901091109210931094 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1095 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1096 }10971098 109911001101110211031104110511061107 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1108 const result = await this.helper.executeExtrinsic(1109 signer,1110 'api.tx.unique.setCollectionProperties', [collectionId, properties],1111 true,1112 );11131114 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1115 }11161117 11181119112011211122112311241125 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1126 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1127 }11281129 async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1130 const api = this.helper.getApi();1131 const props = (await api.query.common.collectionProperties(collectionId)).toJSON();11321133 return (props! as any).consumedSpace;1134 }11351136 async getCollectionOptions(collectionId: number) {1137 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1138 }11391140 114111421143114411451146114711481149 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1150 const result = await this.helper.executeExtrinsic(1151 signer,1152 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1153 true,1154 );11551156 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1157 }11581159 11601161116211631164116511661167116811691170 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1171 const result = await this.helper.executeExtrinsic(1172 signer,1173 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1174 true, 1175 );11761177 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1178 }11791180 1181118211831184118511861187118811891190119111921193 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1194 const result = await this.helper.executeExtrinsic(1195 signer,1196 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1197 true, 1198 );1199 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1200 }12011202 12031204120512061207120812091210121112121213 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1214 const burnResult = await this.helper.executeExtrinsic(1215 signer,1216 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1217 true, 1218 );1219 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1220 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1221 return burnedTokens.success;1222 }12231224 12251226122712281229123012311232123312341235 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1236 const burnResult = await this.helper.executeExtrinsic(1237 signer,1238 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1239 true, 1240 );1241 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1242 return burnedTokens.success && burnedTokens.tokens.length > 0;1243 }12441245 1246124712481249125012511252125312541255 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1256 const approveResult = await this.helper.executeExtrinsic(1257 signer,1258 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1259 true, 1260 );12611262 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1263 }12641265 12661267126812691270127112721273127412751276 async approveTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1277 const approveResult = await this.helper.executeExtrinsic(1278 signer,1279 'api.tx.unique.approveFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1280 true, 1281 );12821283 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1284 }12851286 1287128812891290129112921293129412951296 async approveTokenFromEth(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1297 const ethMirror = CrossAccountId.fromKeyring(signer).toEthereum();1298 return await this.approveTokenFrom(signer, collectionId, tokenId, ethMirror, toAddressObj, amount);1299 }13001301 1302130313041305130613071308130913101311 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1312 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1313 }13141315 1316131713181319132013211322 async getLastTokenId(collectionId: number): Promise<number> {1323 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1324 }13251326 13271328132913301331133213331334 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1335 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1336 }1337}13381339class NFTnRFT extends CollectionGroup {1340 13411342134313441345134613471348 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1349 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1350 }13511352 1353135413551356135713581359136013611362 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1363 properties: IProperty[];1364 owner: CrossAccountId;1365 normalizedOwner: CrossAccountId;1366 }| null> {1367 let tokenData;1368 if(typeof blockHashAt === 'undefined') {1369 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1370 }1371 else {1372 if(propertyKeys.length == 0) {1373 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1374 if(!collection) return null;1375 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1376 }1377 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1378 }1379 tokenData = tokenData.toHuman();1380 if (tokenData === null || tokenData.owner === null) return null;1381 const owner = {} as any;1382 for (const key of Object.keys(tokenData.owner)) {1383 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1384 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1385 : tokenData.owner[key];1386 }1387 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1388 return tokenData;1389 }13901391 13921393139413951396139713981399140014011402 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1403 const result = await this.helper.executeExtrinsic(1404 signer,1405 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1406 true,1407 );14081409 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1410 }14111412 14131414141514161417141814191420 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1421 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1422 }14231424 1425142614271428142914301431143214331434 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1435 const result = await this.helper.executeExtrinsic(1436 signer,1437 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1438 true,1439 );14401441 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1442 }14431444 144514461447144814491450145114521453 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1454 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1455 }14561457 145814591460146114621463146414651466 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1467 const result = await this.helper.executeExtrinsic(1468 signer,1469 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1470 true,1471 );14721473 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1474 }14751476 147714781479148014811482148314841485 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1486 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1487 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1488 for (const key of ['name', 'description', 'tokenPrefix']) {1489 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);1490 }1491 const creationResult = await this.helper.executeExtrinsic(1492 signer,1493 'api.tx.unique.createCollectionEx', [collectionOptions],1494 true, 1495 );1496 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1497 }14981499 getCollectionObject(_collectionId: number): any {1500 return null;1501 }15021503 getTokenObject(_collectionId: number, _tokenId: number): any {1504 return null;1505 }15061507 1508150915101511151215131514 async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1515 return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1516 }15171518 151915201521152215231524 async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1525 const result = await this.helper.executeExtrinsic(1526 signer,1527 'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1528 true,1529 );1530 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1531 }1532}153315341535class NFTGroup extends NFTnRFT {1536 153715381539154015411542 getCollectionObject(collectionId: number): UniqueNFTCollection {1543 return new UniqueNFTCollection(collectionId, this.helper);1544 }15451546 1547154815491550155115521553 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1554 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1555 }15561557 15581559156015611562156315641565 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1566 let owner;1567 if (typeof blockHashAt === 'undefined') {1568 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1569 } else {1570 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1571 }1572 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1573 }15741575 1576157715781579158015811582 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1583 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1584 }15851586 1587158815891590159115921593159415951596 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1597 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1598 }15991600 160116021603160416051606160716081609161016111612 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1613 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1614 }16151616 16171618161916201621162216231624 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1625 let owner;1626 if (typeof blockHashAt === 'undefined') {1627 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1628 } else {1629 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1630 }16311632 if (owner === null) return null;16331634 return owner.toHuman();1635 }16361637 16381639164016411642164316441645 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1646 let children;1647 if(typeof blockHashAt === 'undefined') {1648 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1649 } else {1650 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1651 }16521653 return children.toJSON().map((x: any) => {1654 return {collectionId: x.collection, tokenId: x.token};1655 });1656 }16571658 16591660166116621663166416651666 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1667 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1668 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1669 if(!result) {1670 throw Error('Unable to nest token!');1671 }1672 return result;1673 }16741675 167616771678167916801681168216831684 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1685 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1686 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1687 if(!result) {1688 throw Error('Unable to unnest token!');1689 }1690 return result;1691 }16921693 169416951696169716981699170017011702170317041705 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1706 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1707 }17081709 171017111712171317141715 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1716 const creationResult = await this.helper.executeExtrinsic(1717 signer,1718 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1719 nft: {1720 properties: data.properties,1721 },1722 }],1723 true,1724 );1725 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1726 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1727 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1728 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1729 }17301731 173217331734173517361737173817391740174117421743174417451746 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1747 const creationResult = await this.helper.executeExtrinsic(1748 signer,1749 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1750 true,1751 );1752 const collection = this.getCollectionObject(collectionId);1753 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1754 }17551756 175717581759176017611762176317641765176617671768176917701771177217731774 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1775 const rawTokens = [];1776 for (const token of tokens) {1777 const raw = {NFT: {properties: token.properties}};1778 rawTokens.push(raw);1779 }1780 const creationResult = await this.helper.executeExtrinsic(1781 signer,1782 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1783 true,1784 );1785 const collection = this.getCollectionObject(collectionId);1786 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1787 }17881789 1790179117921793179417951796179717981799 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1800 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1801 }1802}180318041805class RFTGroup extends NFTnRFT {1806 180718081809181018111812 getCollectionObject(collectionId: number): UniqueRFTCollection {1813 return new UniqueRFTCollection(collectionId, this.helper);1814 }18151816 1817181818191820182118221823 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1824 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1825 }18261827 1828182918301831183218331834 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1835 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1836 }18371838 18391840184118421843184418451846 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1847 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1848 }18491850 1851185218531854185518561857185818591860 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1861 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1862 }18631864 18651866186718681869187018711872187318741875 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1876 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1877 }18781879 188018811882188318841885188618871888188918901891 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1892 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1893 }18941895 1896189718981899190019011902 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1903 const creationResult = await this.helper.executeExtrinsic(1904 signer,1905 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1906 refungible: {1907 pieces: data.pieces,1908 properties: data.properties,1909 },1910 }],1911 true,1912 );1913 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1914 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1915 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1916 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1917 }19181919 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1920 throw Error('Not implemented');1921 const creationResult = await this.helper.executeExtrinsic(1922 signer,1923 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1924 true, 1925 );1926 const collection = this.getCollectionObject(collectionId);1927 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1928 }19291930 193119321933193419351936193719381939 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1940 const rawTokens = [];1941 for (const token of tokens) {1942 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1943 rawTokens.push(raw);1944 }1945 const creationResult = await this.helper.executeExtrinsic(1946 signer,1947 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1948 true,1949 );1950 const collection = this.getCollectionObject(collectionId);1951 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1952 }19531954 195519561957195819591960196119621963 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1964 return await super.burnToken(signer, collectionId, tokenId, amount);1965 }19661967 1968196919701971197219731974197519761977 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1978 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1979 }19801981 19821983198419851986198719881989199019911992 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1993 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1994 }19951996 1997199819992000200120022003 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {2004 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();2005 }20062007 200820092010201120122013201420152016 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {2017 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);2018 const repartitionResult = await this.helper.executeExtrinsic(2019 signer,2020 'api.tx.unique.repartition', [collectionId, tokenId, amount],2021 true,2022 );2023 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');2024 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');2025 }2026}202720282029class FTGroup extends CollectionGroup {2030 203120322033203420352036 getCollectionObject(collectionId: number): UniqueFTCollection {2037 return new UniqueFTCollection(collectionId, this.helper);2038 }20392040 2041204220432044204520462047204820492050205120522053 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {2054 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 2055 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');2056 collectionOptions.mode = {fungible: decimalPoints};2057 for (const key of ['name', 'description', 'tokenPrefix']) {2058 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);2059 }2060 const creationResult = await this.helper.executeExtrinsic(2061 signer,2062 'api.tx.unique.createCollectionEx', [collectionOptions],2063 true,2064 );2065 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2066 }20672068 206920702071207220732074207520762077 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2078 const creationResult = await this.helper.executeExtrinsic(2079 signer,2080 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2081 fungible: {2082 value: amount,2083 },2084 }],2085 true, 2086 );2087 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2088 }20892090 20912092209320942095209620972098 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {2099 const rawTokens = [];2100 for (const token of tokens) {2101 const raw = {Fungible: {Value: token.value}};2102 rawTokens.push(raw);2103 }2104 const creationResult = await this.helper.executeExtrinsic(2105 signer,2106 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2107 true,2108 );2109 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2110 }21112112 211321142115211621172118 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2119 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2120 }21212122 2123212421252126212721282129 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2130 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2131 }21322133 213421352136213721382139214021412142 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2143 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2144 }21452146 2147214821492150215121522153215421552156 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2157 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2158 }21592160 21612162216321642165216621672168 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2169 return await super.burnToken(signer, collectionId, 0, amount);2170 }21712172 217321742175217621772178217921802181 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2182 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2183 }21842185 21862187218821892190 async getTotalPieces(collectionId: number): Promise<bigint> {2191 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2192 }21932194 2195219621972198219922002201220222032204 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2205 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2206 }22072208 2209221022112212221322142215 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2216 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2217 }2218}221922202221class ChainGroup extends HelperGroup<ChainHelperBase> {2222 22232224222522262227 getChainProperties(): IChainProperties {2228 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2229 return {2230 ss58Format: properties.ss58Format.toJSON(),2231 tokenDecimals: properties.tokenDecimals.toJSON(),2232 tokenSymbol: properties.tokenSymbol.toJSON(),2233 };2234 }22352236 22372238223922402241 async getLatestBlockNumber(): Promise<number> {2242 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2243 }22442245 224622472248224922502251 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2252 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2253 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2254 return blockHash;2255 }22562257 2258 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2259 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2260 if (!blockHash) return null;2261 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2262 }22632264 2265226622672268 async getRelayBlockNumber(): Promise<bigint> {2269 const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2270 return BigInt(blockNumber);2271 }22722273 227422752276227722782279 async getNonce(address: TSubstrateAccount): Promise<number> {2280 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2281 }2282}22832284class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2285 228622872288228922902291 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2292 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2293 }22942295 22962297229822992300230123022303 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2304 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);23052306 let transfer = {from: null, to: null, amount: 0n} as any;2307 result.result.events.forEach(({event: {data, method, section}}) => {2308 if ((section === 'balances') && (method === 'Transfer')) {2309 transfer = {2310 from: this.helper.address.normalizeSubstrate(data[0]),2311 to: this.helper.address.normalizeSubstrate(data[1]),2312 amount: BigInt(data[2]),2313 };2314 }2315 });2316 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2317 && this.helper.address.normalizeSubstrate(address) === transfer.to2318 && BigInt(amount) === transfer.amount;2319 return isSuccess;2320 }23212322 23232324232523262327 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2328 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2329 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2330 }23312332 async getLocked(address: TSubstrateAccount): Promise<[{id: string, amount: bigint, reason: string}]> {2333 const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2334 return locks.map((lock: any) => {return {id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons};});2335 }2336}23372338class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2339 234023412342234323442345 async getEthereum(address: TEthereumAccount): Promise<bigint> {2346 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2347 }23482349 23502351235223532354235523562357 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2358 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);23592360 let transfer = {from: null, to: null, amount: 0n} as any;2361 result.result.events.forEach(({event: {data, method, section}}) => {2362 if ((section === 'balances') && (method === 'Transfer')) {2363 transfer = {2364 from: data[0].toString(),2365 to: data[1].toString(),2366 amount: BigInt(data[2]),2367 };2368 }2369 });2370 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2371 && address === transfer.to2372 && BigInt(amount) === transfer.amount;2373 return isSuccess;2374 }2375}23762377class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2378 subBalanceGroup: SubstrateBalanceGroup<T>;2379 ethBalanceGroup: EthereumBalanceGroup<T>;23802381 constructor(helper: T) {2382 super(helper);2383 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2384 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2385 }23862387 getCollectionCreationPrice(): bigint {2388 return 2n * this.getOneTokenNominal();2389 }2390 23912392239323942395 getOneTokenNominal(): bigint {2396 const chainProperties = this.helper.chain.getChainProperties();2397 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2398 }23992400 240124022403240424052406 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2407 return this.subBalanceGroup.getSubstrate(address);2408 }24092410 24112412241324142415 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2416 return this.subBalanceGroup.getSubstrateFull(address);2417 }24182419 24202421242224232424 getLocked(address: TSubstrateAccount) {2425 return this.subBalanceGroup.getLocked(address);2426 }24272428 242924302431243224332434 getEthereum(address: TEthereumAccount): Promise<bigint> {2435 return this.ethBalanceGroup.getEthereum(address);2436 }24372438 24392440244124422443244424452446 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2447 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2448 }24492450 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2451 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);24522453 let transfer = {from: null, to: null, amount: 0n} as any;2454 result.result.events.forEach(({event: {data, method, section}}) => {2455 if ((section === 'balances') && (method === 'Transfer')) {2456 transfer = {2457 from: this.helper.address.normalizeSubstrate(data[0]),2458 to: this.helper.address.normalizeSubstrate(data[1]),2459 amount: BigInt(data[2]),2460 };2461 }2462 });2463 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2464 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2465 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2466 return isSuccess;2467 }24682469 2470247124722473247424752476 async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: {start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}): Promise<void> {2477 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2478 const event = result.result.events2479 .find(e => e.event.section === 'vesting' &&2480 e.event.method === 'VestingScheduleAdded' &&2481 e.event.data[0].toHuman() === signer.address);2482 if (!event) throw Error('Cannot find transfer in events');2483 }24842485 24862487248824892490 async getVestingSchedules(address: TSubstrateAccount): Promise<{start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}[]> {2491 const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2492 return schedule.map((schedule: any) => {2493 return {2494 start: BigInt(schedule.start),2495 period: BigInt(schedule.period),2496 periodCount: BigInt(schedule.periodCount),2497 perPeriod: BigInt(schedule.perPeriod),2498 };2499 });2500 }25012502 2503250425052506 async claim(signer: TSigner) {2507 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2508 const event = result.result.events2509 .find(e => e.event.section === 'vesting' &&2510 e.event.method === 'Claimed' &&2511 e.event.data[0].toHuman() === signer.address);2512 if (!event) throw Error('Cannot find claim in events');2513 }2514}25152516class AddressGroup extends HelperGroup<ChainHelperBase> {2517 2518251925202521252225232524 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2525 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2526 }25272528 252925302531253225332534 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2535 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2536 }25372538 2539254025412542254325442545 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2546 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2547 }25482549 255025512552255325542555 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2556 return CrossAccountId.translateSubToEth(subAddress);2557 }25582559 256025612562256325642565 encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2566 const u8a :Uint8Array = typeof key === 'string'2567 ? hexToU8a(key)2568 : typeof key === 'bigint'2569 ? hexToU8a(key.toString(16))2570 : key;25712572 if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2573 throw new Error(`ss58Format is not valid, received ${typeof ss58Format} "${ss58Format}"`);2574 }25752576 const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2577 if (!allowedDecodedLengths.includes(u8a.length)) {2578 throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2579 }25802581 const u8aPrefix = ss58Format < 642582 ? new Uint8Array([ss58Format])2583 : new Uint8Array([2584 ((ss58Format & 0xfc) >> 2) | 0x40,2585 (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2586 ]);25872588 const input = u8aConcat(u8aPrefix, u8a);25892590 return base58Encode(u8aConcat(2591 input,2592 blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2593 ));2594 }25952596 25972598259926002601 restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2602 if (this.helper.api === null) {2603 throw 'Not connected';2604 }2605 const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2606 if (res === undefined || res === null) {2607 throw 'Restore address error';2608 }2609 return res.toString();2610 }26112612 26132614261526162617 convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2618 if (ethCrossAccount.sub === '0') {2619 return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2620 }26212622 const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2623 return {Substrate: ss58};2624 }26252626 paraSiblingSovereignAccount(paraid: number) {2627 2628 2629 const siblingPrefix = '0x7369626c';26302631 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2632 const suffix = '000000000000000000000000000000000000000000000000';26332634 return siblingPrefix + encodedParaId + suffix;2635 }2636}26372638class StakingGroup extends HelperGroup<UniqueHelper> {2639 2640264126422643264426452646 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2647 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2648 const _stakeResult = await this.helper.executeExtrinsic(2649 signer, 'api.tx.appPromotion.stake',2650 [amountToStake], true,2651 );2652 2653 return true;2654 }26552656 2657265826592660266126622663 async unstake(signer: TSigner, label?: string): Promise<number> {2664 if(typeof label === 'undefined') label = `${signer.address}`;2665 const _unstakeResult = await this.helper.executeExtrinsic(2666 signer, 'api.tx.appPromotion.unstake',2667 [], true,2668 );2669 2670 return 1;2671 }26722673 26742675267626772678 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2679 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2680 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2681 }26822683 26842685268626872688 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2689 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2690 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2691 return {2692 block: block.toBigInt(),2693 amount: amount.toBigInt(),2694 };2695 });2696 }26972698 26992700270127022703 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2704 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2705 }27062707 27082709271027112712 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2713 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2714 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2715 return {2716 block: block.toBigInt(),2717 amount: amount.toBigInt(),2718 };2719 });2720 return result;2721 }2722}27232724class SchedulerGroup extends HelperGroup<UniqueHelper> {2725 constructor(helper: UniqueHelper) {2726 super(helper);2727 }27282729 cancelScheduled(signer: TSigner, scheduledId: string) {2730 return this.helper.executeExtrinsic(2731 signer,2732 'api.tx.scheduler.cancelNamed',2733 [scheduledId],2734 true,2735 );2736 }27372738 changePriority(signer: TSigner, scheduledId: string, priority: number) {2739 return this.helper.executeExtrinsic(2740 signer,2741 'api.tx.scheduler.changeNamedPriority',2742 [scheduledId, priority],2743 true,2744 );2745 }27462747 scheduleAt<T extends UniqueHelper>(2748 executionBlockNumber: number,2749 options: ISchedulerOptions = {},2750 ) {2751 return this.schedule<T>('schedule', executionBlockNumber, options);2752 }27532754 scheduleAfter<T extends UniqueHelper>(2755 blocksBeforeExecution: number,2756 options: ISchedulerOptions = {},2757 ) {2758 return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2759 }27602761 schedule<T extends UniqueHelper>(2762 scheduleFn: 'schedule' | 'scheduleAfter',2763 blocksNum: number,2764 options: ISchedulerOptions = {},2765 ) {2766 2767 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2768 return this.helper.clone(ScheduledHelperType, {2769 scheduleFn,2770 blocksNum,2771 options,2772 }) as T;2773 }2774}27752776class CollatorSelectionGroup extends HelperGroup<UniqueHelper> {2777 2778 addInvulnerable(signer: TSigner, address: string) {2779 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.addInvulnerable', [address]);2780 }27812782 removeInvulnerable(signer: TSigner, address: string) {2783 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.removeInvulnerable', [address]);2784 }27852786 async getInvulnerables(): Promise<string[]> {2787 return (await this.helper.callRpc('api.query.collatorSelection.invulnerables')).map((x: any) => x.toHuman());2788 }27892790 2791 maxCollators(): number {2792 return (this.helper.getApi().consts.configuration.defaultCollatorSelectionMaxCollators.toJSON() as number);2793 }27942795 async getDesiredCollators(): Promise<number> {2796 return (await this.helper.callRpc('api.query.configuration.collatorSelectionDesiredCollatorsOverride')).toNumber();2797 }27982799 setLicenseBond(signer: TSigner, amount: bigint) {2800 return this.helper.executeExtrinsic(signer, 'api.tx.configuration.setCollatorSelectionLicenseBond', [amount]);2801 }28022803 async getLicenseBond(): Promise<bigint> {2804 return (await this.helper.callRpc('api.query.configuration.collatorSelectionLicenseBondOverride')).toBigInt();2805 }28062807 obtainLicense(signer: TSigner) {2808 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.getLicense', []);2809 }28102811 releaseLicense(signer: TSigner) {2812 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.releaseLicense', []);2813 }28142815 forceReleaseLicense(signer: TSigner, released: string) {2816 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.forceReleaseLicense', [released]);2817 }28182819 async hasLicense(address: string): Promise<bigint> {2820 return (await this.helper.callRpc('api.query.collatorSelection.licenseDepositOf', [address])).toBigInt();2821 }28222823 onboard(signer: TSigner) {2824 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.onboard', []);2825 }28262827 offboard(signer: TSigner) {2828 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.offboard', []);2829 }28302831 async getCandidates(): Promise<string[]> {2832 return (await this.helper.callRpc('api.query.collatorSelection.candidates')).map((x: any) => x.toHuman());2833 }2834}28352836class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2837 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2838 await this.helper.executeExtrinsic(2839 signer,2840 'api.tx.foreignAssets.registerForeignAsset',2841 [ownerAddress, location, metadata],2842 true,2843 );2844 }28452846 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2847 await this.helper.executeExtrinsic(2848 signer,2849 'api.tx.foreignAssets.updateForeignAsset',2850 [foreignAssetId, location, metadata],2851 true,2852 );2853 }2854}28552856class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2857 palletName: string;28582859 constructor(helper: T, palletName: string) {2860 super(helper);28612862 this.palletName = palletName;2863 }28642865 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {2866 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);2867 }28682869 async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {2870 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);2871 }28722873 async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint) {2874 const destination = {2875 V1: {2876 parents: 0,2877 interior: {2878 X1: {2879 Parachain: destinationParaId,2880 },2881 },2882 },2883 };28842885 const beneficiary = {2886 V1: {2887 parents: 0,2888 interior: {2889 X1: {2890 AccountId32: {2891 network: 'Any',2892 id: targetAccount,2893 },2894 },2895 },2896 },2897 };28982899 const assets = {2900 V1: [2901 {2902 id: {2903 Concrete: {2904 parents: 0,2905 interior: 'Here',2906 },2907 },2908 fun: {2909 Fungible: amount,2910 },2911 },2912 ],2913 };29142915 const feeAssetItem = 0;29162917 await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);2918 }2919}29202921class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2922 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {2923 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2924 }29252926 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {2927 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2928 }29292930 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {2931 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2932 }2933}29342935class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2936 async accounts(address: string, currencyId: any) {2937 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2938 return BigInt(free);2939 }2940}29412942class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2943 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2944 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2945 }29462947 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2948 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2949 }29502951 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2952 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2953 }29542955 async account(assetId: string | number, address: string) {2956 const accountAsset = (2957 await this.helper.callRpc('api.query.assets.account', [assetId, address])2958 ).toJSON()! as any;29592960 if (accountAsset !== null) {2961 return BigInt(accountAsset['balance']);2962 } else {2963 return null;2964 }2965 }2966}29672968class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2969 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2970 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2971 }2972}29732974class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2975 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2976 const apiPrefix = 'api.tx.assetManager.';29772978 const registerTx = this.helper.constructApiCall(2979 apiPrefix + 'registerForeignAsset',2980 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2981 );29822983 const setUnitsTx = this.helper.constructApiCall(2984 apiPrefix + 'setAssetUnitsPerSecond',2985 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2986 );29872988 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2989 const encodedProposal = batchCall?.method.toHex() || '';2990 return encodedProposal;2991 }29922993 async assetTypeId(location: any) {2994 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2995 }2996}29972998class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2999 notePreimagePallet: string;30003001 constructor(helper: MoonbeamHelper, options: {[key: string]: any} = {}) {3002 super(helper);3003 this.notePreimagePallet = options.notePreimagePallet;3004 }30053006 async notePreimage(signer: TSigner, encodedProposal: string) {3007 await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);3008 }30093010 externalProposeMajority(proposal: any) {3011 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);3012 }30133014 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {3015 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);3016 }30173018 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {3019 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);3020 }3021}30223023class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {3024 collective: string;30253026 constructor(helper: MoonbeamHelper, collective: string) {3027 super(helper);30283029 this.collective = collective;3030 }30313032 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {3033 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);3034 }30353036 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {3037 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);3038 }30393040 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {3041 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);3042 }30433044 async proposalCount() {3045 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));3046 }3047}30483049export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;3050export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;30513052export class UniqueHelper extends ChainHelperBase {3053 balance: BalanceGroup<UniqueHelper>;3054 collection: CollectionGroup;3055 nft: NFTGroup;3056 rft: RFTGroup;3057 ft: FTGroup;3058 staking: StakingGroup;3059 scheduler: SchedulerGroup;3060 collatorSelection: CollatorSelectionGroup;3061 foreignAssets: ForeignAssetsGroup;3062 xcm: XcmGroup<UniqueHelper>;3063 xTokens: XTokensGroup<UniqueHelper>;3064 tokens: TokensGroup<UniqueHelper>;30653066 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3067 super(logger, options.helperBase ?? UniqueHelper);30683069 this.balance = new BalanceGroup(this);3070 this.collection = new CollectionGroup(this);3071 this.nft = new NFTGroup(this);3072 this.rft = new RFTGroup(this);3073 this.ft = new FTGroup(this);3074 this.staking = new StakingGroup(this);3075 this.scheduler = new SchedulerGroup(this);3076 this.collatorSelection = new CollatorSelectionGroup(this);3077 this.foreignAssets = new ForeignAssetsGroup(this);3078 this.xcm = new XcmGroup(this, 'polkadotXcm');3079 this.xTokens = new XTokensGroup(this);3080 this.tokens = new TokensGroup(this);3081 }30823083 getSudo<T extends UniqueHelper>() {3084 3085 const SudoHelperType = SudoHelper(this.helperBase);3086 return this.clone(SudoHelperType) as T;3087 }3088}30893090export class XcmChainHelper extends ChainHelperBase {3091 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {3092 const wsProvider = new WsProvider(wsEndpoint);3093 this.api = new ApiPromise({3094 provider: wsProvider,3095 });3096 await this.api.isReadyOrError;3097 this.network = await UniqueHelper.detectNetwork(this.api);3098 }3099}31003101export class RelayHelper extends XcmChainHelper {3102 balance: SubstrateBalanceGroup<RelayHelper>;3103 xcm: XcmGroup<RelayHelper>;31043105 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3106 super(logger, options.helperBase ?? RelayHelper);31073108 this.balance = new SubstrateBalanceGroup(this);3109 this.xcm = new XcmGroup(this, 'xcmPallet');3110 }3111}31123113export class WestmintHelper extends XcmChainHelper {3114 balance: SubstrateBalanceGroup<WestmintHelper>;3115 xcm: XcmGroup<WestmintHelper>;3116 assets: AssetsGroup<WestmintHelper>;3117 xTokens: XTokensGroup<WestmintHelper>;31183119 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3120 super(logger, options.helperBase ?? WestmintHelper);31213122 this.balance = new SubstrateBalanceGroup(this);3123 this.xcm = new XcmGroup(this, 'polkadotXcm');3124 this.assets = new AssetsGroup(this);3125 this.xTokens = new XTokensGroup(this);3126 }3127}31283129export class MoonbeamHelper extends XcmChainHelper {3130 balance: EthereumBalanceGroup<MoonbeamHelper>;3131 assetManager: MoonbeamAssetManagerGroup;3132 assets: AssetsGroup<MoonbeamHelper>;3133 xTokens: XTokensGroup<MoonbeamHelper>;3134 democracy: MoonbeamDemocracyGroup;3135 collective: {3136 council: MoonbeamCollectiveGroup,3137 techCommittee: MoonbeamCollectiveGroup,3138 };31393140 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3141 super(logger, options.helperBase ?? MoonbeamHelper);31423143 this.balance = new EthereumBalanceGroup(this);3144 this.assetManager = new MoonbeamAssetManagerGroup(this);3145 this.assets = new AssetsGroup(this);3146 this.xTokens = new XTokensGroup(this);3147 this.democracy = new MoonbeamDemocracyGroup(this, options);3148 this.collective = {3149 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),3150 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),3151 };3152 }3153}31543155export class AcalaHelper extends XcmChainHelper {3156 balance: SubstrateBalanceGroup<AcalaHelper>;3157 assetRegistry: AcalaAssetRegistryGroup;3158 xTokens: XTokensGroup<AcalaHelper>;3159 tokens: TokensGroup<AcalaHelper>;31603161 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3162 super(logger, options.helperBase ?? AcalaHelper);31633164 this.balance = new SubstrateBalanceGroup(this);3165 this.assetRegistry = new AcalaAssetRegistryGroup(this);3166 this.xTokens = new XTokensGroup(this);3167 this.tokens = new TokensGroup(this);3168 }31693170 getSudo<T extends AcalaHelper>() {3171 3172 const SudoHelperType = SudoHelper(this.helperBase);3173 return this.clone(SudoHelperType) as T;3174 }3175}317631773178function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3179 return class extends Base {3180 scheduleFn: 'schedule' | 'scheduleAfter';3181 blocksNum: number;3182 options: ISchedulerOptions;31833184 constructor(...args: any[]) {3185 const logger = args[0] as ILogger;3186 const options = args[1] as {3187 scheduleFn: 'schedule' | 'scheduleAfter',3188 blocksNum: number,3189 options: ISchedulerOptions3190 };31913192 super(logger);31933194 this.scheduleFn = options.scheduleFn;3195 this.blocksNum = options.blocksNum;3196 this.options = options.options;3197 }31983199 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3200 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);32013202 const mandatorySchedArgs = [3203 this.blocksNum,3204 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3205 this.options.priority ?? null,3206 scheduledTx,3207 ];32083209 let schedArgs;3210 let scheduleFn;32113212 if (this.options.scheduledId) {3213 schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];32143215 if (this.scheduleFn == 'schedule') {3216 scheduleFn = 'scheduleNamed';3217 } else if (this.scheduleFn == 'scheduleAfter') {3218 scheduleFn = 'scheduleNamedAfter';3219 }3220 } else {3221 schedArgs = mandatorySchedArgs;3222 scheduleFn = this.scheduleFn;3223 }32243225 const extrinsic = 'api.tx.scheduler.' + scheduleFn;32263227 return super.executeExtrinsic(3228 sender,3229 extrinsic,3230 schedArgs,3231 expectSuccess,3232 );3233 }3234 };3235}323632373238function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3239 return class extends Base {3240 constructor(...args: any[]) {3241 super(...args);3242 }32433244 async executeExtrinsic(3245 sender: IKeyringPair,3246 extrinsic: string,3247 params: any[],3248 expectSuccess?: boolean,3249 options: Partial<SignerOptions>|null = null,3250 ): Promise<ITransactionResult> {3251 const call = this.constructApiCall(extrinsic, params);3252 const result = await super.executeExtrinsic(3253 sender,3254 'api.tx.sudo.sudo',3255 [call],3256 expectSuccess,3257 options,3258 );32593260 if (result.status === 'Fail') return result;32613262 const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;3263 if (data.isErr) {3264 if (data.asErr.isModule) {3265 const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;3266 const metaError = super.getApi()?.registry.findMetaError(error);3267 throw new Error(`${metaError.section}.${metaError.name}`);3268 } else {3269 throw new Error(data.asErr.toHuman());3270 }3271 }3272 return result;3273 }3274 };3275}32763277export class UniqueBaseCollection {3278 helper: UniqueHelper;3279 collectionId: number;32803281 constructor(collectionId: number, uniqueHelper: UniqueHelper) {3282 this.collectionId = collectionId;3283 this.helper = uniqueHelper;3284 }32853286 async getData() {3287 return await this.helper.collection.getData(this.collectionId);3288 }32893290 async getLastTokenId() {3291 return await this.helper.collection.getLastTokenId(this.collectionId);3292 }32933294 async doesTokenExist(tokenId: number) {3295 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3296 }32973298 async getAdmins() {3299 return await this.helper.collection.getAdmins(this.collectionId);3300 }33013302 async getAllowList() {3303 return await this.helper.collection.getAllowList(this.collectionId);3304 }33053306 async getEffectiveLimits() {3307 return await this.helper.collection.getEffectiveLimits(this.collectionId);3308 }33093310 async getProperties(propertyKeys?: string[] | null) {3311 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3312 }33133314 async getPropertiesConsumedSpace() {3315 return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3316 }33173318 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3319 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3320 }33213322 async getOptions() {3323 return await this.helper.collection.getCollectionOptions(this.collectionId);3324 }33253326 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3327 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3328 }33293330 async confirmSponsorship(signer: TSigner) {3331 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3332 }33333334 async removeSponsor(signer: TSigner) {3335 return await this.helper.collection.removeSponsor(signer, this.collectionId);3336 }33373338 async setLimits(signer: TSigner, limits: ICollectionLimits) {3339 return await this.helper.collection.setLimits(signer, this.collectionId, limits);3340 }33413342 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3343 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3344 }33453346 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3347 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3348 }33493350 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3351 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3352 }33533354 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3355 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3356 }33573358 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3359 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3360 }33613362 async setProperties(signer: TSigner, properties: IProperty[]) {3363 return await this.helper.collection.setProperties(signer, this.collectionId, properties);3364 }33653366 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3367 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3368 }33693370 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3371 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3372 }33733374 async enableNesting(signer: TSigner, permissions: INestingPermissions) {3375 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3376 }33773378 async disableNesting(signer: TSigner) {3379 return await this.helper.collection.disableNesting(signer, this.collectionId);3380 }33813382 async burn(signer: TSigner) {3383 return await this.helper.collection.burn(signer, this.collectionId);3384 }33853386 scheduleAt<T extends UniqueHelper>(3387 executionBlockNumber: number,3388 options: ISchedulerOptions = {},3389 ) {3390 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3391 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3392 }33933394 scheduleAfter<T extends UniqueHelper>(3395 blocksBeforeExecution: number,3396 options: ISchedulerOptions = {},3397 ) {3398 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3399 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3400 }34013402 getSudo<T extends UniqueHelper>() {3403 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3404 }3405}340634073408export class UniqueNFTCollection extends UniqueBaseCollection {3409 getTokenObject(tokenId: number) {3410 return new UniqueNFToken(tokenId, this);3411 }34123413 async getTokensByAddress(addressObj: ICrossAccountId) {3414 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3415 }34163417 async getToken(tokenId: number, blockHashAt?: string) {3418 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3419 }34203421 async getTokenOwner(tokenId: number, blockHashAt?: string) {3422 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3423 }34243425 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3426 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3427 }34283429 async getTokenChildren(tokenId: number, blockHashAt?: string) {3430 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3431 }34323433 async getPropertyPermissions(propertyKeys: string[] | null = null) {3434 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3435 }34363437 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3438 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3439 }34403441 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3442 const api = this.helper.getApi();3443 const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();34443445 return (props! as any).consumedSpace;3446 }34473448 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3449 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3450 }34513452 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3453 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3454 }34553456 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3457 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3458 }34593460 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3461 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3462 }34633464 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3465 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3466 }34673468 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3469 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3470 }34713472 async burnToken(signer: TSigner, tokenId: number) {3473 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3474 }34753476 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3477 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3478 }34793480 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3481 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3482 }34833484 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3485 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3486 }34873488 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3489 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3490 }34913492 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3493 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3494 }34953496 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3497 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3498 }34993500 scheduleAt<T extends UniqueHelper>(3501 executionBlockNumber: number,3502 options: ISchedulerOptions = {},3503 ) {3504 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3505 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3506 }35073508 scheduleAfter<T extends UniqueHelper>(3509 blocksBeforeExecution: number,3510 options: ISchedulerOptions = {},3511 ) {3512 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3513 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3514 }35153516 getSudo<T extends UniqueHelper>() {3517 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3518 }3519}352035213522export class UniqueRFTCollection extends UniqueBaseCollection {3523 getTokenObject(tokenId: number) {3524 return new UniqueRFToken(tokenId, this);3525 }35263527 async getToken(tokenId: number, blockHashAt?: string) {3528 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3529 }35303531 async getTokensByAddress(addressObj: ICrossAccountId) {3532 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3533 }35343535 async getTop10TokenOwners(tokenId: number) {3536 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3537 }35383539 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3540 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3541 }35423543 async getTokenTotalPieces(tokenId: number) {3544 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3545 }35463547 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3548 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3549 }35503551 async getPropertyPermissions(propertyKeys: string[] | null = null) {3552 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3553 }35543555 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3556 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3557 }35583559 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3560 const api = this.helper.getApi();3561 const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();35623563 return (props! as any).consumedSpace;3564 }35653566 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3567 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3568 }35693570 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3571 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3572 }35733574 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3575 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3576 }35773578 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3579 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3580 }35813582 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3583 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3584 }35853586 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3587 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3588 }35893590 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3591 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3592 }35933594 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3595 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3596 }35973598 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3599 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3600 }36013602 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3603 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3604 }36053606 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3607 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3608 }36093610 scheduleAt<T extends UniqueHelper>(3611 executionBlockNumber: number,3612 options: ISchedulerOptions = {},3613 ) {3614 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3615 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3616 }36173618 scheduleAfter<T extends UniqueHelper>(3619 blocksBeforeExecution: number,3620 options: ISchedulerOptions = {},3621 ) {3622 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3623 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3624 }36253626 getSudo<T extends UniqueHelper>() {3627 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3628 }3629}363036313632export class UniqueFTCollection extends UniqueBaseCollection {3633 async getBalance(addressObj: ICrossAccountId) {3634 return await this.helper.ft.getBalance(this.collectionId, addressObj);3635 }36363637 async getTotalPieces() {3638 return await this.helper.ft.getTotalPieces(this.collectionId);3639 }36403641 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3642 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3643 }36443645 async getTop10Owners() {3646 return await this.helper.ft.getTop10Owners(this.collectionId);3647 }36483649 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3650 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3651 }36523653 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3654 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3655 }36563657 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3658 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3659 }36603661 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3662 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3663 }36643665 async burnTokens(signer: TSigner, amount=1n) {3666 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3667 }36683669 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3670 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3671 }36723673 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3674 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3675 }36763677 scheduleAt<T extends UniqueHelper>(3678 executionBlockNumber: number,3679 options: ISchedulerOptions = {},3680 ) {3681 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3682 return new UniqueFTCollection(this.collectionId, scheduledHelper);3683 }36843685 scheduleAfter<T extends UniqueHelper>(3686 blocksBeforeExecution: number,3687 options: ISchedulerOptions = {},3688 ) {3689 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3690 return new UniqueFTCollection(this.collectionId, scheduledHelper);3691 }36923693 getSudo<T extends UniqueHelper>() {3694 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3695 }3696}369736983699export class UniqueBaseToken {3700 collection: UniqueNFTCollection | UniqueRFTCollection;3701 collectionId: number;3702 tokenId: number;37033704 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3705 this.collection = collection;3706 this.collectionId = collection.collectionId;3707 this.tokenId = tokenId;3708 }37093710 async getNextSponsored(addressObj: ICrossAccountId) {3711 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3712 }37133714 async getProperties(propertyKeys?: string[] | null) {3715 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3716 }37173718 async getTokenPropertiesConsumedSpace() {3719 return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3720 }37213722 async setProperties(signer: TSigner, properties: IProperty[]) {3723 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3724 }37253726 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3727 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3728 }37293730 async doesExist() {3731 return await this.collection.doesTokenExist(this.tokenId);3732 }37333734 nestingAccount() {3735 return this.collection.helper.util.getTokenAccount(this);3736 }37373738 scheduleAt<T extends UniqueHelper>(3739 executionBlockNumber: number,3740 options: ISchedulerOptions = {},3741 ) {3742 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3743 return new UniqueBaseToken(this.tokenId, scheduledCollection);3744 }37453746 scheduleAfter<T extends UniqueHelper>(3747 blocksBeforeExecution: number,3748 options: ISchedulerOptions = {},3749 ) {3750 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3751 return new UniqueBaseToken(this.tokenId, scheduledCollection);3752 }37533754 getSudo<T extends UniqueHelper>() {3755 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3756 }3757}375837593760export class UniqueNFToken extends UniqueBaseToken {3761 collection: UniqueNFTCollection;37623763 constructor(tokenId: number, collection: UniqueNFTCollection) {3764 super(tokenId, collection);3765 this.collection = collection;3766 }37673768 async getData(blockHashAt?: string) {3769 return await this.collection.getToken(this.tokenId, blockHashAt);3770 }37713772 async getOwner(blockHashAt?: string) {3773 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3774 }37753776 async getTopmostOwner(blockHashAt?: string) {3777 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3778 }37793780 async getChildren(blockHashAt?: string) {3781 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3782 }37833784 async nest(signer: TSigner, toTokenObj: IToken) {3785 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3786 }37873788 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3789 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3790 }37913792 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3793 return await this.collection.transferToken(signer, this.tokenId, addressObj);3794 }37953796 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3797 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3798 }37993800 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3801 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3802 }38033804 async isApproved(toAddressObj: ICrossAccountId) {3805 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3806 }38073808 async burn(signer: TSigner) {3809 return await this.collection.burnToken(signer, this.tokenId);3810 }38113812 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3813 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3814 }38153816 scheduleAt<T extends UniqueHelper>(3817 executionBlockNumber: number,3818 options: ISchedulerOptions = {},3819 ) {3820 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3821 return new UniqueNFToken(this.tokenId, scheduledCollection);3822 }38233824 scheduleAfter<T extends UniqueHelper>(3825 blocksBeforeExecution: number,3826 options: ISchedulerOptions = {},3827 ) {3828 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3829 return new UniqueNFToken(this.tokenId, scheduledCollection);3830 }38313832 getSudo<T extends UniqueHelper>() {3833 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3834 }3835}38363837export class UniqueRFToken extends UniqueBaseToken {3838 collection: UniqueRFTCollection;38393840 constructor(tokenId: number, collection: UniqueRFTCollection) {3841 super(tokenId, collection);3842 this.collection = collection;3843 }38443845 async getData(blockHashAt?: string) {3846 return await this.collection.getToken(this.tokenId, blockHashAt);3847 }38483849 async getTop10Owners() {3850 return await this.collection.getTop10TokenOwners(this.tokenId);3851 }38523853 async getBalance(addressObj: ICrossAccountId) {3854 return await this.collection.getTokenBalance(this.tokenId, addressObj);3855 }38563857 async getTotalPieces() {3858 return await this.collection.getTokenTotalPieces(this.tokenId);3859 }38603861 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3862 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3863 }38643865 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3866 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3867 }38683869 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3870 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3871 }38723873 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3874 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3875 }38763877 async repartition(signer: TSigner, amount: bigint) {3878 return await this.collection.repartitionToken(signer, this.tokenId, amount);3879 }38803881 async burn(signer: TSigner, amount=1n) {3882 return await this.collection.burnToken(signer, this.tokenId, amount);3883 }38843885 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3886 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3887 }38883889 scheduleAt<T extends UniqueHelper>(3890 executionBlockNumber: number,3891 options: ISchedulerOptions = {},3892 ) {3893 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3894 return new UniqueRFToken(this.tokenId, scheduledCollection);3895 }38963897 scheduleAfter<T extends UniqueHelper>(3898 blocksBeforeExecution: number,3899 options: ISchedulerOptions = {},3900 ) {3901 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3902 return new UniqueRFToken(this.tokenId, scheduledCollection);3903 }39043905 getSudo<T extends UniqueHelper>() {3906 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3907 }3908}