12345678import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {SignerOptions} from '@polkadot/api/types/submittable';10import {ApiInterfaceEvents} from '@polkadot/api/types';11import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';12import {IKeyringPair} from '@polkadot/types/types';13import {hexToU8a} from '@polkadot/util/hex';14import {u8aConcat} from '@polkadot/util/u8a';15import {16 IApiListeners,17 IBlock,18 IEvent,19 IChainProperties,20 ICollectionCreationOptions,21 ICollectionLimits,22 ICollectionPermissions,23 ICrossAccountId,24 ICrossAccountIdLower,25 ILogger,26 INestingPermissions,27 IProperty,28 IStakingInfo,29 ISchedulerOptions,30 ISubstrateBalance,31 IToken,32 ITokenPropertyPermission,33 ITransactionResult,34 IUniqueHelperLog,35 TApiAllowedListeners,36 TEthereumAccount,37 TSigner,38 TSubstrateAccount,39 TNetworks,40 IForeignAssetMetadata,41 AcalaAssetMetadata,42 MoonbeamAssetInfo,43 DemocracyStandardAccountVote,44 IEthCrossAccountId,45} from './types';46import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';47import type {Vec} from '@polkadot/types-codec';48import {FrameSystemEventRecord} from '@polkadot/types/lookup';4950export class CrossAccountId implements ICrossAccountId {51 Substrate?: TSubstrateAccount;52 Ethereum?: TEthereumAccount;5354 constructor(account: ICrossAccountId) {55 if (account.Substrate) this.Substrate = account.Substrate;56 if (account.Ethereum) this.Ethereum = account.Ethereum;57 }5859 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {60 switch (domain) {61 case 'Substrate': return new CrossAccountId({Substrate: account.address});62 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();63 }64 }6566 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {67 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});68 }6970 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {71 return encodeAddress(decodeAddress(address), ss58Format);72 }7374 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {75 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});76 }7778 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {79 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);80 return this;81 }8283 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {84 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));85 }8687 toEthereum(): CrossAccountId {88 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});89 return this;90 }9192 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {93 return evmToAddress(address, ss58Format);94 }9596 toSubstrate(ss58Format?: number): CrossAccountId {97 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});98 return this;99 }100101 toLowerCase(): CrossAccountId {102 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();103 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();104 return this;105 }106}107108const nesting = {109 toChecksumAddress(address: string): string {110 if (typeof address === 'undefined') return '';111112 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);113114 address = address.toLowerCase().replace(/^0x/i,'');115 const addressHash = keccakAsHex(address).replace(/^0x/i,'');116 const checksumAddress = ['0x'];117118 for (let i = 0; i < address.length; i++) {119 120 if (parseInt(addressHash[i], 16) > 7) {121 checksumAddress.push(address[i].toUpperCase());122 } else {123 checksumAddress.push(address[i]);124 }125 }126 return checksumAddress.join('');127 },128 tokenIdToAddress(collectionId: number, tokenId: number) {129 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);130 },131};132133class UniqueUtil {134 static transactionStatus = {135 NOT_READY: 'NotReady',136 FAIL: 'Fail',137 SUCCESS: 'Success',138 };139140 static chainLogType = {141 EXTRINSIC: 'extrinsic',142 RPC: 'rpc',143 };144145 static getTokenAccount(token: IToken): CrossAccountId {146 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});147 }148149 static getTokenAddress(token: IToken): string {150 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);151 }152153 static getDefaultLogger(): ILogger {154 return {155 log(msg: any, level = 'INFO') {156 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));157 },158 level: {159 ERROR: 'ERROR',160 WARNING: 'WARNING',161 INFO: 'INFO',162 },163 };164 }165166 static vec2str(arr: string[] | number[]) {167 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');168 }169170 static str2vec(string: string) {171 if (typeof string !== 'string') return string;172 return Array.from(string).map(x => x.charCodeAt(0));173 }174175 static fromSeed(seed: string, ss58Format = 42) {176 const keyring = new Keyring({type: 'sr25519', ss58Format});177 return keyring.addFromUri(seed);178 }179180 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {181 if (creationResult.status !== this.transactionStatus.SUCCESS) {182 throw Error('Unable to create collection!');183 }184185 let collectionId = null;186 creationResult.result.events.forEach(({event: {data, method, section}}) => {187 if ((section === 'common') && (method === 'CollectionCreated')) {188 collectionId = parseInt(data[0].toString(), 10);189 }190 });191192 if (collectionId === null) {193 throw Error('No CollectionCreated event was found!');194 }195196 return collectionId;197 }198199 static extractTokensFromCreationResult(creationResult: ITransactionResult): {200 success: boolean,201 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],202 } {203 if (creationResult.status !== this.transactionStatus.SUCCESS) {204 throw Error('Unable to create tokens!');205 }206 let success = false;207 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];208 creationResult.result.events.forEach(({event: {data, method, section}}) => {209 if (method === 'ExtrinsicSuccess') {210 success = true;211 } else if ((section === 'common') && (method === 'ItemCreated')) {212 tokens.push({213 collectionId: parseInt(data[0].toString(), 10),214 tokenId: parseInt(data[1].toString(), 10),215 owner: data[2].toHuman(),216 amount: data[3].toBigInt(),217 });218 }219 });220 return {success, tokens};221 }222223 static extractTokensFromBurnResult(burnResult: ITransactionResult): {224 success: boolean,225 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],226 } {227 if (burnResult.status !== this.transactionStatus.SUCCESS) {228 throw Error('Unable to burn tokens!');229 }230 let success = false;231 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];232 burnResult.result.events.forEach(({event: {data, method, section}}) => {233 if (method === 'ExtrinsicSuccess') {234 success = true;235 } else if ((section === 'common') && (method === 'ItemDestroyed')) {236 tokens.push({237 collectionId: parseInt(data[0].toString(), 10),238 tokenId: parseInt(data[1].toString(), 10),239 owner: data[2].toHuman(),240 amount: data[3].toBigInt(),241 });242 }243 });244 return {success, tokens};245 }246247 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {248 let eventId = null;249 events.forEach(({event: {data, method, section}}) => {250 if ((section === expectedSection) && (method === expectedMethod)) {251 eventId = parseInt(data[0].toString(), 10);252 }253 });254255 if (eventId === null) {256 throw Error(`No ${expectedMethod} event was found!`);257 }258 return eventId === collectionId;259 }260261 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {262 const normalizeAddress = (address: string | ICrossAccountId) => {263 if(typeof address === 'string') return address;264 const obj = {} as any;265 Object.keys(address).forEach(k => {266 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];267 });268 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);269 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();270 return address;271 };272 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;273 events.forEach(({event: {data, method, section}}) => {274 if ((section === 'common') && (method === 'Transfer')) {275 const hData = (data as any).toJSON();276 transfer = {277 collectionId: hData[0],278 tokenId: hData[1],279 from: normalizeAddress(hData[2]),280 to: normalizeAddress(hData[3]),281 amount: BigInt(hData[4]),282 };283 }284 });285 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;286 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);287 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);288 isSuccess = isSuccess && amount === transfer.amount;289 return isSuccess;290 }291292 static bigIntToDecimals(number: bigint, decimals = 18) {293 const numberStr = number.toString();294 const dotPos = numberStr.length - decimals;295296 if (dotPos <= 0) {297 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;298 } else {299 const intPart = numberStr.substring(0, dotPos);300 const fractPart = numberStr.substring(dotPos);301 return intPart + '.' + fractPart;302 }303 }304}305306class UniqueEventHelper {307 private static extractIndex(index: any): [number, number] | string {308 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];309 return index.toJSON();310 }311312 private static extractSub(data: any, subTypes: any): {[key: string]: any} {313 let obj: any = {};314 let index = 0;315316 if (data.entries) {317 for(const [key, value] of data.entries()) {318 obj[key] = this.extractData(value, subTypes[index]);319 index++;320 }321 } else obj = data.toJSON();322323 return obj;324 }325326 private static toHuman(data: any) {327 return data && data.toHuman ? data.toHuman() : `${data}`;328 }329330 private static extractData(data: any, type: any): any {331 if(!type) return this.toHuman(data);332 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();333 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();334 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);335 return this.toHuman(data);336 }337338 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {339 const parsedEvents: IEvent[] = [];340341 events.forEach((record) => {342 const {event, phase} = record;343 const types = event.typeDef;344345 const eventData: IEvent = {346 section: event.section.toString(),347 method: event.method.toString(),348 index: this.extractIndex(event.index),349 data: [],350 phase: phase.toJSON(),351 };352353 event.data.forEach((val: any, index: number) => {354 eventData.data.push(this.extractData(val, types[index]));355 });356357 parsedEvents.push(eventData);358 });359360 return parsedEvents;361 }362}363364export class ChainHelperBase {365 helperBase: any;366367 transactionStatus = UniqueUtil.transactionStatus;368 chainLogType = UniqueUtil.chainLogType;369 util: typeof UniqueUtil;370 eventHelper: typeof UniqueEventHelper;371 logger: ILogger;372 api: ApiPromise | null;373 forcedNetwork: TNetworks | null;374 network: TNetworks | null;375 wsEndpoint: string | null;376 chainLog: IUniqueHelperLog[];377 children: ChainHelperBase[];378 address: AddressGroup;379 chain: ChainGroup;380381 constructor(logger?: ILogger, helperBase?: any) {382 this.helperBase = helperBase;383384 this.util = UniqueUtil;385 this.eventHelper = UniqueEventHelper;386 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();387 this.logger = logger;388 this.api = null;389 this.forcedNetwork = null;390 this.network = null;391 this.wsEndpoint = null;392 this.chainLog = [];393 this.children = [];394 this.address = new AddressGroup(this);395 this.chain = new ChainGroup(this);396 }397398 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {399 Object.setPrototypeOf(helperCls.prototype, this);400 const newHelper = new helperCls(this.logger, options);401402 newHelper.api = this.api;403 newHelper.network = this.network;404 newHelper.forceNetwork = this.forceNetwork;405406 this.children.push(newHelper);407408 return newHelper;409 }410411 getEndpoint(): string {412 if (this.wsEndpoint === null) throw Error('No connection was established');413 return this.wsEndpoint;414 }415416 getApi(): ApiPromise {417 if(this.api === null) throw Error('API not initialized');418 return this.api;419 }420421 async subscribeEvents(expectedEvents: {section: string, names: string[]}[]) {422 const collectedEvents: IEvent[] = [];423 const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {424 const ievents = this.eventHelper.extractEvents(events);425 ievents.forEach((event) => {426 expectedEvents.forEach((e => {427 if (event.section === e.section && e.names.includes(event.method)) {428 collectedEvents.push(event);429 }430 }));431 });432 });433 return {unsubscribe: unsubscribe as any, collectedEvents};434 }435436 clearChainLog(): void {437 this.chainLog = [];438 }439440 forceNetwork(value: TNetworks): void {441 this.forcedNetwork = value;442 }443444 async connect(wsEndpoint: string, listeners?: IApiListeners) {445 if (this.api !== null) throw Error('Already connected');446 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);447 this.wsEndpoint = wsEndpoint;448 this.api = api;449 this.network = network;450 }451452 async disconnect() {453 for (const child of this.children) {454 child.clearApi();455 }456457 if (this.api === null) return;458 await this.api.disconnect();459 this.clearApi();460 }461462 clearApi() {463 this.api = null;464 this.network = null;465 }466467 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {468 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;469 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];470471 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;472473 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;474 return 'opal';475 }476477 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {478 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});479 await api.isReady;480481 const network = await this.detectNetwork(api);482483 await api.disconnect();484485 return network;486 }487488 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{489 api: ApiPromise;490 network: TNetworks;491 }> {492 if(typeof network === 'undefined' || network === null) network = 'opal';493 const supportedRPC = {494 opal: {495 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,496 },497 quartz: {498 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,499 },500 unique: {501 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,502 },503 rococo: {},504 westend: {},505 moonbeam: {},506 moonriver: {},507 acala: {},508 karura: {},509 westmint: {},510 };511 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);512 const rpc = supportedRPC[network];513514 515 516517 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});518519 await api.isReadyOrError;520521 if (typeof listeners === 'undefined') listeners = {};522 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {523 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;524 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);525 }526527 return {api, network};528 }529530 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {531 const {events, status} = data;532 if (status.isReady) {533 return this.transactionStatus.NOT_READY;534 }535 if (status.isBroadcast) {536 return this.transactionStatus.NOT_READY;537 }538 if (status.isInBlock || status.isFinalized) {539 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');540 if (errors.length > 0) {541 return this.transactionStatus.FAIL;542 }543 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {544 return this.transactionStatus.SUCCESS;545 }546 }547548 return this.transactionStatus.FAIL;549 }550551 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {552 const sign = (callback: any) => {553 if(options !== null) return transaction.signAndSend(sender, options, callback);554 return transaction.signAndSend(sender, callback);555 };556 557 return new Promise(async (resolve, reject) => {558 try {559 const unsub = await sign((result: any) => {560 const status = this.getTransactionStatus(result);561562 if (status === this.transactionStatus.SUCCESS) {563 this.logger.log(`${label} successful`);564 unsub();565 resolve({result, status, blockHash: result.status.asInBlock.toHuman()});566 } else if (status === this.transactionStatus.FAIL) {567 let moduleError = null;568569 if (result.hasOwnProperty('dispatchError')) {570 const dispatchError = result['dispatchError'];571572 if (dispatchError) {573 if (dispatchError.isModule) {574 const modErr = dispatchError.asModule;575 const errorMeta = dispatchError.registry.findMetaError(modErr);576577 moduleError = `${errorMeta.section}.${errorMeta.name}`;578 } else {579 moduleError = dispatchError.toHuman();580 }581 } else {582 this.logger.log(result, this.logger.level.ERROR);583 }584 }585586 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);587 unsub();588 reject({status, moduleError, result});589 }590 });591 } catch (e) {592 this.logger.log(e, this.logger.level.ERROR);593 reject(e);594 }595 });596 }597598 async signTransactionWithoutSending(signer: TSigner, tx: any) {599 const api = this.getApi();600 const signingInfo = await api.derive.tx.signingInfo(signer.address);601602 tx.sign(signer, {603 blockHash: api.genesisHash,604 genesisHash: api.genesisHash,605 runtimeVersion: api.runtimeVersion,606 nonce: signingInfo.nonce,607 });608609 return tx.toHex();610 }611612 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {613 const api = this.getApi();614 const signingInfo = await api.derive.tx.signingInfo(signer.address);615616 617 618 tx.sign(signer, {619 blockHash: api.genesisHash,620 genesisHash: api.genesisHash,621 runtimeVersion: api.runtimeVersion,622 nonce: signingInfo.nonce,623 });624625 if (len === null) {626 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;627 } else {628 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;629 }630 }631632 constructApiCall(apiCall: string, params: any[]) {633 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);634 let call = this.getApi() as any;635 for(const part of apiCall.slice(4).split('.')) {636 call = call[part];637 if (!call) {638 const advice = part.includes('_') ? ' Looks like it needs to be converted to camel case.' : '';639 throw Error(`Function ${part} of api call ${apiCall} not found.${advice}`);640 }641 }642 return call(...params);643 }644645 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null) {646 if(this.api === null) throw Error('API not initialized');647 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);648649 const startTime = (new Date()).getTime();650 let result: ITransactionResult;651 let events: IEvent[] = [];652 try {653 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;654 events = this.eventHelper.extractEvents(result.result.events);655 const errorEvent = events.find((event) => event.method == 'ExecutedFailed' || event.method == 'CreatedFailed');656 if (errorEvent)657 throw Error(errorEvent.method + ': ' + extrinsic);658 }659 catch(e) {660 if(!(e as object).hasOwnProperty('status')) throw e;661 result = e as ITransactionResult;662 }663664 const endTime = (new Date()).getTime();665666 const log = {667 executedAt: endTime,668 executionTime: endTime - startTime,669 type: this.chainLogType.EXTRINSIC,670 status: result.status,671 call: extrinsic,672 signer: this.getSignerAddress(sender),673 params,674 } as IUniqueHelperLog;675676 let errorMessage = '';677678 if(result.status !== this.transactionStatus.SUCCESS) {679 if (result.moduleError) {680 errorMessage = typeof result.moduleError === 'string'681 ? result.moduleError682 : `${Object.keys(result.moduleError)[0]}: ${Object.values(result.moduleError)[0]}`;683 log.moduleError = errorMessage;684 }685 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;686 }687 if(events.length > 0) log.events = events;688689 this.chainLog.push(log);690691 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {692 if (result.moduleError) throw Error(`${errorMessage}`);693 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));694 }695 return result;696 }697698 async callRpc(rpc: string, params?: any[]) {699 if(typeof params === 'undefined') params = [];700 if(this.api === null) throw Error('API not initialized');701 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);702703 const startTime = (new Date()).getTime();704 let result;705 let error = null;706 const log = {707 type: this.chainLogType.RPC,708 call: rpc,709 params,710 } as IUniqueHelperLog;711712 try {713 result = await this.constructApiCall(rpc, params);714 }715 catch(e) {716 error = e;717 }718719 const endTime = (new Date()).getTime();720721 log.executedAt = endTime;722 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';723 log.executionTime = endTime - startTime;724725 this.chainLog.push(log);726727 if(error !== null) throw error;728729 return result;730 }731732 getSignerAddress(signer: IKeyringPair | string): string {733 if(typeof signer === 'string') return signer;734 return signer.address;735 }736737 fetchAllPalletNames(): string[] {738 if(this.api === null) throw Error('API not initialized');739 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());740 }741742 fetchMissingPalletNames(requiredPallets: string[]): string[] {743 const palletNames = this.fetchAllPalletNames();744 return requiredPallets.filter(p => !palletNames.includes(p));745 }746}747748749class HelperGroup<T extends ChainHelperBase> {750 helper: T;751752 constructor(uniqueHelper: T) {753 this.helper = uniqueHelper;754 }755}756757758class CollectionGroup extends HelperGroup<UniqueHelper> {759 760761762763764765766767768 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {769 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();770 }771772 773774775776777 async getTotalCount(): Promise<number> {778 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();779 }780781 782783784785786787788789790 async getData(collectionId: number): Promise<{791 id: number;792 name: string;793 description: string;794 tokensCount: number;795 admins: CrossAccountId[];796 normalizedOwner: TSubstrateAccount;797 raw: any798 } | null> {799 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);800 const humanCollection = collection.toHuman(), collectionData = {801 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],802 raw: humanCollection,803 } as any, jsonCollection = collection.toJSON();804 if (humanCollection === null) return null;805 collectionData.raw.limits = jsonCollection.limits;806 collectionData.raw.permissions = jsonCollection.permissions;807 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);808 for (const key of ['name', 'description']) {809 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);810 }811812 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))813 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)814 : 0;815 collectionData.admins = await this.getAdmins(collectionId);816817 return collectionData;818 }819820 821822823824825826827828 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {829 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();830831 return normalize832 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())833 : admins;834 }835836 837838839840841842843 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {844 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();845 return normalize846 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())847 : allowListed;848 }849850 851852853854855856857 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {858 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();859 }860861 862863864865866867868869 async burn(signer: TSigner, collectionId: number): Promise<boolean> {870 const result = await this.helper.executeExtrinsic(871 signer,872 'api.tx.unique.destroyCollection', [collectionId],873 true,874 );875876 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');877 }878879 880881882883884885886887888 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {889 const result = await this.helper.executeExtrinsic(890 signer,891 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],892 true,893 );894895 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');896 }897898 899900901902903904905906 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {907 const result = await this.helper.executeExtrinsic(908 signer,909 'api.tx.unique.confirmSponsorship', [collectionId],910 true,911 );912913 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');914 }915916 917918919920921922923924 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {925 const result = await this.helper.executeExtrinsic(926 signer,927 'api.tx.unique.removeCollectionSponsor', [collectionId],928 true,929 );930931 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');932 }933934 935936937938939940941942943944945946947948949950951 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {952 const result = await this.helper.executeExtrinsic(953 signer,954 'api.tx.unique.setCollectionLimits', [collectionId, limits],955 true,956 );957958 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');959 }960961 962963964965966967968969970 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {971 const result = await this.helper.executeExtrinsic(972 signer,973 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],974 true,975 );976977 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');978 }979980 981982983984985986987988989 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {990 const result = await this.helper.executeExtrinsic(991 signer,992 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],993 true,994 );995996 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');997 }998999 100010011002100310041005100610071008 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1009 const result = await this.helper.executeExtrinsic(1010 signer,1011 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],1012 true,1013 );10141015 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');1016 }10171018 10191020102110221023102410251026 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {1027 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();1028 }10291030 1031103210331034103510361037 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1038 const result = await this.helper.executeExtrinsic(1039 signer,1040 'api.tx.unique.addToAllowList', [collectionId, addressObj],1041 true,1042 );10431044 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1045 }10461047 10481049105010511052105310541055 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1056 const result = await this.helper.executeExtrinsic(1057 signer,1058 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1059 true,1060 );10611062 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1063 }10641065 106610671068106910701071107210731074 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1075 const result = await this.helper.executeExtrinsic(1076 signer,1077 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1078 true,1079 );10801081 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1082 }10831084 108510861087108810891090109110921093 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1094 return await this.setPermissions(signer, collectionId, {nesting: permissions});1095 }10961097 10981099110011011102110311041105 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1106 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1107 }11081109 111011111112111311141115111611171118 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1119 const result = await this.helper.executeExtrinsic(1120 signer,1121 'api.tx.unique.setCollectionProperties', [collectionId, properties],1122 true,1123 );11241125 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1126 }11271128 11291130113111321133113411351136 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1137 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1138 }11391140 async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1141 const api = this.helper.getApi();1142 const props = (await api.query.common.collectionProperties(collectionId)).toJSON();11431144 return (props! as any).consumedSpace;1145 }11461147 async getCollectionOptions(collectionId: number) {1148 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1149 }11501151 115211531154115511561157115811591160 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1161 const result = await this.helper.executeExtrinsic(1162 signer,1163 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1164 true,1165 );11661167 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1168 }11691170 11711172117311741175117611771178117911801181 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1182 const result = await this.helper.executeExtrinsic(1183 signer,1184 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1185 true, 1186 );11871188 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1189 }11901191 1192119311941195119611971198119912001201120212031204 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1205 const result = await this.helper.executeExtrinsic(1206 signer,1207 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1208 true, 1209 );1210 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1211 }12121213 12141215121612171218121912201221122212231224 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1225 const burnResult = await this.helper.executeExtrinsic(1226 signer,1227 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1228 true, 1229 );1230 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1231 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1232 return burnedTokens.success;1233 }12341235 12361237123812391240124112421243124412451246 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1247 const burnResult = await this.helper.executeExtrinsic(1248 signer,1249 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1250 true, 1251 );1252 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1253 return burnedTokens.success && burnedTokens.tokens.length > 0;1254 }12551256 1257125812591260126112621263126412651266 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1267 const approveResult = await this.helper.executeExtrinsic(1268 signer,1269 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1270 true, 1271 );12721273 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1274 }12751276 12771278127912801281128212831284128512861287 async approveTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1288 const approveResult = await this.helper.executeExtrinsic(1289 signer,1290 'api.tx.unique.approveFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1291 true, 1292 );12931294 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1295 }12961297 1298129913001301130213031304130513061307 async approveTokenFromEth(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1308 const ethMirror = CrossAccountId.fromKeyring(signer).toEthereum();1309 return await this.approveTokenFrom(signer, collectionId, tokenId, ethMirror, toAddressObj, amount);1310 }13111312 1313131413151316131713181319132013211322 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1323 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1324 }13251326 1327132813291330133113321333 async getLastTokenId(collectionId: number): Promise<number> {1334 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1335 }13361337 13381339134013411342134313441345 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1346 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1347 }1348}13491350class NFTnRFT extends CollectionGroup {1351 13521353135413551356135713581359 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1360 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1361 }13621363 1364136513661367136813691370137113721373 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1374 properties: IProperty[];1375 owner: CrossAccountId;1376 normalizedOwner: CrossAccountId;1377 }| null> {1378 let tokenData;1379 if(typeof blockHashAt === 'undefined') {1380 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1381 }1382 else {1383 if(propertyKeys.length == 0) {1384 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1385 if(!collection) return null;1386 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1387 }1388 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1389 }1390 tokenData = tokenData.toHuman();1391 if (tokenData === null || tokenData.owner === null) return null;1392 const owner = {} as any;1393 for (const key of Object.keys(tokenData.owner)) {1394 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1395 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1396 : tokenData.owner[key];1397 }1398 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1399 return tokenData;1400 }14011402 14031404140514061407140814091410 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1411 let owner;1412 if (typeof blockHashAt === 'undefined') {1413 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1414 } else {1415 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1416 }1417 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1418 }14191420 14211422142314241425142614271428 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1429 let owner;1430 if (typeof blockHashAt === 'undefined') {1431 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1432 } else {1433 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1434 }14351436 if (owner === null) return null;14371438 return owner.toHuman();1439 }14401441 14421443144414451446144714481449 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1450 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1451 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1452 if(!result) {1453 throw Error('Unable to nest token!');1454 }1455 return result;1456 }14571458 145914601461146214631464146514661467 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1468 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1469 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1470 if(!result) {1471 throw Error('Unable to unnest token!');1472 }1473 return result;1474 }14751476 14771478147914801481148214831484148514861487 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1488 const result = await this.helper.executeExtrinsic(1489 signer,1490 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1491 true,1492 );14931494 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1495 }14961497 14981499150015011502150315041505 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1506 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1507 }15081509 1510151115121513151415151516151715181519 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1520 const result = await this.helper.executeExtrinsic(1521 signer,1522 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1523 true,1524 );15251526 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1527 }15281529 153015311532153315341535153615371538 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1539 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1540 }15411542 154315441545154615471548154915501551 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1552 const result = await this.helper.executeExtrinsic(1553 signer,1554 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1555 true,1556 );15571558 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1559 }15601561 156215631564156515661567156815691570 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1571 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1572 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1573 for (const key of ['name', 'description', 'tokenPrefix']) {1574 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);1575 }1576 const creationResult = await this.helper.executeExtrinsic(1577 signer,1578 'api.tx.unique.createCollectionEx', [collectionOptions],1579 true, 1580 );1581 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1582 }15831584 getCollectionObject(_collectionId: number): any {1585 return null;1586 }15871588 getTokenObject(_collectionId: number, _tokenId: number): any {1589 return null;1590 }15911592 1593159415951596159715981599 async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1600 return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1601 }16021603 160416051606160716081609 async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1610 const result = await this.helper.executeExtrinsic(1611 signer,1612 'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1613 true,1614 );1615 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1616 }1617}161816191620class NFTGroup extends NFTnRFT {1621 162216231624162516261627 getCollectionObject(collectionId: number): UniqueNFTCollection {1628 return new UniqueNFTCollection(collectionId, this.helper);1629 }16301631 1632163316341635163616371638 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1639 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1640 }16411642 1643164416451646164716481649 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1650 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1651 }16521653 1654165516561657165816591660166116621663 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1664 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1665 }16661667 166816691670167116721673167416751676167716781679 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1680 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1681 }16821683 16841685168616871688168916901691 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1692 let children;1693 if(typeof blockHashAt === 'undefined') {1694 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1695 } else {1696 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1697 }16981699 return children.toJSON().map((x: any) => {1700 return {collectionId: x.collection, tokenId: x.token};1701 });1702 }17031704 170517061707170817091710171117121713171417151716 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1717 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1718 }17191720 172117221723172417251726 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1727 const creationResult = await this.helper.executeExtrinsic(1728 signer,1729 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1730 nft: {1731 properties: data.properties,1732 },1733 }],1734 true,1735 );1736 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1737 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1738 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1739 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1740 }17411742 174317441745174617471748174917501751175217531754175517561757 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1758 const creationResult = await this.helper.executeExtrinsic(1759 signer,1760 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1761 true,1762 );1763 const collection = this.getCollectionObject(collectionId);1764 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1765 }17661767 176817691770177117721773177417751776177717781779178017811782178317841785 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1786 const rawTokens = [];1787 for (const token of tokens) {1788 const raw = {NFT: {properties: token.properties}};1789 rawTokens.push(raw);1790 }1791 const creationResult = await this.helper.executeExtrinsic(1792 signer,1793 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1794 true,1795 );1796 const collection = this.getCollectionObject(collectionId);1797 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1798 }17991800 1801180218031804180518061807180818091810 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1811 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1812 }1813}181418151816class RFTGroup extends NFTnRFT {1817 181818191820182118221823 getCollectionObject(collectionId: number): UniqueRFTCollection {1824 return new UniqueRFTCollection(collectionId, this.helper);1825 }18261827 1828182918301831183218331834 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1835 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1836 }18371838 1839184018411842184318441845 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1846 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1847 }18481849 18501851185218531854185518561857 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1858 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1859 }18601861 1862186318641865186618671868186918701871 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1872 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1873 }18741875 18761877187818791880188118821883188418851886 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1887 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1888 }18891890 189118921893189418951896189718981899190019011902 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1903 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1904 }19051906 1907190819091910191119121913 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1914 const creationResult = await this.helper.executeExtrinsic(1915 signer,1916 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1917 refungible: {1918 pieces: data.pieces,1919 properties: data.properties,1920 },1921 }],1922 true,1923 );1924 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1925 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1926 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1927 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1928 }19291930 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1931 throw Error('Not implemented');1932 const creationResult = await this.helper.executeExtrinsic(1933 signer,1934 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1935 true, 1936 );1937 const collection = this.getCollectionObject(collectionId);1938 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1939 }19401941 194219431944194519461947194819491950 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1951 const rawTokens = [];1952 for (const token of tokens) {1953 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1954 rawTokens.push(raw);1955 }1956 const creationResult = await this.helper.executeExtrinsic(1957 signer,1958 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1959 true,1960 );1961 const collection = this.getCollectionObject(collectionId);1962 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1963 }19641965 196619671968196919701971197219731974 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1975 return await super.burnToken(signer, collectionId, tokenId, amount);1976 }19771978 1979198019811982198319841985198619871988 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1989 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1990 }19911992 19931994199519961997199819992000200120022003 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2004 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);2005 }20062007 2008200920102011201220132014 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {2015 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();2016 }20172018 201920202021202220232024202520262027 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {2028 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);2029 const repartitionResult = await this.helper.executeExtrinsic(2030 signer,2031 'api.tx.unique.repartition', [collectionId, tokenId, amount],2032 true,2033 );2034 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');2035 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');2036 }2037}203820392040class FTGroup extends CollectionGroup {2041 204220432044204520462047 getCollectionObject(collectionId: number): UniqueFTCollection {2048 return new UniqueFTCollection(collectionId, this.helper);2049 }20502051 2052205320542055205620572058205920602061206220632064 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {2065 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 2066 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');2067 collectionOptions.mode = {fungible: decimalPoints};2068 for (const key of ['name', 'description', 'tokenPrefix']) {2069 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);2070 }2071 const creationResult = await this.helper.executeExtrinsic(2072 signer,2073 'api.tx.unique.createCollectionEx', [collectionOptions],2074 true,2075 );2076 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2077 }20782079 208020812082208320842085208620872088 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2089 const creationResult = await this.helper.executeExtrinsic(2090 signer,2091 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2092 fungible: {2093 value: amount,2094 },2095 }],2096 true, 2097 );2098 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2099 }21002101 21022103210421052106210721082109 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {2110 const rawTokens = [];2111 for (const token of tokens) {2112 const raw = {Fungible: {Value: token.value}};2113 rawTokens.push(raw);2114 }2115 const creationResult = await this.helper.executeExtrinsic(2116 signer,2117 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2118 true,2119 );2120 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2121 }21222123 212421252126212721282129 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2130 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2131 }21322133 2134213521362137213821392140 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2141 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2142 }21432144 214521462147214821492150215121522153 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2154 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2155 }21562157 2158215921602161216221632164216521662167 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2168 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2169 }21702171 21722173217421752176217721782179 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2180 return await super.burnToken(signer, collectionId, 0, amount);2181 }21822183 218421852186218721882189219021912192 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2193 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2194 }21952196 21972198219922002201 async getTotalPieces(collectionId: number): Promise<bigint> {2202 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2203 }22042205 2206220722082209221022112212221322142215 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2216 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2217 }22182219 2220222122222223222422252226 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2227 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2228 }2229}223022312232class ChainGroup extends HelperGroup<ChainHelperBase> {2233 22342235223622372238 getChainProperties(): IChainProperties {2239 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2240 return {2241 ss58Format: properties.ss58Format.toJSON(),2242 tokenDecimals: properties.tokenDecimals.toJSON(),2243 tokenSymbol: properties.tokenSymbol.toJSON(),2244 };2245 }22462247 22482249225022512252 async getLatestBlockNumber(): Promise<number> {2253 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2254 }22552256 225722582259226022612262 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2263 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2264 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2265 return blockHash;2266 }22672268 2269 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2270 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2271 if (!blockHash) return null;2272 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2273 }22742275 2276227722782279 async getRelayBlockNumber(): Promise<bigint> {2280 const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2281 return BigInt(blockNumber);2282 }22832284 228522862287228822892290 async getNonce(address: TSubstrateAccount): Promise<number> {2291 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2292 }2293}22942295class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2296 229722982299230023012302 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2303 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2304 }23052306 23072308230923102311231223132314 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2315 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);23162317 let transfer = {from: null, to: null, amount: 0n} as any;2318 result.result.events.forEach(({event: {data, method, section}}) => {2319 if ((section === 'balances') && (method === 'Transfer')) {2320 transfer = {2321 from: this.helper.address.normalizeSubstrate(data[0]),2322 to: this.helper.address.normalizeSubstrate(data[1]),2323 amount: BigInt(data[2]),2324 };2325 }2326 });2327 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2328 && this.helper.address.normalizeSubstrate(address) === transfer.to2329 && BigInt(amount) === transfer.amount;2330 return isSuccess;2331 }23322333 23342335233623372338 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2339 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2340 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2341 }23422343 async getLocked(address: TSubstrateAccount): Promise<[{id: string, amount: bigint, reason: string}]> {2344 const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2345 return locks.map((lock: any) => {return {id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons};});2346 }2347}23482349class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2350 235123522353235423552356 async getEthereum(address: TEthereumAccount): Promise<bigint> {2357 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2358 }23592360 23612362236323642365236623672368 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2369 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);23702371 let transfer = {from: null, to: null, amount: 0n} as any;2372 result.result.events.forEach(({event: {data, method, section}}) => {2373 if ((section === 'balances') && (method === 'Transfer')) {2374 transfer = {2375 from: data[0].toString(),2376 to: data[1].toString(),2377 amount: BigInt(data[2]),2378 };2379 }2380 });2381 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2382 && address === transfer.to2383 && BigInt(amount) === transfer.amount;2384 return isSuccess;2385 }2386}23872388class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2389 subBalanceGroup: SubstrateBalanceGroup<T>;2390 ethBalanceGroup: EthereumBalanceGroup<T>;23912392 constructor(helper: T) {2393 super(helper);2394 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2395 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2396 }23972398 getCollectionCreationPrice(): bigint {2399 return 2n * this.getOneTokenNominal();2400 }2401 24022403240424052406 getOneTokenNominal(): bigint {2407 const chainProperties = this.helper.chain.getChainProperties();2408 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2409 }24102411 241224132414241524162417 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2418 return this.subBalanceGroup.getSubstrate(address);2419 }24202421 24222423242424252426 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2427 return this.subBalanceGroup.getSubstrateFull(address);2428 }24292430 24312432243324342435 getLocked(address: TSubstrateAccount) {2436 return this.subBalanceGroup.getLocked(address);2437 }24382439 244024412442244324442445 getEthereum(address: TEthereumAccount): Promise<bigint> {2446 return this.ethBalanceGroup.getEthereum(address);2447 }24482449 24502451245224532454245524562457 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2458 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2459 }24602461 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2462 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);24632464 let transfer = {from: null, to: null, amount: 0n} as any;2465 result.result.events.forEach(({event: {data, method, section}}) => {2466 if ((section === 'balances') && (method === 'Transfer')) {2467 transfer = {2468 from: this.helper.address.normalizeSubstrate(data[0]),2469 to: this.helper.address.normalizeSubstrate(data[1]),2470 amount: BigInt(data[2]),2471 };2472 }2473 });2474 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2475 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2476 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2477 return isSuccess;2478 }24792480 2481248224832484248524862487 async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: {start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}): Promise<void> {2488 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2489 const event = result.result.events2490 .find(e => e.event.section === 'vesting' &&2491 e.event.method === 'VestingScheduleAdded' &&2492 e.event.data[0].toHuman() === signer.address);2493 if (!event) throw Error('Cannot find transfer in events');2494 }24952496 24972498249925002501 async getVestingSchedules(address: TSubstrateAccount): Promise<{start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}[]> {2502 const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2503 return schedule.map((schedule: any) => {2504 return {2505 start: BigInt(schedule.start),2506 period: BigInt(schedule.period),2507 periodCount: BigInt(schedule.periodCount),2508 perPeriod: BigInt(schedule.perPeriod),2509 };2510 });2511 }25122513 2514251525162517 async claim(signer: TSigner) {2518 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2519 const event = result.result.events2520 .find(e => e.event.section === 'vesting' &&2521 e.event.method === 'Claimed' &&2522 e.event.data[0].toHuman() === signer.address);2523 if (!event) throw Error('Cannot find claim in events');2524 }2525}25262527class AddressGroup extends HelperGroup<ChainHelperBase> {2528 2529253025312532253325342535 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2536 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2537 }25382539 254025412542254325442545 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2546 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2547 }25482549 2550255125522553255425552556 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2557 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2558 }25592560 256125622563256425652566 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2567 return CrossAccountId.translateSubToEth(subAddress);2568 }25692570 257125722573257425752576 encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2577 const u8a :Uint8Array = typeof key === 'string'2578 ? hexToU8a(key)2579 : typeof key === 'bigint'2580 ? hexToU8a(key.toString(16))2581 : key;25822583 if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2584 throw new Error(`ss58Format is not valid, received ${typeof ss58Format} "${ss58Format}"`);2585 }25862587 const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2588 if (!allowedDecodedLengths.includes(u8a.length)) {2589 throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2590 }25912592 const u8aPrefix = ss58Format < 642593 ? new Uint8Array([ss58Format])2594 : new Uint8Array([2595 ((ss58Format & 0xfc) >> 2) | 0x40,2596 (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2597 ]);25982599 const input = u8aConcat(u8aPrefix, u8a);26002601 return base58Encode(u8aConcat(2602 input,2603 blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2604 ));2605 }26062607 26082609261026112612 restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2613 if (this.helper.api === null) {2614 throw 'Not connected';2615 }2616 const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2617 if (res === undefined || res === null) {2618 throw 'Restore address error';2619 }2620 return res.toString();2621 }26222623 26242625262626272628 convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2629 if (ethCrossAccount.sub === '0') {2630 return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2631 }26322633 const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2634 return {Substrate: ss58};2635 }26362637 paraSiblingSovereignAccount(paraid: number) {2638 2639 2640 const siblingPrefix = '0x7369626c';26412642 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2643 const suffix = '000000000000000000000000000000000000000000000000';26442645 return siblingPrefix + encodedParaId + suffix;2646 }2647}26482649class StakingGroup extends HelperGroup<UniqueHelper> {2650 2651265226532654265526562657 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2658 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2659 const _stakeResult = await this.helper.executeExtrinsic(2660 signer, 'api.tx.appPromotion.stake',2661 [amountToStake], true,2662 );2663 2664 return true;2665 }26662667 2668266926702671267226732674 async unstakeAll(signer: TSigner, label?: string): Promise<string> {2675 if(typeof label === 'undefined') label = `${signer.address}`;2676 const unstakeResult = await this.helper.executeExtrinsic(2677 signer, 'api.tx.appPromotion.unstakeAll',2678 [], true,2679 );2680 return unstakeResult.blockHash;2681 }26822683 2684268526862687268826892690 async unstakePartial(signer: TSigner, amount: bigint, label?: string): Promise<string> {2691 if(typeof label === 'undefined') label = `${signer.address}`;2692 const unstakeResult = await this.helper.executeExtrinsic(2693 signer, 'api.tx.appPromotion.unstakePartial',2694 [amount], true,2695 );2696 return unstakeResult.blockHash;2697 }26982699 27002701270227032704 async getStakesNumber(address: ICrossAccountId): Promise<number> {2705 if (address.Ethereum) throw Error('only substrate address');2706 return (await this.helper.callRpc('api.query.appPromotion.stakesPerAccount', [address.Substrate])).toNumber();2707 }27082709 27102711271227132714 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2715 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2716 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2717 }27182719 27202721272227232724 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2725 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2726 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2727 return {2728 block: block.toBigInt(),2729 amount: amount.toBigInt(),2730 };2731 });2732 }27332734 27352736273727382739 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2740 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2741 }27422743 27442745274627472748 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2749 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2750 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2751 return {2752 block: block.toBigInt(),2753 amount: amount.toBigInt(),2754 };2755 });2756 return result;2757 }2758}27592760class SchedulerGroup extends HelperGroup<UniqueHelper> {2761 constructor(helper: UniqueHelper) {2762 super(helper);2763 }27642765 cancelScheduled(signer: TSigner, scheduledId: string) {2766 return this.helper.executeExtrinsic(2767 signer,2768 'api.tx.scheduler.cancelNamed',2769 [scheduledId],2770 true,2771 );2772 }27732774 changePriority(signer: TSigner, scheduledId: string, priority: number) {2775 return this.helper.executeExtrinsic(2776 signer,2777 'api.tx.scheduler.changeNamedPriority',2778 [scheduledId, priority],2779 true,2780 );2781 }27822783 scheduleAt<T extends UniqueHelper>(2784 executionBlockNumber: number,2785 options: ISchedulerOptions = {},2786 ) {2787 return this.schedule<T>('schedule', executionBlockNumber, options);2788 }27892790 scheduleAfter<T extends UniqueHelper>(2791 blocksBeforeExecution: number,2792 options: ISchedulerOptions = {},2793 ) {2794 return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2795 }27962797 schedule<T extends UniqueHelper>(2798 scheduleFn: 'schedule' | 'scheduleAfter',2799 blocksNum: number,2800 options: ISchedulerOptions = {},2801 ) {2802 2803 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2804 return this.helper.clone(ScheduledHelperType, {2805 scheduleFn,2806 blocksNum,2807 options,2808 }) as T;2809 }2810}28112812class CollatorSelectionGroup extends HelperGroup<UniqueHelper> {2813 2814 addInvulnerable(signer: TSigner, address: string) {2815 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.addInvulnerable', [address]);2816 }28172818 removeInvulnerable(signer: TSigner, address: string) {2819 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.removeInvulnerable', [address]);2820 }28212822 async getInvulnerables(): Promise<string[]> {2823 return (await this.helper.callRpc('api.query.collatorSelection.invulnerables')).map((x: any) => x.toHuman());2824 }28252826 2827 maxCollators(): number {2828 return (this.helper.getApi().consts.configuration.defaultCollatorSelectionMaxCollators.toJSON() as number);2829 }28302831 async getDesiredCollators(): Promise<number> {2832 return (await this.helper.callRpc('api.query.configuration.collatorSelectionDesiredCollatorsOverride')).toNumber();2833 }28342835 setLicenseBond(signer: TSigner, amount: bigint) {2836 return this.helper.executeExtrinsic(signer, 'api.tx.configuration.setCollatorSelectionLicenseBond', [amount]);2837 }28382839 async getLicenseBond(): Promise<bigint> {2840 return (await this.helper.callRpc('api.query.configuration.collatorSelectionLicenseBondOverride')).toBigInt();2841 }28422843 obtainLicense(signer: TSigner) {2844 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.getLicense', []);2845 }28462847 releaseLicense(signer: TSigner) {2848 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.releaseLicense', []);2849 }28502851 forceReleaseLicense(signer: TSigner, released: string) {2852 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.forceReleaseLicense', [released]);2853 }28542855 async hasLicense(address: string): Promise<bigint> {2856 return (await this.helper.callRpc('api.query.collatorSelection.licenseDepositOf', [address])).toBigInt();2857 }28582859 onboard(signer: TSigner) {2860 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.onboard', []);2861 }28622863 offboard(signer: TSigner) {2864 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.offboard', []);2865 }28662867 async getCandidates(): Promise<string[]> {2868 return (await this.helper.callRpc('api.query.collatorSelection.candidates')).map((x: any) => x.toHuman());2869 }2870}28712872class PreimageGroup extends HelperGroup<UniqueHelper> {2873 async getPreimageInfo(h256: string) {2874 return (await this.helper.callRpc('api.query.preimage.statusFor', [h256])).toJSON();2875 }28762877 287828792880288128822883288428852886 notePreimage(signer: TSigner, bytes: string | Uint8Array) {2887 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.notePreimage', [bytes]);2888 }28892890 289128922893289428952896 unnotePreimage(signer: TSigner, h256: string) {2897 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unnotePreimage', [h256]);2898 }28992900 290129022903290429052906 requestPreimage(signer: TSigner, h256: string) {2907 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.requestPreimage', [h256]);2908 }29092910 291129122913291429152916 unrequestPreimage(signer: TSigner, h256: string) {2917 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unrequestPreimage', [h256]);2918 }2919}29202921class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2922 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2923 await this.helper.executeExtrinsic(2924 signer,2925 'api.tx.foreignAssets.registerForeignAsset',2926 [ownerAddress, location, metadata],2927 true,2928 );2929 }29302931 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2932 await this.helper.executeExtrinsic(2933 signer,2934 'api.tx.foreignAssets.updateForeignAsset',2935 [foreignAssetId, location, metadata],2936 true,2937 );2938 }2939}29402941class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2942 palletName: string;29432944 constructor(helper: T, palletName: string) {2945 super(helper);29462947 this.palletName = palletName;2948 }29492950 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {2951 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);2952 }29532954 async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {2955 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);2956 }29572958 async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint) {2959 const destination = {2960 V1: {2961 parents: 0,2962 interior: {2963 X1: {2964 Parachain: destinationParaId,2965 },2966 },2967 },2968 };29692970 const beneficiary = {2971 V1: {2972 parents: 0,2973 interior: {2974 X1: {2975 AccountId32: {2976 network: 'Any',2977 id: targetAccount,2978 },2979 },2980 },2981 },2982 };29832984 const assets = {2985 V1: [2986 {2987 id: {2988 Concrete: {2989 parents: 0,2990 interior: 'Here',2991 },2992 },2993 fun: {2994 Fungible: amount,2995 },2996 },2997 ],2998 };29993000 const feeAssetItem = 0;30013002 await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);3003 }3004}30053006class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {3007 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {3008 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);3009 }30103011 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {3012 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);3013 }30143015 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {3016 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);3017 }3018}30193020class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {3021 async accounts(address: string, currencyId: any) {3022 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;3023 return BigInt(free);3024 }3025}30263027class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {3028 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {3029 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);3030 }30313032 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {3033 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);3034 }30353036 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {3037 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);3038 }30393040 async account(assetId: string | number, address: string) {3041 const accountAsset = (3042 await this.helper.callRpc('api.query.assets.account', [assetId, address])3043 ).toJSON()! as any;30443045 if (accountAsset !== null) {3046 return BigInt(accountAsset['balance']);3047 } else {3048 return null;3049 }3050 }3051}30523053class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {3054 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {3055 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);3056 }3057}30583059class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {3060 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {3061 const apiPrefix = 'api.tx.assetManager.';30623063 const registerTx = this.helper.constructApiCall(3064 apiPrefix + 'registerForeignAsset',3065 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],3066 );30673068 const setUnitsTx = this.helper.constructApiCall(3069 apiPrefix + 'setAssetUnitsPerSecond',3070 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],3071 );30723073 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);3074 const encodedProposal = batchCall?.method.toHex() || '';3075 return encodedProposal;3076 }30773078 async assetTypeId(location: any) {3079 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);3080 }3081}30823083class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {3084 notePreimagePallet: string;30853086 constructor(helper: MoonbeamHelper, options: {[key: string]: any} = {}) {3087 super(helper);3088 this.notePreimagePallet = options.notePreimagePallet;3089 }30903091 async notePreimage(signer: TSigner, encodedProposal: string) {3092 await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);3093 }30943095 externalProposeMajority(proposal: any) {3096 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);3097 }30983099 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {3100 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);3101 }31023103 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {3104 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);3105 }3106}31073108class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {3109 collective: string;31103111 constructor(helper: MoonbeamHelper, collective: string) {3112 super(helper);31133114 this.collective = collective;3115 }31163117 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {3118 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);3119 }31203121 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {3122 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);3123 }31243125 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {3126 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);3127 }31283129 async proposalCount() {3130 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));3131 }3132}31333134export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;3135export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;31363137export class UniqueHelper extends ChainHelperBase {3138 balance: BalanceGroup<UniqueHelper>;3139 collection: CollectionGroup;3140 nft: NFTGroup;3141 rft: RFTGroup;3142 ft: FTGroup;3143 staking: StakingGroup;3144 scheduler: SchedulerGroup;3145 collatorSelection: CollatorSelectionGroup;3146 preimage: PreimageGroup;3147 foreignAssets: ForeignAssetsGroup;3148 xcm: XcmGroup<UniqueHelper>;3149 xTokens: XTokensGroup<UniqueHelper>;3150 tokens: TokensGroup<UniqueHelper>;31513152 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3153 super(logger, options.helperBase ?? UniqueHelper);31543155 this.balance = new BalanceGroup(this);3156 this.collection = new CollectionGroup(this);3157 this.nft = new NFTGroup(this);3158 this.rft = new RFTGroup(this);3159 this.ft = new FTGroup(this);3160 this.staking = new StakingGroup(this);3161 this.scheduler = new SchedulerGroup(this);3162 this.collatorSelection = new CollatorSelectionGroup(this);3163 this.preimage = new PreimageGroup(this);3164 this.foreignAssets = new ForeignAssetsGroup(this);3165 this.xcm = new XcmGroup(this, 'polkadotXcm');3166 this.xTokens = new XTokensGroup(this);3167 this.tokens = new TokensGroup(this);3168 }31693170 getSudo<T extends UniqueHelper>() {3171 3172 const SudoHelperType = SudoHelper(this.helperBase);3173 return this.clone(SudoHelperType) as T;3174 }3175}31763177export class XcmChainHelper extends ChainHelperBase {3178 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {3179 const wsProvider = new WsProvider(wsEndpoint);3180 this.api = new ApiPromise({3181 provider: wsProvider,3182 });3183 await this.api.isReadyOrError;3184 this.network = await UniqueHelper.detectNetwork(this.api);3185 }3186}31873188export class RelayHelper extends XcmChainHelper {3189 balance: SubstrateBalanceGroup<RelayHelper>;3190 xcm: XcmGroup<RelayHelper>;31913192 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3193 super(logger, options.helperBase ?? RelayHelper);31943195 this.balance = new SubstrateBalanceGroup(this);3196 this.xcm = new XcmGroup(this, 'xcmPallet');3197 }3198}31993200export class WestmintHelper extends XcmChainHelper {3201 balance: SubstrateBalanceGroup<WestmintHelper>;3202 xcm: XcmGroup<WestmintHelper>;3203 assets: AssetsGroup<WestmintHelper>;3204 xTokens: XTokensGroup<WestmintHelper>;32053206 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3207 super(logger, options.helperBase ?? WestmintHelper);32083209 this.balance = new SubstrateBalanceGroup(this);3210 this.xcm = new XcmGroup(this, 'polkadotXcm');3211 this.assets = new AssetsGroup(this);3212 this.xTokens = new XTokensGroup(this);3213 }3214}32153216export class MoonbeamHelper extends XcmChainHelper {3217 balance: EthereumBalanceGroup<MoonbeamHelper>;3218 assetManager: MoonbeamAssetManagerGroup;3219 assets: AssetsGroup<MoonbeamHelper>;3220 xTokens: XTokensGroup<MoonbeamHelper>;3221 democracy: MoonbeamDemocracyGroup;3222 collective: {3223 council: MoonbeamCollectiveGroup,3224 techCommittee: MoonbeamCollectiveGroup,3225 };32263227 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3228 super(logger, options.helperBase ?? MoonbeamHelper);32293230 this.balance = new EthereumBalanceGroup(this);3231 this.assetManager = new MoonbeamAssetManagerGroup(this);3232 this.assets = new AssetsGroup(this);3233 this.xTokens = new XTokensGroup(this);3234 this.democracy = new MoonbeamDemocracyGroup(this, options);3235 this.collective = {3236 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),3237 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),3238 };3239 }3240}32413242export class AcalaHelper extends XcmChainHelper {3243 balance: SubstrateBalanceGroup<AcalaHelper>;3244 assetRegistry: AcalaAssetRegistryGroup;3245 xTokens: XTokensGroup<AcalaHelper>;3246 tokens: TokensGroup<AcalaHelper>;32473248 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3249 super(logger, options.helperBase ?? AcalaHelper);32503251 this.balance = new SubstrateBalanceGroup(this);3252 this.assetRegistry = new AcalaAssetRegistryGroup(this);3253 this.xTokens = new XTokensGroup(this);3254 this.tokens = new TokensGroup(this);3255 }32563257 getSudo<T extends AcalaHelper>() {3258 3259 const SudoHelperType = SudoHelper(this.helperBase);3260 return this.clone(SudoHelperType) as T;3261 }3262}326332643265function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3266 return class extends Base {3267 scheduleFn: 'schedule' | 'scheduleAfter';3268 blocksNum: number;3269 options: ISchedulerOptions;32703271 constructor(...args: any[]) {3272 const logger = args[0] as ILogger;3273 const options = args[1] as {3274 scheduleFn: 'schedule' | 'scheduleAfter',3275 blocksNum: number,3276 options: ISchedulerOptions3277 };32783279 super(logger);32803281 this.scheduleFn = options.scheduleFn;3282 this.blocksNum = options.blocksNum;3283 this.options = options.options;3284 }32853286 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3287 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);32883289 const mandatorySchedArgs = [3290 this.blocksNum,3291 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3292 this.options.priority ?? null,3293 scheduledTx,3294 ];32953296 let schedArgs;3297 let scheduleFn;32983299 if (this.options.scheduledId) {3300 schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];33013302 if (this.scheduleFn == 'schedule') {3303 scheduleFn = 'scheduleNamed';3304 } else if (this.scheduleFn == 'scheduleAfter') {3305 scheduleFn = 'scheduleNamedAfter';3306 }3307 } else {3308 schedArgs = mandatorySchedArgs;3309 scheduleFn = this.scheduleFn;3310 }33113312 const extrinsic = 'api.tx.scheduler.' + scheduleFn;33133314 return super.executeExtrinsic(3315 sender,3316 extrinsic,3317 schedArgs,3318 expectSuccess,3319 );3320 }3321 };3322}332333243325function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3326 return class extends Base {3327 constructor(...args: any[]) {3328 super(...args);3329 }33303331 async executeExtrinsic(3332 sender: IKeyringPair,3333 extrinsic: string,3334 params: any[],3335 expectSuccess?: boolean,3336 options: Partial<SignerOptions>|null = null,3337 ): Promise<ITransactionResult> {3338 const call = this.constructApiCall(extrinsic, params);3339 const result = await super.executeExtrinsic(3340 sender,3341 'api.tx.sudo.sudo',3342 [call],3343 expectSuccess,3344 options,3345 );33463347 if (result.status === 'Fail') return result;33483349 const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;3350 if (data.isErr) {3351 if (data.asErr.isModule) {3352 const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;3353 const metaError = super.getApi()?.registry.findMetaError(error);3354 throw new Error(`${metaError.section}.${metaError.name}`);3355 } else {3356 throw new Error(data.asErr.toHuman());3357 }3358 }3359 return result;3360 }3361 };3362}33633364export class UniqueBaseCollection {3365 helper: UniqueHelper;3366 collectionId: number;33673368 constructor(collectionId: number, uniqueHelper: UniqueHelper) {3369 this.collectionId = collectionId;3370 this.helper = uniqueHelper;3371 }33723373 async getData() {3374 return await this.helper.collection.getData(this.collectionId);3375 }33763377 async getLastTokenId() {3378 return await this.helper.collection.getLastTokenId(this.collectionId);3379 }33803381 async doesTokenExist(tokenId: number) {3382 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3383 }33843385 async getAdmins() {3386 return await this.helper.collection.getAdmins(this.collectionId);3387 }33883389 async getAllowList() {3390 return await this.helper.collection.getAllowList(this.collectionId);3391 }33923393 async getEffectiveLimits() {3394 return await this.helper.collection.getEffectiveLimits(this.collectionId);3395 }33963397 async getProperties(propertyKeys?: string[] | null) {3398 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3399 }34003401 async getPropertiesConsumedSpace() {3402 return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3403 }34043405 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3406 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3407 }34083409 async getOptions() {3410 return await this.helper.collection.getCollectionOptions(this.collectionId);3411 }34123413 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3414 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3415 }34163417 async confirmSponsorship(signer: TSigner) {3418 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3419 }34203421 async removeSponsor(signer: TSigner) {3422 return await this.helper.collection.removeSponsor(signer, this.collectionId);3423 }34243425 async setLimits(signer: TSigner, limits: ICollectionLimits) {3426 return await this.helper.collection.setLimits(signer, this.collectionId, limits);3427 }34283429 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3430 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3431 }34323433 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3434 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3435 }34363437 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3438 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3439 }34403441 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3442 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3443 }34443445 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3446 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3447 }34483449 async setProperties(signer: TSigner, properties: IProperty[]) {3450 return await this.helper.collection.setProperties(signer, this.collectionId, properties);3451 }34523453 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3454 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3455 }34563457 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3458 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3459 }34603461 async enableNesting(signer: TSigner, permissions: INestingPermissions) {3462 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3463 }34643465 async disableNesting(signer: TSigner) {3466 return await this.helper.collection.disableNesting(signer, this.collectionId);3467 }34683469 async burn(signer: TSigner) {3470 return await this.helper.collection.burn(signer, this.collectionId);3471 }34723473 scheduleAt<T extends UniqueHelper>(3474 executionBlockNumber: number,3475 options: ISchedulerOptions = {},3476 ) {3477 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3478 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3479 }34803481 scheduleAfter<T extends UniqueHelper>(3482 blocksBeforeExecution: number,3483 options: ISchedulerOptions = {},3484 ) {3485 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3486 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3487 }34883489 getSudo<T extends UniqueHelper>() {3490 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3491 }3492}349334943495export class UniqueNFTCollection extends UniqueBaseCollection {3496 getTokenObject(tokenId: number) {3497 return new UniqueNFToken(tokenId, this);3498 }34993500 async getTokensByAddress(addressObj: ICrossAccountId) {3501 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3502 }35033504 async getToken(tokenId: number, blockHashAt?: string) {3505 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3506 }35073508 async getTokenOwner(tokenId: number, blockHashAt?: string) {3509 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3510 }35113512 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3513 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3514 }35153516 async getTokenChildren(tokenId: number, blockHashAt?: string) {3517 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3518 }35193520 async getPropertyPermissions(propertyKeys: string[] | null = null) {3521 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3522 }35233524 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3525 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3526 }35273528 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3529 const api = this.helper.getApi();3530 const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();35313532 return (props! as any).consumedSpace;3533 }35343535 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3536 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3537 }35383539 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3540 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3541 }35423543 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3544 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3545 }35463547 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3548 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3549 }35503551 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3552 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3553 }35543555 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3556 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3557 }35583559 async burnToken(signer: TSigner, tokenId: number) {3560 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3561 }35623563 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3564 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3565 }35663567 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3568 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3569 }35703571 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3572 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3573 }35743575 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3576 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3577 }35783579 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3580 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3581 }35823583 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3584 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3585 }35863587 scheduleAt<T extends UniqueHelper>(3588 executionBlockNumber: number,3589 options: ISchedulerOptions = {},3590 ) {3591 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3592 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3593 }35943595 scheduleAfter<T extends UniqueHelper>(3596 blocksBeforeExecution: number,3597 options: ISchedulerOptions = {},3598 ) {3599 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3600 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3601 }36023603 getSudo<T extends UniqueHelper>() {3604 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3605 }3606}360736083609export class UniqueRFTCollection extends UniqueBaseCollection {3610 getTokenObject(tokenId: number) {3611 return new UniqueRFToken(tokenId, this);3612 }36133614 async getToken(tokenId: number, blockHashAt?: string) {3615 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3616 }36173618 async getTokenOwner(tokenId: number, blockHashAt?: string) {3619 return await this.helper.rft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3620 }36213622 async getTokensByAddress(addressObj: ICrossAccountId) {3623 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3624 }36253626 async getTop10TokenOwners(tokenId: number) {3627 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3628 }36293630 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3631 return await this.helper.rft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3632 }36333634 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3635 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3636 }36373638 async getTokenTotalPieces(tokenId: number) {3639 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3640 }36413642 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3643 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3644 }36453646 async getPropertyPermissions(propertyKeys: string[] | null = null) {3647 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3648 }36493650 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3651 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3652 }36533654 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3655 const api = this.helper.getApi();3656 const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();36573658 return (props! as any).consumedSpace;3659 }36603661 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3662 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3663 }36643665 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3666 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3667 }36683669 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3670 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3671 }36723673 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3674 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3675 }36763677 async mintToken(signer: TSigner, pieces = 1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3678 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3679 }36803681 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3682 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3683 }36843685 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3686 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3687 }36883689 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3690 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3691 }36923693 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3694 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3695 }36963697 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3698 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3699 }37003701 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3702 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3703 }37043705 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3706 return await this.helper.rft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3707 }37083709 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3710 return await this.helper.rft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3711 }37123713 scheduleAt<T extends UniqueHelper>(3714 executionBlockNumber: number,3715 options: ISchedulerOptions = {},3716 ) {3717 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3718 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3719 }37203721 scheduleAfter<T extends UniqueHelper>(3722 blocksBeforeExecution: number,3723 options: ISchedulerOptions = {},3724 ) {3725 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3726 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3727 }37283729 getSudo<T extends UniqueHelper>() {3730 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3731 }3732}373337343735export class UniqueFTCollection extends UniqueBaseCollection {3736 async getBalance(addressObj: ICrossAccountId) {3737 return await this.helper.ft.getBalance(this.collectionId, addressObj);3738 }37393740 async getTotalPieces() {3741 return await this.helper.ft.getTotalPieces(this.collectionId);3742 }37433744 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3745 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3746 }37473748 async getTop10Owners() {3749 return await this.helper.ft.getTop10Owners(this.collectionId);3750 }37513752 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3753 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3754 }37553756 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3757 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3758 }37593760 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3761 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3762 }37633764 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3765 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3766 }37673768 async burnTokens(signer: TSigner, amount=1n) {3769 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3770 }37713772 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3773 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3774 }37753776 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3777 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3778 }37793780 scheduleAt<T extends UniqueHelper>(3781 executionBlockNumber: number,3782 options: ISchedulerOptions = {},3783 ) {3784 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3785 return new UniqueFTCollection(this.collectionId, scheduledHelper);3786 }37873788 scheduleAfter<T extends UniqueHelper>(3789 blocksBeforeExecution: number,3790 options: ISchedulerOptions = {},3791 ) {3792 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3793 return new UniqueFTCollection(this.collectionId, scheduledHelper);3794 }37953796 getSudo<T extends UniqueHelper>() {3797 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3798 }3799}380038013802export class UniqueBaseToken {3803 collection: UniqueNFTCollection | UniqueRFTCollection;3804 collectionId: number;3805 tokenId: number;38063807 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3808 this.collection = collection;3809 this.collectionId = collection.collectionId;3810 this.tokenId = tokenId;3811 }38123813 async getNextSponsored(addressObj: ICrossAccountId) {3814 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3815 }38163817 async getProperties(propertyKeys?: string[] | null) {3818 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3819 }38203821 async getTokenPropertiesConsumedSpace() {3822 return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3823 }38243825 async setProperties(signer: TSigner, properties: IProperty[]) {3826 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3827 }38283829 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3830 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3831 }38323833 async doesExist() {3834 return await this.collection.doesTokenExist(this.tokenId);3835 }38363837 nestingAccount() {3838 return this.collection.helper.util.getTokenAccount(this);3839 }38403841 scheduleAt<T extends UniqueHelper>(3842 executionBlockNumber: number,3843 options: ISchedulerOptions = {},3844 ) {3845 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3846 return new UniqueBaseToken(this.tokenId, scheduledCollection);3847 }38483849 scheduleAfter<T extends UniqueHelper>(3850 blocksBeforeExecution: number,3851 options: ISchedulerOptions = {},3852 ) {3853 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3854 return new UniqueBaseToken(this.tokenId, scheduledCollection);3855 }38563857 getSudo<T extends UniqueHelper>() {3858 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3859 }3860}386138623863export class UniqueNFToken extends UniqueBaseToken {3864 collection: UniqueNFTCollection;38653866 constructor(tokenId: number, collection: UniqueNFTCollection) {3867 super(tokenId, collection);3868 this.collection = collection;3869 }38703871 async getData(blockHashAt?: string) {3872 return await this.collection.getToken(this.tokenId, blockHashAt);3873 }38743875 async getOwner(blockHashAt?: string) {3876 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3877 }38783879 async getTopmostOwner(blockHashAt?: string) {3880 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3881 }38823883 async getChildren(blockHashAt?: string) {3884 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3885 }38863887 async nest(signer: TSigner, toTokenObj: IToken) {3888 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3889 }38903891 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3892 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3893 }38943895 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3896 return await this.collection.transferToken(signer, this.tokenId, addressObj);3897 }38983899 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3900 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3901 }39023903 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3904 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3905 }39063907 async isApproved(toAddressObj: ICrossAccountId) {3908 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3909 }39103911 async burn(signer: TSigner) {3912 return await this.collection.burnToken(signer, this.tokenId);3913 }39143915 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3916 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3917 }39183919 scheduleAt<T extends UniqueHelper>(3920 executionBlockNumber: number,3921 options: ISchedulerOptions = {},3922 ) {3923 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3924 return new UniqueNFToken(this.tokenId, scheduledCollection);3925 }39263927 scheduleAfter<T extends UniqueHelper>(3928 blocksBeforeExecution: number,3929 options: ISchedulerOptions = {},3930 ) {3931 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3932 return new UniqueNFToken(this.tokenId, scheduledCollection);3933 }39343935 getSudo<T extends UniqueHelper>() {3936 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3937 }3938}39393940export class UniqueRFToken extends UniqueBaseToken {3941 collection: UniqueRFTCollection;39423943 constructor(tokenId: number, collection: UniqueRFTCollection) {3944 super(tokenId, collection);3945 this.collection = collection;3946 }39473948 async getData(blockHashAt?: string) {3949 return await this.collection.getToken(this.tokenId, blockHashAt);3950 }39513952 async getOwner(blockHashAt?: string) {3953 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3954 }39553956 async getTop10Owners() {3957 return await this.collection.getTop10TokenOwners(this.tokenId);3958 }39593960 async getTopmostOwner(blockHashAt?: string) {3961 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3962 }39633964 async nest(signer: TSigner, toTokenObj: IToken) {3965 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3966 }39673968 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3969 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3970 }39713972 async getBalance(addressObj: ICrossAccountId) {3973 return await this.collection.getTokenBalance(this.tokenId, addressObj);3974 }39753976 async getTotalPieces() {3977 return await this.collection.getTokenTotalPieces(this.tokenId);3978 }39793980 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3981 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3982 }39833984 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3985 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3986 }39873988 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3989 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3990 }39913992 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3993 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3994 }39953996 async repartition(signer: TSigner, amount: bigint) {3997 return await this.collection.repartitionToken(signer, this.tokenId, amount);3998 }39994000 async burn(signer: TSigner, amount=1n) {4001 return await this.collection.burnToken(signer, this.tokenId, amount);4002 }40034004 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {4005 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);4006 }40074008 scheduleAt<T extends UniqueHelper>(4009 executionBlockNumber: number,4010 options: ISchedulerOptions = {},4011 ) {4012 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);4013 return new UniqueRFToken(this.tokenId, scheduledCollection);4014 }40154016 scheduleAfter<T extends UniqueHelper>(4017 blocksBeforeExecution: number,4018 options: ISchedulerOptions = {},4019 ) {4020 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);4021 return new UniqueRFToken(this.tokenId, scheduledCollection);4022 }40234024 getSudo<T extends UniqueHelper>() {4025 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());4026 }4027}