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 }637 return call(...params);638 }639640 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null) {641 if(this.api === null) throw Error('API not initialized');642 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);643644 const startTime = (new Date()).getTime();645 let result: ITransactionResult;646 let events: IEvent[] = [];647 try {648 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;649 events = this.eventHelper.extractEvents(result.result.events);650 }651 catch(e) {652 if(!(e as object).hasOwnProperty('status')) throw e;653 result = e as ITransactionResult;654 }655656 const endTime = (new Date()).getTime();657658 const log = {659 executedAt: endTime,660 executionTime: endTime - startTime,661 type: this.chainLogType.EXTRINSIC,662 status: result.status,663 call: extrinsic,664 signer: this.getSignerAddress(sender),665 params,666 } as IUniqueHelperLog;667668 if(result.status !== this.transactionStatus.SUCCESS) {669 if (result.moduleError) log.moduleError = result.moduleError;670 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;671 }672 if(events.length > 0) log.events = events;673674 this.chainLog.push(log);675676 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {677 if (result.moduleError) throw Error(`${result.moduleError}`);678 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));679 }680 return result;681 }682683 async callRpc(rpc: string, params?: any[]) {684 if(typeof params === 'undefined') params = [];685 if(this.api === null) throw Error('API not initialized');686 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);687688 const startTime = (new Date()).getTime();689 let result;690 let error = null;691 const log = {692 type: this.chainLogType.RPC,693 call: rpc,694 params,695 } as IUniqueHelperLog;696697 try {698 result = await this.constructApiCall(rpc, params);699 }700 catch(e) {701 error = e;702 }703704 const endTime = (new Date()).getTime();705706 log.executedAt = endTime;707 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';708 log.executionTime = endTime - startTime;709710 this.chainLog.push(log);711712 if(error !== null) throw error;713714 return result;715 }716717 getSignerAddress(signer: IKeyringPair | string): string {718 if(typeof signer === 'string') return signer;719 return signer.address;720 }721722 fetchAllPalletNames(): string[] {723 if(this.api === null) throw Error('API not initialized');724 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());725 }726727 fetchMissingPalletNames(requiredPallets: string[]): string[] {728 const palletNames = this.fetchAllPalletNames();729 return requiredPallets.filter(p => !palletNames.includes(p));730 }731}732733734class HelperGroup<T extends ChainHelperBase> {735 helper: T;736737 constructor(uniqueHelper: T) {738 this.helper = uniqueHelper;739 }740}741742743class CollectionGroup extends HelperGroup<UniqueHelper> {744 745746747748749750751752753 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {754 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();755 }756757 758759760761762 async getTotalCount(): Promise<number> {763 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();764 }765766 767768769770771772773774775 async getData(collectionId: number): Promise<{776 id: number;777 name: string;778 description: string;779 tokensCount: number;780 admins: CrossAccountId[];781 normalizedOwner: TSubstrateAccount;782 raw: any783 } | null> {784 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);785 const humanCollection = collection.toHuman(), collectionData = {786 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],787 raw: humanCollection,788 } as any, jsonCollection = collection.toJSON();789 if (humanCollection === null) return null;790 collectionData.raw.limits = jsonCollection.limits;791 collectionData.raw.permissions = jsonCollection.permissions;792 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);793 for (const key of ['name', 'description']) {794 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);795 }796797 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))798 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)799 : 0;800 collectionData.admins = await this.getAdmins(collectionId);801802 return collectionData;803 }804805 806807808809810811812813 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {814 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();815816 return normalize817 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())818 : admins;819 }820821 822823824825826827828 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {829 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();830 return normalize831 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())832 : allowListed;833 }834835 836837838839840841842 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {843 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();844 }845846 847848849850851852853854 async burn(signer: TSigner, collectionId: number): Promise<boolean> {855 const result = await this.helper.executeExtrinsic(856 signer,857 'api.tx.unique.destroyCollection', [collectionId],858 true,859 );860861 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');862 }863864 865866867868869870871872873 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {874 const result = await this.helper.executeExtrinsic(875 signer,876 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],877 true,878 );879880 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');881 }882883 884885886887888889890891 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {892 const result = await this.helper.executeExtrinsic(893 signer,894 'api.tx.unique.confirmSponsorship', [collectionId],895 true,896 );897898 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');899 }900901 902903904905906907908909 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {910 const result = await this.helper.executeExtrinsic(911 signer,912 'api.tx.unique.removeCollectionSponsor', [collectionId],913 true,914 );915916 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');917 }918919 920921922923924925926927928929930931932933934935936 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {937 const result = await this.helper.executeExtrinsic(938 signer,939 'api.tx.unique.setCollectionLimits', [collectionId, limits],940 true,941 );942943 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');944 }945946 947948949950951952953954955 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {956 const result = await this.helper.executeExtrinsic(957 signer,958 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],959 true,960 );961962 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');963 }964965 966967968969970971972973974 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {975 const result = await this.helper.executeExtrinsic(976 signer,977 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],978 true,979 );980981 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');982 }983984 985986987988989990991992993 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {994 const result = await this.helper.executeExtrinsic(995 signer,996 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],997 true,998 );9991000 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');1001 }10021003 10041005100610071008100910101011 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {1012 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();1013 }10141015 1016101710181019102010211022 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1023 const result = await this.helper.executeExtrinsic(1024 signer,1025 'api.tx.unique.addToAllowList', [collectionId, addressObj],1026 true,1027 );10281029 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1030 }10311032 10331034103510361037103810391040 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1041 const result = await this.helper.executeExtrinsic(1042 signer,1043 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1044 true,1045 );10461047 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1048 }10491050 105110521053105410551056105710581059 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1060 const result = await this.helper.executeExtrinsic(1061 signer,1062 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1063 true,1064 );10651066 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1067 }10681069 107010711072107310741075107610771078 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1079 return await this.setPermissions(signer, collectionId, {nesting: permissions});1080 }10811082 10831084108510861087108810891090 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1091 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1092 }10931094 109510961097109810991100110111021103 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1104 const result = await this.helper.executeExtrinsic(1105 signer,1106 'api.tx.unique.setCollectionProperties', [collectionId, properties],1107 true,1108 );11091110 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1111 }11121113 11141115111611171118111911201121 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1122 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1123 }11241125 async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1126 const api = this.helper.getApi();1127 const props = (await api.query.common.collectionProperties(collectionId)).toJSON();11281129 return (props! as any).consumedSpace;1130 }11311132 async getCollectionOptions(collectionId: number) {1133 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1134 }11351136 113711381139114011411142114311441145 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1146 const result = await this.helper.executeExtrinsic(1147 signer,1148 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1149 true,1150 );11511152 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1153 }11541155 11561157115811591160116111621163116411651166 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1167 const result = await this.helper.executeExtrinsic(1168 signer,1169 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1170 true, 1171 );11721173 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1174 }11751176 1177117811791180118111821183118411851186118711881189 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1190 const result = await this.helper.executeExtrinsic(1191 signer,1192 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1193 true, 1194 );1195 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1196 }11971198 11991200120112021203120412051206120712081209 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1210 const burnResult = await this.helper.executeExtrinsic(1211 signer,1212 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1213 true, 1214 );1215 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1216 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1217 return burnedTokens.success;1218 }12191220 12211222122312241225122612271228122912301231 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1232 const burnResult = await this.helper.executeExtrinsic(1233 signer,1234 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1235 true, 1236 );1237 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1238 return burnedTokens.success && burnedTokens.tokens.length > 0;1239 }12401241 1242124312441245124612471248124912501251 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1252 const approveResult = await this.helper.executeExtrinsic(1253 signer,1254 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1255 true, 1256 );12571258 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1259 }12601261 1262126312641265126612671268126912701271 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1272 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1273 }12741275 1276127712781279128012811282 async getLastTokenId(collectionId: number): Promise<number> {1283 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1284 }12851286 12871288128912901291129212931294 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1295 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1296 }1297}12981299class NFTnRFT extends CollectionGroup {1300 13011302130313041305130613071308 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1309 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1310 }13111312 1313131413151316131713181319132013211322 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1323 properties: IProperty[];1324 owner: CrossAccountId;1325 normalizedOwner: CrossAccountId;1326 }| null> {1327 let tokenData;1328 if(typeof blockHashAt === 'undefined') {1329 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1330 }1331 else {1332 if(propertyKeys.length == 0) {1333 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1334 if(!collection) return null;1335 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1336 }1337 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1338 }1339 tokenData = tokenData.toHuman();1340 if (tokenData === null || tokenData.owner === null) return null;1341 const owner = {} as any;1342 for (const key of Object.keys(tokenData.owner)) {1343 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1344 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1345 : tokenData.owner[key];1346 }1347 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1348 return tokenData;1349 }13501351 13521353135413551356135713581359136013611362 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1363 const result = await this.helper.executeExtrinsic(1364 signer,1365 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1366 true,1367 );13681369 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1370 }13711372 13731374137513761377137813791380 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1381 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1382 }13831384 1385138613871388138913901391139213931394 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1395 const result = await this.helper.executeExtrinsic(1396 signer,1397 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1398 true,1399 );14001401 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1402 }14031404 140514061407140814091410141114121413 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1414 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1415 }14161417 141814191420142114221423142414251426 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1427 const result = await this.helper.executeExtrinsic(1428 signer,1429 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1430 true,1431 );14321433 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1434 }14351436 143714381439144014411442144314441445 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1446 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1447 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1448 for (const key of ['name', 'description', 'tokenPrefix']) {1449 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);1450 }1451 const creationResult = await this.helper.executeExtrinsic(1452 signer,1453 'api.tx.unique.createCollectionEx', [collectionOptions],1454 true, 1455 );1456 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1457 }14581459 getCollectionObject(_collectionId: number): any {1460 return null;1461 }14621463 getTokenObject(_collectionId: number, _tokenId: number): any {1464 return null;1465 }14661467 1468146914701471147214731474 async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1475 return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1476 }14771478 147914801481148214831484 async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1485 const result = await this.helper.executeExtrinsic(1486 signer,1487 'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1488 true,1489 );1490 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1491 }1492}149314941495class NFTGroup extends NFTnRFT {1496 149714981499150015011502 getCollectionObject(collectionId: number): UniqueNFTCollection {1503 return new UniqueNFTCollection(collectionId, this.helper);1504 }15051506 1507150815091510151115121513 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1514 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1515 }15161517 15181519152015211522152315241525 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1526 let owner;1527 if (typeof blockHashAt === 'undefined') {1528 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1529 } else {1530 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1531 }1532 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1533 }15341535 1536153715381539154015411542 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1543 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1544 }15451546 1547154815491550155115521553155415551556 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1557 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1558 }15591560 156115621563156415651566156715681569157015711572 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1573 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1574 }15751576 15771578157915801581158215831584 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1585 let owner;1586 if (typeof blockHashAt === 'undefined') {1587 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1588 } else {1589 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1590 }15911592 if (owner === null) return null;15931594 return owner.toHuman();1595 }15961597 15981599160016011602160316041605 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1606 let children;1607 if(typeof blockHashAt === 'undefined') {1608 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1609 } else {1610 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1611 }16121613 return children.toJSON().map((x: any) => {1614 return {collectionId: x.collection, tokenId: x.token};1615 });1616 }16171618 16191620162116221623162416251626 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1627 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1628 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1629 if(!result) {1630 throw Error('Unable to nest token!');1631 }1632 return result;1633 }16341635 163616371638163916401641164216431644 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1645 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1646 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1647 if(!result) {1648 throw Error('Unable to unnest token!');1649 }1650 return result;1651 }16521653 165416551656165716581659166016611662166316641665 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1666 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1667 }16681669 167016711672167316741675 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1676 const creationResult = await this.helper.executeExtrinsic(1677 signer,1678 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1679 nft: {1680 properties: data.properties,1681 },1682 }],1683 true,1684 );1685 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1686 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1687 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1688 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1689 }16901691 169216931694169516961697169816991700170117021703170417051706 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1707 const creationResult = await this.helper.executeExtrinsic(1708 signer,1709 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1710 true,1711 );1712 const collection = this.getCollectionObject(collectionId);1713 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1714 }17151716 171717181719172017211722172317241725172617271728172917301731173217331734 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1735 const rawTokens = [];1736 for (const token of tokens) {1737 const raw = {NFT: {properties: token.properties}};1738 rawTokens.push(raw);1739 }1740 const creationResult = await this.helper.executeExtrinsic(1741 signer,1742 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1743 true,1744 );1745 const collection = this.getCollectionObject(collectionId);1746 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1747 }17481749 1750175117521753175417551756175717581759 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1760 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1761 }1762}176317641765class RFTGroup extends NFTnRFT {1766 176717681769177017711772 getCollectionObject(collectionId: number): UniqueRFTCollection {1773 return new UniqueRFTCollection(collectionId, this.helper);1774 }17751776 1777177817791780178117821783 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1784 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1785 }17861787 1788178917901791179217931794 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1795 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1796 }17971798 17991800180118021803180418051806 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1807 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1808 }18091810 1811181218131814181518161817181818191820 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1821 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1822 }18231824 18251826182718281829183018311832183318341835 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1836 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1837 }18381839 184018411842184318441845184618471848184918501851 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1852 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1853 }18541855 1856185718581859186018611862 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1863 const creationResult = await this.helper.executeExtrinsic(1864 signer,1865 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1866 refungible: {1867 pieces: data.pieces,1868 properties: data.properties,1869 },1870 }],1871 true,1872 );1873 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1874 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1875 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1876 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1877 }18781879 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1880 throw Error('Not implemented');1881 const creationResult = await this.helper.executeExtrinsic(1882 signer,1883 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1884 true, 1885 );1886 const collection = this.getCollectionObject(collectionId);1887 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1888 }18891890 189118921893189418951896189718981899 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1900 const rawTokens = [];1901 for (const token of tokens) {1902 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1903 rawTokens.push(raw);1904 }1905 const creationResult = await this.helper.executeExtrinsic(1906 signer,1907 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1908 true,1909 );1910 const collection = this.getCollectionObject(collectionId);1911 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1912 }19131914 191519161917191819191920192119221923 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1924 return await super.burnToken(signer, collectionId, tokenId, amount);1925 }19261927 1928192919301931193219331934193519361937 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1938 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1939 }19401941 19421943194419451946194719481949195019511952 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1953 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1954 }19551956 1957195819591960196119621963 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1964 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1965 }19661967 196819691970197119721973197419751976 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1977 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1978 const repartitionResult = await this.helper.executeExtrinsic(1979 signer,1980 'api.tx.unique.repartition', [collectionId, tokenId, amount],1981 true,1982 );1983 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1984 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1985 }1986}198719881989class FTGroup extends CollectionGroup {1990 199119921993199419951996 getCollectionObject(collectionId: number): UniqueFTCollection {1997 return new UniqueFTCollection(collectionId, this.helper);1998 }19992000 2001200220032004200520062007200820092010201120122013 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {2014 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 2015 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');2016 collectionOptions.mode = {fungible: decimalPoints};2017 for (const key of ['name', 'description', 'tokenPrefix']) {2018 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);2019 }2020 const creationResult = await this.helper.executeExtrinsic(2021 signer,2022 'api.tx.unique.createCollectionEx', [collectionOptions],2023 true,2024 );2025 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2026 }20272028 202920302031203220332034203520362037 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2038 const creationResult = await this.helper.executeExtrinsic(2039 signer,2040 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2041 fungible: {2042 value: amount,2043 },2044 }],2045 true, 2046 );2047 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2048 }20492050 20512052205320542055205620572058 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {2059 const rawTokens = [];2060 for (const token of tokens) {2061 const raw = {Fungible: {Value: token.value}};2062 rawTokens.push(raw);2063 }2064 const creationResult = await this.helper.executeExtrinsic(2065 signer,2066 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2067 true,2068 );2069 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2070 }20712072 207320742075207620772078 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2079 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2080 }20812082 2083208420852086208720882089 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2090 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2091 }20922093 209420952096209720982099210021012102 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2103 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2104 }21052106 2107210821092110211121122113211421152116 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2117 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2118 }21192120 21212122212321242125212621272128 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2129 return await super.burnToken(signer, collectionId, 0, amount);2130 }21312132 213321342135213621372138213921402141 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2142 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2143 }21442145 21462147214821492150 async getTotalPieces(collectionId: number): Promise<bigint> {2151 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2152 }21532154 2155215621572158215921602161216221632164 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2165 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2166 }21672168 2169217021712172217321742175 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2176 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2177 }2178}217921802181class ChainGroup extends HelperGroup<ChainHelperBase> {2182 21832184218521862187 getChainProperties(): IChainProperties {2188 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2189 return {2190 ss58Format: properties.ss58Format.toJSON(),2191 tokenDecimals: properties.tokenDecimals.toJSON(),2192 tokenSymbol: properties.tokenSymbol.toJSON(),2193 };2194 }21952196 21972198219922002201 async getLatestBlockNumber(): Promise<number> {2202 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2203 }22042205 220622072208220922102211 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2212 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2213 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2214 return blockHash;2215 }22162217 2218 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2219 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2220 if (!blockHash) return null;2221 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2222 }22232224 2225222622272228 async getRelayBlockNumber(): Promise<bigint> {2229 const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2230 return BigInt(blockNumber);2231 }22322233 223422352236223722382239 async getNonce(address: TSubstrateAccount): Promise<number> {2240 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2241 }2242}22432244class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2245 224622472248224922502251 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2252 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2253 }22542255 22562257225822592260226122622263 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2264 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);22652266 let transfer = {from: null, to: null, amount: 0n} as any;2267 result.result.events.forEach(({event: {data, method, section}}) => {2268 if ((section === 'balances') && (method === 'Transfer')) {2269 transfer = {2270 from: this.helper.address.normalizeSubstrate(data[0]),2271 to: this.helper.address.normalizeSubstrate(data[1]),2272 amount: BigInt(data[2]),2273 };2274 }2275 });2276 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2277 && this.helper.address.normalizeSubstrate(address) === transfer.to2278 && BigInt(amount) === transfer.amount;2279 return isSuccess;2280 }22812282 22832284228522862287 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2288 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2289 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2290 }22912292 async getLocked(address: TSubstrateAccount): Promise<[{id: string, amount: bigint, reason: string}]> {2293 const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2294 return locks.map((lock: any) => {return {id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons};});2295 }2296}22972298class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2299 230023012302230323042305 async getEthereum(address: TEthereumAccount): Promise<bigint> {2306 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2307 }23082309 23102311231223132314231523162317 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2318 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);23192320 let transfer = {from: null, to: null, amount: 0n} as any;2321 result.result.events.forEach(({event: {data, method, section}}) => {2322 if ((section === 'balances') && (method === 'Transfer')) {2323 transfer = {2324 from: data[0].toString(),2325 to: data[1].toString(),2326 amount: BigInt(data[2]),2327 };2328 }2329 });2330 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2331 && address === transfer.to2332 && BigInt(amount) === transfer.amount;2333 return isSuccess;2334 }2335}23362337class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2338 subBalanceGroup: SubstrateBalanceGroup<T>;2339 ethBalanceGroup: EthereumBalanceGroup<T>;23402341 constructor(helper: T) {2342 super(helper);2343 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2344 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2345 }23462347 getCollectionCreationPrice(): bigint {2348 return 2n * this.getOneTokenNominal();2349 }2350 23512352235323542355 getOneTokenNominal(): bigint {2356 const chainProperties = this.helper.chain.getChainProperties();2357 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2358 }23592360 236123622363236423652366 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2367 return this.subBalanceGroup.getSubstrate(address);2368 }23692370 23712372237323742375 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2376 return this.subBalanceGroup.getSubstrateFull(address);2377 }23782379 23802381238223832384 getLocked(address: TSubstrateAccount) {2385 return this.subBalanceGroup.getLocked(address);2386 }23872388 238923902391239223932394 getEthereum(address: TEthereumAccount): Promise<bigint> {2395 return this.ethBalanceGroup.getEthereum(address);2396 }23972398 23992400240124022403240424052406 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2407 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2408 }24092410 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2411 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);24122413 let transfer = {from: null, to: null, amount: 0n} as any;2414 result.result.events.forEach(({event: {data, method, section}}) => {2415 if ((section === 'balances') && (method === 'Transfer')) {2416 transfer = {2417 from: this.helper.address.normalizeSubstrate(data[0]),2418 to: this.helper.address.normalizeSubstrate(data[1]),2419 amount: BigInt(data[2]),2420 };2421 }2422 });2423 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2424 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2425 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2426 return isSuccess;2427 }24282429 2430243124322433243424352436 async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: {start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}): Promise<void> {2437 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2438 const event = result.result.events2439 .find(e => e.event.section === 'vesting' &&2440 e.event.method === 'VestingScheduleAdded' &&2441 e.event.data[0].toHuman() === signer.address);2442 if (!event) throw Error('Cannot find transfer in events');2443 }24442445 24462447244824492450 async getVestingSchedules(address: TSubstrateAccount): Promise<{start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}[]> {2451 const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2452 return schedule.map((schedule: any) => {2453 return {2454 start: BigInt(schedule.start),2455 period: BigInt(schedule.period),2456 periodCount: BigInt(schedule.periodCount),2457 perPeriod: BigInt(schedule.perPeriod),2458 };2459 });2460 }24612462 2463246424652466 async claim(signer: TSigner) {2467 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2468 const event = result.result.events2469 .find(e => e.event.section === 'vesting' &&2470 e.event.method === 'Claimed' &&2471 e.event.data[0].toHuman() === signer.address);2472 if (!event) throw Error('Cannot find claim in events');2473 }2474}24752476class AddressGroup extends HelperGroup<ChainHelperBase> {2477 2478247924802481248224832484 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2485 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2486 }24872488 248924902491249224932494 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2495 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2496 }24972498 2499250025012502250325042505 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2506 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2507 }25082509 251025112512251325142515 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2516 return CrossAccountId.translateSubToEth(subAddress);2517 }25182519 252025212522252325242525 encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2526 const u8a :Uint8Array = typeof key === 'string'2527 ? hexToU8a(key)2528 : typeof key === 'bigint'2529 ? hexToU8a(key.toString(16))2530 : key;25312532 if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2533 throw new Error(`ss58Format is not valid, received ${typeof ss58Format} "${ss58Format}"`);2534 }25352536 const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2537 if (!allowedDecodedLengths.includes(u8a.length)) {2538 throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2539 }25402541 const u8aPrefix = ss58Format < 642542 ? new Uint8Array([ss58Format])2543 : new Uint8Array([2544 ((ss58Format & 0xfc) >> 2) | 0x40,2545 (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2546 ]);25472548 const input = u8aConcat(u8aPrefix, u8a);25492550 return base58Encode(u8aConcat(2551 input,2552 blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2553 ));2554 }25552556 25572558255925602561 restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2562 if (this.helper.api === null) {2563 throw 'Not connected';2564 }2565 const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2566 if (res === undefined || res === null) {2567 throw 'Restore address error';2568 }2569 return res.toString();2570 }25712572 25732574257525762577 convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2578 if (ethCrossAccount.sub === '0') {2579 return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2580 }25812582 const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2583 return {Substrate: ss58};2584 }25852586 paraSiblingSovereignAccount(paraid: number) {2587 2588 2589 const siblingPrefix = '0x7369626c';25902591 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2592 const suffix = '000000000000000000000000000000000000000000000000';25932594 return siblingPrefix + encodedParaId + suffix;2595 }2596}25972598class StakingGroup extends HelperGroup<UniqueHelper> {2599 2600260126022603260426052606 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2607 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2608 const _stakeResult = await this.helper.executeExtrinsic(2609 signer, 'api.tx.appPromotion.stake',2610 [amountToStake], true,2611 );2612 2613 return true;2614 }26152616 2617261826192620262126222623 async unstake(signer: TSigner, label?: string): Promise<number> {2624 if(typeof label === 'undefined') label = `${signer.address}`;2625 const _unstakeResult = await this.helper.executeExtrinsic(2626 signer, 'api.tx.appPromotion.unstake',2627 [], true,2628 );2629 2630 return 1;2631 }26322633 26342635263626372638 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2639 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2640 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2641 }26422643 26442645264626472648 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2649 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2650 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2651 return {2652 block: block.toBigInt(),2653 amount: amount.toBigInt(),2654 };2655 });2656 }26572658 26592660266126622663 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2664 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2665 }26662667 26682669267026712672 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2673 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2674 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2675 return {2676 block: block.toBigInt(),2677 amount: amount.toBigInt(),2678 };2679 });2680 return result;2681 }2682}26832684class SchedulerGroup extends HelperGroup<UniqueHelper> {2685 constructor(helper: UniqueHelper) {2686 super(helper);2687 }26882689 cancelScheduled(signer: TSigner, scheduledId: string) {2690 return this.helper.executeExtrinsic(2691 signer,2692 'api.tx.scheduler.cancelNamed',2693 [scheduledId],2694 true,2695 );2696 }26972698 changePriority(signer: TSigner, scheduledId: string, priority: number) {2699 return this.helper.executeExtrinsic(2700 signer,2701 'api.tx.scheduler.changeNamedPriority',2702 [scheduledId, priority],2703 true,2704 );2705 }27062707 scheduleAt<T extends UniqueHelper>(2708 executionBlockNumber: number,2709 options: ISchedulerOptions = {},2710 ) {2711 return this.schedule<T>('schedule', executionBlockNumber, options);2712 }27132714 scheduleAfter<T extends UniqueHelper>(2715 blocksBeforeExecution: number,2716 options: ISchedulerOptions = {},2717 ) {2718 return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2719 }27202721 schedule<T extends UniqueHelper>(2722 scheduleFn: 'schedule' | 'scheduleAfter',2723 blocksNum: number,2724 options: ISchedulerOptions = {},2725 ) {2726 2727 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2728 return this.helper.clone(ScheduledHelperType, {2729 scheduleFn,2730 blocksNum,2731 options,2732 }) as T;2733 }2734}27352736class CollatorSelectionGroup extends HelperGroup<UniqueHelper> {2737 2738 addInvulnerable(signer: TSigner, address: string) {2739 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.addInvulnerable', [address]);2740 }27412742 removeInvulnerable(signer: TSigner, address: string) {2743 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.removeInvulnerable', [address]);2744 }27452746 async getInvulnerables(): Promise<string[]> {2747 return (await this.helper.callRpc('api.query.collatorSelection.invulnerables')).map((x: any) => x.toHuman());2748 }27492750 2751 maxCollators(): number {2752 return (this.helper.getApi().consts.configuration.defaultCollatorSelectionMaxCollators.toJSON() as number);2753 }27542755 async getDesiredCollators(): Promise<number> {2756 return (await this.helper.callRpc('api.query.configuration.collatorSelectionDesiredCollatorsOverride')).toNumber();2757 }27582759 setLicenseBond(signer: TSigner, amount: bigint) {2760 return this.helper.executeExtrinsic(signer, 'api.tx.configuration.setCollatorSelectionLicenseBond', [amount]);2761 }27622763 async getLicenseBond(): Promise<bigint> {2764 return (await this.helper.callRpc('api.query.configuration.collatorSelectionLicenseBondOverride')).toBigInt();2765 }27662767 obtainLicense(signer: TSigner) {2768 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.getLicense', []);2769 }27702771 releaseLicense(signer: TSigner) {2772 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.releaseLicense', []);2773 }27742775 forceRevokeLicense(signer: TSigner, released: string) {2776 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.forceRevokeLicense', [released]);2777 }27782779 async hasLicense(address: string): Promise<bigint> {2780 return (await this.helper.callRpc('api.query.collatorSelection.licenseDepositOf', [address])).toBigInt();2781 }27822783 onboard(signer: TSigner) {2784 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.onboard', []);2785 }27862787 offboard(signer: TSigner) {2788 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.offboard', []);2789 }27902791 async getCandidates(): Promise<string[]> {2792 return (await this.helper.callRpc('api.query.collatorSelection.candidates')).map((x: any) => x.toHuman());2793 }2794}27952796class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2797 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2798 await this.helper.executeExtrinsic(2799 signer,2800 'api.tx.foreignAssets.registerForeignAsset',2801 [ownerAddress, location, metadata],2802 true,2803 );2804 }28052806 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2807 await this.helper.executeExtrinsic(2808 signer,2809 'api.tx.foreignAssets.updateForeignAsset',2810 [foreignAssetId, location, metadata],2811 true,2812 );2813 }2814}28152816class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2817 palletName: string;28182819 constructor(helper: T, palletName: string) {2820 super(helper);28212822 this.palletName = palletName;2823 }28242825 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {2826 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);2827 }28282829 async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {2830 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);2831 }28322833 async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint) {2834 const destination = {2835 V1: {2836 parents: 0,2837 interior: {2838 X1: {2839 Parachain: destinationParaId,2840 },2841 },2842 },2843 };28442845 const beneficiary = {2846 V1: {2847 parents: 0,2848 interior: {2849 X1: {2850 AccountId32: {2851 network: 'Any',2852 id: targetAccount,2853 },2854 },2855 },2856 },2857 };28582859 const assets = {2860 V1: [2861 {2862 id: {2863 Concrete: {2864 parents: 0,2865 interior: 'Here',2866 },2867 },2868 fun: {2869 Fungible: amount,2870 },2871 },2872 ],2873 };28742875 const feeAssetItem = 0;28762877 await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);2878 }2879}28802881class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2882 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {2883 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2884 }28852886 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {2887 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2888 }28892890 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {2891 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2892 }2893}28942895class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2896 async accounts(address: string, currencyId: any) {2897 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2898 return BigInt(free);2899 }2900}29012902class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2903 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2904 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2905 }29062907 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2908 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2909 }29102911 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2912 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2913 }29142915 async account(assetId: string | number, address: string) {2916 const accountAsset = (2917 await this.helper.callRpc('api.query.assets.account', [assetId, address])2918 ).toJSON()! as any;29192920 if (accountAsset !== null) {2921 return BigInt(accountAsset['balance']);2922 } else {2923 return null;2924 }2925 }2926}29272928class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2929 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2930 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2931 }2932}29332934class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2935 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2936 const apiPrefix = 'api.tx.assetManager.';29372938 const registerTx = this.helper.constructApiCall(2939 apiPrefix + 'registerForeignAsset',2940 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2941 );29422943 const setUnitsTx = this.helper.constructApiCall(2944 apiPrefix + 'setAssetUnitsPerSecond',2945 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2946 );29472948 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2949 const encodedProposal = batchCall?.method.toHex() || '';2950 return encodedProposal;2951 }29522953 async assetTypeId(location: any) {2954 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2955 }2956}29572958class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2959 notePreimagePallet: string;29602961 constructor(helper: MoonbeamHelper, options: {[key: string]: any} = {}) {2962 super(helper);2963 this.notePreimagePallet = options.notePreimagePallet;2964 }29652966 async notePreimage(signer: TSigner, encodedProposal: string) {2967 await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);2968 }29692970 externalProposeMajority(proposal: any) {2971 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);2972 }29732974 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2975 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2976 }29772978 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2979 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2980 }2981}29822983class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2984 collective: string;29852986 constructor(helper: MoonbeamHelper, collective: string) {2987 super(helper);29882989 this.collective = collective;2990 }29912992 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2993 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2994 }29952996 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2997 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2998 }29993000 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {3001 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);3002 }30033004 async proposalCount() {3005 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));3006 }3007}30083009export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;3010export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;30113012export class UniqueHelper extends ChainHelperBase {3013 balance: BalanceGroup<UniqueHelper>;3014 collection: CollectionGroup;3015 nft: NFTGroup;3016 rft: RFTGroup;3017 ft: FTGroup;3018 staking: StakingGroup;3019 scheduler: SchedulerGroup;3020 collatorSelection: CollatorSelectionGroup;3021 foreignAssets: ForeignAssetsGroup;3022 xcm: XcmGroup<UniqueHelper>;3023 xTokens: XTokensGroup<UniqueHelper>;3024 tokens: TokensGroup<UniqueHelper>;30253026 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3027 super(logger, options.helperBase ?? UniqueHelper);30283029 this.balance = new BalanceGroup(this);3030 this.collection = new CollectionGroup(this);3031 this.nft = new NFTGroup(this);3032 this.rft = new RFTGroup(this);3033 this.ft = new FTGroup(this);3034 this.staking = new StakingGroup(this);3035 this.scheduler = new SchedulerGroup(this);3036 this.collatorSelection = new CollatorSelectionGroup(this);3037 this.foreignAssets = new ForeignAssetsGroup(this);3038 this.xcm = new XcmGroup(this, 'polkadotXcm');3039 this.xTokens = new XTokensGroup(this);3040 this.tokens = new TokensGroup(this);3041 }30423043 getSudo<T extends UniqueHelper>() {3044 3045 const SudoHelperType = SudoHelper(this.helperBase);3046 return this.clone(SudoHelperType) as T;3047 }3048}30493050export class XcmChainHelper extends ChainHelperBase {3051 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {3052 const wsProvider = new WsProvider(wsEndpoint);3053 this.api = new ApiPromise({3054 provider: wsProvider,3055 });3056 await this.api.isReadyOrError;3057 this.network = await UniqueHelper.detectNetwork(this.api);3058 }3059}30603061export class RelayHelper extends XcmChainHelper {3062 balance: SubstrateBalanceGroup<RelayHelper>;3063 xcm: XcmGroup<RelayHelper>;30643065 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3066 super(logger, options.helperBase ?? RelayHelper);30673068 this.balance = new SubstrateBalanceGroup(this);3069 this.xcm = new XcmGroup(this, 'xcmPallet');3070 }3071}30723073export class WestmintHelper extends XcmChainHelper {3074 balance: SubstrateBalanceGroup<WestmintHelper>;3075 xcm: XcmGroup<WestmintHelper>;3076 assets: AssetsGroup<WestmintHelper>;3077 xTokens: XTokensGroup<WestmintHelper>;30783079 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3080 super(logger, options.helperBase ?? WestmintHelper);30813082 this.balance = new SubstrateBalanceGroup(this);3083 this.xcm = new XcmGroup(this, 'polkadotXcm');3084 this.assets = new AssetsGroup(this);3085 this.xTokens = new XTokensGroup(this);3086 }3087}30883089export class MoonbeamHelper extends XcmChainHelper {3090 balance: EthereumBalanceGroup<MoonbeamHelper>;3091 assetManager: MoonbeamAssetManagerGroup;3092 assets: AssetsGroup<MoonbeamHelper>;3093 xTokens: XTokensGroup<MoonbeamHelper>;3094 democracy: MoonbeamDemocracyGroup;3095 collective: {3096 council: MoonbeamCollectiveGroup,3097 techCommittee: MoonbeamCollectiveGroup,3098 };30993100 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3101 super(logger, options.helperBase ?? MoonbeamHelper);31023103 this.balance = new EthereumBalanceGroup(this);3104 this.assetManager = new MoonbeamAssetManagerGroup(this);3105 this.assets = new AssetsGroup(this);3106 this.xTokens = new XTokensGroup(this);3107 this.democracy = new MoonbeamDemocracyGroup(this, options);3108 this.collective = {3109 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),3110 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),3111 };3112 }3113}31143115export class AcalaHelper extends XcmChainHelper {3116 balance: SubstrateBalanceGroup<AcalaHelper>;3117 assetRegistry: AcalaAssetRegistryGroup;3118 xTokens: XTokensGroup<AcalaHelper>;3119 tokens: TokensGroup<AcalaHelper>;31203121 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3122 super(logger, options.helperBase ?? AcalaHelper);31233124 this.balance = new SubstrateBalanceGroup(this);3125 this.assetRegistry = new AcalaAssetRegistryGroup(this);3126 this.xTokens = new XTokensGroup(this);3127 this.tokens = new TokensGroup(this);3128 }31293130 getSudo<T extends AcalaHelper>() {3131 3132 const SudoHelperType = SudoHelper(this.helperBase);3133 return this.clone(SudoHelperType) as T;3134 }3135}313631373138function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3139 return class extends Base {3140 scheduleFn: 'schedule' | 'scheduleAfter';3141 blocksNum: number;3142 options: ISchedulerOptions;31433144 constructor(...args: any[]) {3145 const logger = args[0] as ILogger;3146 const options = args[1] as {3147 scheduleFn: 'schedule' | 'scheduleAfter',3148 blocksNum: number,3149 options: ISchedulerOptions3150 };31513152 super(logger);31533154 this.scheduleFn = options.scheduleFn;3155 this.blocksNum = options.blocksNum;3156 this.options = options.options;3157 }31583159 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3160 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);31613162 const mandatorySchedArgs = [3163 this.blocksNum,3164 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3165 this.options.priority ?? null,3166 scheduledTx,3167 ];31683169 let schedArgs;3170 let scheduleFn;31713172 if (this.options.scheduledId) {3173 schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];31743175 if (this.scheduleFn == 'schedule') {3176 scheduleFn = 'scheduleNamed';3177 } else if (this.scheduleFn == 'scheduleAfter') {3178 scheduleFn = 'scheduleNamedAfter';3179 }3180 } else {3181 schedArgs = mandatorySchedArgs;3182 scheduleFn = this.scheduleFn;3183 }31843185 const extrinsic = 'api.tx.scheduler.' + scheduleFn;31863187 return super.executeExtrinsic(3188 sender,3189 extrinsic,3190 schedArgs,3191 expectSuccess,3192 );3193 }3194 };3195}319631973198function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3199 return class extends Base {3200 constructor(...args: any[]) {3201 super(...args);3202 }32033204 async executeExtrinsic(3205 sender: IKeyringPair,3206 extrinsic: string,3207 params: any[],3208 expectSuccess?: boolean,3209 options: Partial<SignerOptions>|null = null,3210 ): Promise<ITransactionResult> {3211 const call = this.constructApiCall(extrinsic, params);3212 const result = await super.executeExtrinsic(3213 sender,3214 'api.tx.sudo.sudo',3215 [call],3216 expectSuccess,3217 options,3218 );32193220 if (result.status === 'Fail') return result;32213222 const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;3223 if (data.isErr) {3224 if (data.asErr.isModule) {3225 const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;3226 const metaError = super.getApi()?.registry.findMetaError(error);3227 throw new Error(`${metaError.section}.${metaError.name}`);3228 } else {3229 throw new Error(data.asErr.toHuman());3230 }3231 }3232 return result;3233 }3234 };3235}32363237export class UniqueBaseCollection {3238 helper: UniqueHelper;3239 collectionId: number;32403241 constructor(collectionId: number, uniqueHelper: UniqueHelper) {3242 this.collectionId = collectionId;3243 this.helper = uniqueHelper;3244 }32453246 async getData() {3247 return await this.helper.collection.getData(this.collectionId);3248 }32493250 async getLastTokenId() {3251 return await this.helper.collection.getLastTokenId(this.collectionId);3252 }32533254 async doesTokenExist(tokenId: number) {3255 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3256 }32573258 async getAdmins() {3259 return await this.helper.collection.getAdmins(this.collectionId);3260 }32613262 async getAllowList() {3263 return await this.helper.collection.getAllowList(this.collectionId);3264 }32653266 async getEffectiveLimits() {3267 return await this.helper.collection.getEffectiveLimits(this.collectionId);3268 }32693270 async getProperties(propertyKeys?: string[] | null) {3271 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3272 }32733274 async getPropertiesConsumedSpace() {3275 return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3276 }32773278 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3279 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3280 }32813282 async getOptions() {3283 return await this.helper.collection.getCollectionOptions(this.collectionId);3284 }32853286 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3287 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3288 }32893290 async confirmSponsorship(signer: TSigner) {3291 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3292 }32933294 async removeSponsor(signer: TSigner) {3295 return await this.helper.collection.removeSponsor(signer, this.collectionId);3296 }32973298 async setLimits(signer: TSigner, limits: ICollectionLimits) {3299 return await this.helper.collection.setLimits(signer, this.collectionId, limits);3300 }33013302 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3303 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3304 }33053306 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3307 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3308 }33093310 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3311 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3312 }33133314 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3315 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3316 }33173318 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3319 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3320 }33213322 async setProperties(signer: TSigner, properties: IProperty[]) {3323 return await this.helper.collection.setProperties(signer, this.collectionId, properties);3324 }33253326 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3327 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3328 }33293330 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3331 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3332 }33333334 async enableNesting(signer: TSigner, permissions: INestingPermissions) {3335 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3336 }33373338 async disableNesting(signer: TSigner) {3339 return await this.helper.collection.disableNesting(signer, this.collectionId);3340 }33413342 async burn(signer: TSigner) {3343 return await this.helper.collection.burn(signer, this.collectionId);3344 }33453346 scheduleAt<T extends UniqueHelper>(3347 executionBlockNumber: number,3348 options: ISchedulerOptions = {},3349 ) {3350 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3351 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3352 }33533354 scheduleAfter<T extends UniqueHelper>(3355 blocksBeforeExecution: number,3356 options: ISchedulerOptions = {},3357 ) {3358 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3359 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3360 }33613362 getSudo<T extends UniqueHelper>() {3363 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3364 }3365}336633673368export class UniqueNFTCollection extends UniqueBaseCollection {3369 getTokenObject(tokenId: number) {3370 return new UniqueNFToken(tokenId, this);3371 }33723373 async getTokensByAddress(addressObj: ICrossAccountId) {3374 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3375 }33763377 async getToken(tokenId: number, blockHashAt?: string) {3378 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3379 }33803381 async getTokenOwner(tokenId: number, blockHashAt?: string) {3382 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3383 }33843385 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3386 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3387 }33883389 async getTokenChildren(tokenId: number, blockHashAt?: string) {3390 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3391 }33923393 async getPropertyPermissions(propertyKeys: string[] | null = null) {3394 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3395 }33963397 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3398 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3399 }34003401 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3402 const api = this.helper.getApi();3403 const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();34043405 return (props! as any).consumedSpace;3406 }34073408 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3409 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3410 }34113412 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3413 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3414 }34153416 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3417 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3418 }34193420 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3421 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3422 }34233424 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3425 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3426 }34273428 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3429 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3430 }34313432 async burnToken(signer: TSigner, tokenId: number) {3433 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3434 }34353436 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3437 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3438 }34393440 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3441 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3442 }34433444 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3445 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3446 }34473448 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3449 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3450 }34513452 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3453 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3454 }34553456 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3457 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3458 }34593460 scheduleAt<T extends UniqueHelper>(3461 executionBlockNumber: number,3462 options: ISchedulerOptions = {},3463 ) {3464 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3465 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3466 }34673468 scheduleAfter<T extends UniqueHelper>(3469 blocksBeforeExecution: number,3470 options: ISchedulerOptions = {},3471 ) {3472 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3473 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3474 }34753476 getSudo<T extends UniqueHelper>() {3477 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3478 }3479}348034813482export class UniqueRFTCollection extends UniqueBaseCollection {3483 getTokenObject(tokenId: number) {3484 return new UniqueRFToken(tokenId, this);3485 }34863487 async getToken(tokenId: number, blockHashAt?: string) {3488 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3489 }34903491 async getTokensByAddress(addressObj: ICrossAccountId) {3492 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3493 }34943495 async getTop10TokenOwners(tokenId: number) {3496 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3497 }34983499 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3500 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3501 }35023503 async getTokenTotalPieces(tokenId: number) {3504 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3505 }35063507 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3508 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3509 }35103511 async getPropertyPermissions(propertyKeys: string[] | null = null) {3512 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3513 }35143515 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3516 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3517 }35183519 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3520 const api = this.helper.getApi();3521 const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();35223523 return (props! as any).consumedSpace;3524 }35253526 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3527 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3528 }35293530 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3531 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3532 }35333534 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3535 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3536 }35373538 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3539 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3540 }35413542 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3543 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3544 }35453546 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3547 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3548 }35493550 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3551 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3552 }35533554 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3555 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3556 }35573558 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3559 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3560 }35613562 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3563 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3564 }35653566 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3567 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3568 }35693570 scheduleAt<T extends UniqueHelper>(3571 executionBlockNumber: number,3572 options: ISchedulerOptions = {},3573 ) {3574 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3575 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3576 }35773578 scheduleAfter<T extends UniqueHelper>(3579 blocksBeforeExecution: number,3580 options: ISchedulerOptions = {},3581 ) {3582 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3583 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3584 }35853586 getSudo<T extends UniqueHelper>() {3587 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3588 }3589}359035913592export class UniqueFTCollection extends UniqueBaseCollection {3593 async getBalance(addressObj: ICrossAccountId) {3594 return await this.helper.ft.getBalance(this.collectionId, addressObj);3595 }35963597 async getTotalPieces() {3598 return await this.helper.ft.getTotalPieces(this.collectionId);3599 }36003601 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3602 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3603 }36043605 async getTop10Owners() {3606 return await this.helper.ft.getTop10Owners(this.collectionId);3607 }36083609 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3610 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3611 }36123613 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3614 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3615 }36163617 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3618 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3619 }36203621 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3622 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3623 }36243625 async burnTokens(signer: TSigner, amount=1n) {3626 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3627 }36283629 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3630 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3631 }36323633 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3634 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3635 }36363637 scheduleAt<T extends UniqueHelper>(3638 executionBlockNumber: number,3639 options: ISchedulerOptions = {},3640 ) {3641 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3642 return new UniqueFTCollection(this.collectionId, scheduledHelper);3643 }36443645 scheduleAfter<T extends UniqueHelper>(3646 blocksBeforeExecution: number,3647 options: ISchedulerOptions = {},3648 ) {3649 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3650 return new UniqueFTCollection(this.collectionId, scheduledHelper);3651 }36523653 getSudo<T extends UniqueHelper>() {3654 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3655 }3656}365736583659export class UniqueBaseToken {3660 collection: UniqueNFTCollection | UniqueRFTCollection;3661 collectionId: number;3662 tokenId: number;36633664 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3665 this.collection = collection;3666 this.collectionId = collection.collectionId;3667 this.tokenId = tokenId;3668 }36693670 async getNextSponsored(addressObj: ICrossAccountId) {3671 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3672 }36733674 async getProperties(propertyKeys?: string[] | null) {3675 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3676 }36773678 async getTokenPropertiesConsumedSpace() {3679 return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3680 }36813682 async setProperties(signer: TSigner, properties: IProperty[]) {3683 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3684 }36853686 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3687 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3688 }36893690 async doesExist() {3691 return await this.collection.doesTokenExist(this.tokenId);3692 }36933694 nestingAccount() {3695 return this.collection.helper.util.getTokenAccount(this);3696 }36973698 scheduleAt<T extends UniqueHelper>(3699 executionBlockNumber: number,3700 options: ISchedulerOptions = {},3701 ) {3702 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3703 return new UniqueBaseToken(this.tokenId, scheduledCollection);3704 }37053706 scheduleAfter<T extends UniqueHelper>(3707 blocksBeforeExecution: number,3708 options: ISchedulerOptions = {},3709 ) {3710 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3711 return new UniqueBaseToken(this.tokenId, scheduledCollection);3712 }37133714 getSudo<T extends UniqueHelper>() {3715 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3716 }3717}371837193720export class UniqueNFToken extends UniqueBaseToken {3721 collection: UniqueNFTCollection;37223723 constructor(tokenId: number, collection: UniqueNFTCollection) {3724 super(tokenId, collection);3725 this.collection = collection;3726 }37273728 async getData(blockHashAt?: string) {3729 return await this.collection.getToken(this.tokenId, blockHashAt);3730 }37313732 async getOwner(blockHashAt?: string) {3733 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3734 }37353736 async getTopmostOwner(blockHashAt?: string) {3737 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3738 }37393740 async getChildren(blockHashAt?: string) {3741 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3742 }37433744 async nest(signer: TSigner, toTokenObj: IToken) {3745 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3746 }37473748 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3749 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3750 }37513752 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3753 return await this.collection.transferToken(signer, this.tokenId, addressObj);3754 }37553756 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3757 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3758 }37593760 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3761 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3762 }37633764 async isApproved(toAddressObj: ICrossAccountId) {3765 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3766 }37673768 async burn(signer: TSigner) {3769 return await this.collection.burnToken(signer, this.tokenId);3770 }37713772 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3773 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3774 }37753776 scheduleAt<T extends UniqueHelper>(3777 executionBlockNumber: number,3778 options: ISchedulerOptions = {},3779 ) {3780 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3781 return new UniqueNFToken(this.tokenId, scheduledCollection);3782 }37833784 scheduleAfter<T extends UniqueHelper>(3785 blocksBeforeExecution: number,3786 options: ISchedulerOptions = {},3787 ) {3788 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3789 return new UniqueNFToken(this.tokenId, scheduledCollection);3790 }37913792 getSudo<T extends UniqueHelper>() {3793 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3794 }3795}37963797export class UniqueRFToken extends UniqueBaseToken {3798 collection: UniqueRFTCollection;37993800 constructor(tokenId: number, collection: UniqueRFTCollection) {3801 super(tokenId, collection);3802 this.collection = collection;3803 }38043805 async getData(blockHashAt?: string) {3806 return await this.collection.getToken(this.tokenId, blockHashAt);3807 }38083809 async getTop10Owners() {3810 return await this.collection.getTop10TokenOwners(this.tokenId);3811 }38123813 async getBalance(addressObj: ICrossAccountId) {3814 return await this.collection.getTokenBalance(this.tokenId, addressObj);3815 }38163817 async getTotalPieces() {3818 return await this.collection.getTokenTotalPieces(this.tokenId);3819 }38203821 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3822 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3823 }38243825 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3826 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3827 }38283829 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3830 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3831 }38323833 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3834 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3835 }38363837 async repartition(signer: TSigner, amount: bigint) {3838 return await this.collection.repartitionToken(signer, this.tokenId, amount);3839 }38403841 async burn(signer: TSigner, amount=1n) {3842 return await this.collection.burnToken(signer, this.tokenId, amount);3843 }38443845 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3846 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3847 }38483849 scheduleAt<T extends UniqueHelper>(3850 executionBlockNumber: number,3851 options: ISchedulerOptions = {},3852 ) {3853 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3854 return new UniqueRFToken(this.tokenId, scheduledCollection);3855 }38563857 scheduleAfter<T extends UniqueHelper>(3858 blocksBeforeExecution: number,3859 options: ISchedulerOptions = {},3860 ) {3861 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3862 return new UniqueRFToken(this.tokenId, scheduledCollection);3863 }38643865 getSudo<T extends UniqueHelper>() {3866 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3867 }3868}