12345678import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISchedulerOptions, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, IForeignAssetMetadata, TNetworks, MoonbeamAssetInfo, DemocracyStandardAccountVote, AcalaAssetMetadata} from './types';1314export class CrossAccountId implements ICrossAccountId {15 Substrate?: TSubstrateAccount;16 Ethereum?: TEthereumAccount;1718 constructor(account: ICrossAccountId) {19 if (account.Substrate) this.Substrate = account.Substrate;20 if (account.Ethereum) this.Ethereum = account.Ethereum;21 }2223 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {24 switch (domain) {25 case 'Substrate': return new CrossAccountId({Substrate: account.address});26 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();27 }28 }2930 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {31 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});32 }3334 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {35 return encodeAddress(decodeAddress(address), ss58Format);36 }3738 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {39 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});40 }41 42 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {43 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);44 return this;45 }4647 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {48 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));49 }5051 toEthereum(): CrossAccountId {52 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});53 return this;54 }5556 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {57 return evmToAddress(address, ss58Format);58 }5960 toSubstrate(ss58Format?: number): CrossAccountId {61 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});62 return this;63 }64 65 toLowerCase(): CrossAccountId {66 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();67 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();68 return this;69 }70}7172const nesting = {73 toChecksumAddress(address: string): string {74 if (typeof address === 'undefined') return '';7576 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);7778 address = address.toLowerCase().replace(/^0x/i,'');79 const addressHash = keccakAsHex(address).replace(/^0x/i,'');80 const checksumAddress = ['0x'];8182 for (let i = 0; i < address.length; i++) {83 84 if (parseInt(addressHash[i], 16) > 7) {85 checksumAddress.push(address[i].toUpperCase());86 } else {87 checksumAddress.push(address[i]);88 }89 }90 return checksumAddress.join('');91 },92 tokenIdToAddress(collectionId: number, tokenId: number) {93 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);94 },95};9697class UniqueUtil {98 static transactionStatus = {99 NOT_READY: 'NotReady',100 FAIL: 'Fail',101 SUCCESS: 'Success',102 };103104 static chainLogType = {105 EXTRINSIC: 'extrinsic',106 RPC: 'rpc',107 };108109 static getTokenAccount(token: IToken): CrossAccountId {110 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});111 }112113 static getTokenAddress(token: IToken): string {114 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);115 }116117 static getDefaultLogger(): ILogger {118 return {119 log(msg: any, level = 'INFO') {120 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));121 },122 level: {123 ERROR: 'ERROR',124 WARNING: 'WARNING',125 INFO: 'INFO',126 },127 };128 }129130 static vec2str(arr: string[] | number[]) {131 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');132 }133134 static str2vec(string: string) {135 if (typeof string !== 'string') return string;136 return Array.from(string).map(x => x.charCodeAt(0));137 }138139 static fromSeed(seed: string, ss58Format = 42) {140 const keyring = new Keyring({type: 'sr25519', ss58Format});141 return keyring.addFromUri(seed);142 }143144 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {145 if (creationResult.status !== this.transactionStatus.SUCCESS) {146 throw Error('Unable to create collection!');147 }148149 let collectionId = null;150 creationResult.result.events.forEach(({event: {data, method, section}}) => {151 if ((section === 'common') && (method === 'CollectionCreated')) {152 collectionId = parseInt(data[0].toString(), 10);153 }154 });155156 if (collectionId === null) {157 throw Error('No CollectionCreated event was found!');158 }159160 return collectionId;161 }162163 static extractTokensFromCreationResult(creationResult: ITransactionResult): {164 success: boolean, 165 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],166 } {167 if (creationResult.status !== this.transactionStatus.SUCCESS) {168 throw Error('Unable to create tokens!');169 }170 let success = false;171 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];172 creationResult.result.events.forEach(({event: {data, method, section}}) => {173 if (method === 'ExtrinsicSuccess') {174 success = true;175 } else if ((section === 'common') && (method === 'ItemCreated')) {176 tokens.push({177 collectionId: parseInt(data[0].toString(), 10),178 tokenId: parseInt(data[1].toString(), 10),179 owner: data[2].toHuman(),180 amount: data[3].toBigInt(),181 });182 }183 });184 return {success, tokens};185 }186187 static extractTokensFromBurnResult(burnResult: ITransactionResult): {188 success: boolean, 189 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],190 } {191 if (burnResult.status !== this.transactionStatus.SUCCESS) {192 throw Error('Unable to burn tokens!');193 }194 let success = false;195 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];196 burnResult.result.events.forEach(({event: {data, method, section}}) => {197 if (method === 'ExtrinsicSuccess') {198 success = true;199 } else if ((section === 'common') && (method === 'ItemDestroyed')) {200 tokens.push({201 collectionId: parseInt(data[0].toString(), 10),202 tokenId: parseInt(data[1].toString(), 10),203 owner: data[2].toHuman(),204 amount: data[3].toBigInt(),205 });206 }207 });208 return {success, tokens};209 }210211 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {212 let eventId = null;213 events.forEach(({event: {data, method, section}}) => {214 if ((section === expectedSection) && (method === expectedMethod)) {215 eventId = parseInt(data[0].toString(), 10);216 }217 });218219 if (eventId === null) {220 throw Error(`No ${expectedMethod} event was found!`);221 }222 return eventId === collectionId;223 }224225 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {226 const normalizeAddress = (address: string | ICrossAccountId) => {227 if(typeof address === 'string') return address;228 const obj = {} as any;229 Object.keys(address).forEach(k => {230 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];231 });232 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);233 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();234 return address;235 };236 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;237 events.forEach(({event: {data, method, section}}) => {238 if ((section === 'common') && (method === 'Transfer')) {239 const hData = (data as any).toJSON();240 transfer = {241 collectionId: hData[0],242 tokenId: hData[1],243 from: normalizeAddress(hData[2]),244 to: normalizeAddress(hData[3]),245 amount: BigInt(hData[4]),246 };247 }248 });249 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;250 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);251 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);252 isSuccess = isSuccess && amount === transfer.amount;253 return isSuccess;254 }255256 static bigIntToDecimals(number: bigint, decimals = 18) {257 const numberStr = number.toString();258 const dotPos = numberStr.length - decimals;259 260 if (dotPos <= 0) {261 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;262 } else {263 const intPart = numberStr.substring(0, dotPos);264 const fractPart = numberStr.substring(dotPos);265 return intPart + '.' + fractPart;266 }267 }268}269270class UniqueEventHelper {271 private static extractIndex(index: any): [number, number] | string {272 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];273 return index.toJSON();274 }275276 private static extractSub(data: any, subTypes: any): {[key: string]: any} {277 let obj: any = {};278 let index = 0;279280 if (data.entries) {281 for(const [key, value] of data.entries()) {282 obj[key] = this.extractData(value, subTypes[index]);283 index++;284 }285 } else obj = data.toJSON();286287 return obj;288 }289 290 private static extractData(data: any, type: any): any {291 if(!type) return data.toHuman();292 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();293 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();294 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);295 return data.toHuman();296 }297298 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {299 const parsedEvents: IEvent[] = [];300301 events.forEach((record) => {302 const {event, phase} = record;303 const types = event.typeDef;304305 const eventData: IEvent = {306 section: event.section.toString(),307 method: event.method.toString(),308 index: this.extractIndex(event.index),309 data: [],310 phase: phase.toJSON(),311 };312313 event.data.forEach((val: any, index: number) => {314 eventData.data.push(this.extractData(val, types[index]));315 });316317 parsedEvents.push(eventData);318 });319320 return parsedEvents;321 }322}323324export class ChainHelperBase {325 helperBase: any;326327 transactionStatus = UniqueUtil.transactionStatus;328 chainLogType = UniqueUtil.chainLogType;329 util: typeof UniqueUtil;330 eventHelper: typeof UniqueEventHelper;331 logger: ILogger;332 api: ApiPromise | null;333 forcedNetwork: TNetworks | null;334 network: TNetworks | null;335 chainLog: IUniqueHelperLog[];336 children: ChainHelperBase[];337 address: AddressGroup;338 chain: ChainGroup;339340 constructor(logger?: ILogger, helperBase?: any) {341 this.helperBase = helperBase;342343 this.util = UniqueUtil;344 this.eventHelper = UniqueEventHelper;345 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();346 this.logger = logger;347 this.api = null;348 this.forcedNetwork = null;349 this.network = null;350 this.chainLog = [];351 this.children = [];352 this.address = new AddressGroup(this);353 this.chain = new ChainGroup(this);354 }355356 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {357 Object.setPrototypeOf(helperCls.prototype, this);358 const newHelper = new helperCls(this.logger, options);359360 newHelper.api = this.api;361 newHelper.network = this.network;362 newHelper.forceNetwork = this.forceNetwork;363364 this.children.push(newHelper);365366 return newHelper;367 }368369 getApi(): ApiPromise {370 if(this.api === null) throw Error('API not initialized');371 return this.api;372 }373374 clearChainLog(): void {375 this.chainLog = [];376 }377378 forceNetwork(value: TNetworks): void {379 this.forcedNetwork = value;380 }381382 async connect(wsEndpoint: string, listeners?: IApiListeners) {383 if (this.api !== null) throw Error('Already connected');384 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);385 this.api = api;386 this.network = network;387 }388389 async disconnect() {390 for (const child of this.children) {391 child.clearApi();392 }393394 if (this.api === null) return;395 await this.api.disconnect();396 this.clearApi();397 }398399 clearApi() {400 this.api = null;401 this.network = null;402 }403404 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {405 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;406 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];407408 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;409410 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;411 return 'opal';412 }413414 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {415 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});416 await api.isReady;417418 const network = await this.detectNetwork(api);419420 await api.disconnect();421422 return network;423 }424425 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{426 api: ApiPromise;427 network: TNetworks;428 }> {429 if(typeof network === 'undefined' || network === null) network = 'opal';430 const supportedRPC = {431 opal: {432 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,433 },434 quartz: {435 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,436 },437 unique: {438 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,439 },440 rococo: {},441 westend: {},442 moonbeam: {},443 moonriver: {},444 acala: {},445 karura: {},446 westmint: {},447 };448 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);449 const rpc = supportedRPC[network];450451 452 453454 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});455456 await api.isReadyOrError;457458 if (typeof listeners === 'undefined') listeners = {};459 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {460 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;461 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);462 }463464 return {api, network};465 }466467 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {468 const {events, status} = data;469 if (status.isReady) {470 return this.transactionStatus.NOT_READY;471 }472 if (status.isBroadcast) {473 return this.transactionStatus.NOT_READY;474 }475 if (status.isInBlock || status.isFinalized) {476 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');477 if (errors.length > 0) {478 return this.transactionStatus.FAIL;479 }480 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {481 return this.transactionStatus.SUCCESS;482 }483 }484485 return this.transactionStatus.FAIL;486 }487488 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {489 const sign = (callback: any) => {490 if(options !== null) return transaction.signAndSend(sender, options, callback);491 return transaction.signAndSend(sender, callback);492 };493 494 return new Promise(async (resolve, reject) => {495 try {496 const unsub = await sign((result: any) => {497 const status = this.getTransactionStatus(result);498499 if (status === this.transactionStatus.SUCCESS) {500 this.logger.log(`${label} successful`);501 unsub();502 resolve({result, status});503 } else if (status === this.transactionStatus.FAIL) {504 let moduleError = null;505506 if (result.hasOwnProperty('dispatchError')) {507 const dispatchError = result['dispatchError'];508509 if (dispatchError) {510 if (dispatchError.isModule) {511 const modErr = dispatchError.asModule;512 const errorMeta = dispatchError.registry.findMetaError(modErr);513514 moduleError = `${errorMeta.section}.${errorMeta.name}`;515 } else {516 moduleError = dispatchError.toHuman();517 }518 } else {519 this.logger.log(result, this.logger.level.ERROR);520 }521 }522523 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);524 unsub();525 reject({status, moduleError, result});526 }527 });528 } catch (e) {529 this.logger.log(e, this.logger.level.ERROR);530 reject(e);531 }532 });533 }534535 constructApiCall(apiCall: string, params: any[]) {536 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);537 let call = this.getApi() as any;538 for(const part of apiCall.slice(4).split('.')) {539 call = call[part];540 }541 return call(...params);542 }543544 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null) {545 if(this.api === null) throw Error('API not initialized');546 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);547548 const startTime = (new Date()).getTime();549 let result: ITransactionResult;550 let events: IEvent[] = [];551 try {552 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;553 events = this.eventHelper.extractEvents(result.result.events);554 }555 catch(e) {556 if(!(e as object).hasOwnProperty('status')) throw e;557 result = e as ITransactionResult;558 }559560 const endTime = (new Date()).getTime();561562 const log = {563 executedAt: endTime,564 executionTime: endTime - startTime,565 type: this.chainLogType.EXTRINSIC,566 status: result.status,567 call: extrinsic,568 signer: this.getSignerAddress(sender),569 params,570 } as IUniqueHelperLog;571572 if(result.status !== this.transactionStatus.SUCCESS) {573 if (result.moduleError) log.moduleError = result.moduleError;574 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;575 }576 if(events.length > 0) log.events = events;577578 this.chainLog.push(log);579580 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {581 if (result.moduleError) throw Error(`${result.moduleError}`);582 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));583 }584 return result;585 }586587 async callRpc(rpc: string, params?: any[]) {588 if(typeof params === 'undefined') params = [];589 if(this.api === null) throw Error('API not initialized');590 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);591592 const startTime = (new Date()).getTime();593 let result;594 let error = null;595 const log = {596 type: this.chainLogType.RPC,597 call: rpc,598 params,599 } as IUniqueHelperLog;600601 try {602 result = await this.constructApiCall(rpc, params);603 }604 catch(e) {605 error = e;606 }607608 const endTime = (new Date()).getTime();609610 log.executedAt = endTime;611 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';612 log.executionTime = endTime - startTime;613614 this.chainLog.push(log);615616 if(error !== null) throw error;617618 return result;619 }620621 getSignerAddress(signer: IKeyringPair | string): string {622 if(typeof signer === 'string') return signer;623 return signer.address;624 }625626 fetchAllPalletNames(): string[] {627 if(this.api === null) throw Error('API not initialized');628 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());629 }630631 fetchMissingPalletNames(requiredPallets: string[]): string[] {632 const palletNames = this.fetchAllPalletNames();633 return requiredPallets.filter(p => !palletNames.includes(p));634 }635}636637638class HelperGroup<T extends ChainHelperBase> {639 helper: T;640641 constructor(uniqueHelper: T) {642 this.helper = uniqueHelper;643 }644}645646647class CollectionGroup extends HelperGroup<UniqueHelper> {648 649650651652653654655656657 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {658 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();659 }660661 662663664665666 async getTotalCount(): Promise<number> {667 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();668 }669670 671672673674675676677678679 async getData(collectionId: number): Promise<{680 id: number;681 name: string;682 description: string;683 tokensCount: number;684 admins: CrossAccountId[];685 normalizedOwner: TSubstrateAccount;686 raw: any687 } | null> {688 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);689 const humanCollection = collection.toHuman(), collectionData = {690 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],691 raw: humanCollection,692 } as any, jsonCollection = collection.toJSON();693 if (humanCollection === null) return null;694 collectionData.raw.limits = jsonCollection.limits;695 collectionData.raw.permissions = jsonCollection.permissions;696 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);697 for (const key of ['name', 'description']) {698 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);699 }700701 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))702 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)703 : 0;704 collectionData.admins = await this.getAdmins(collectionId);705706 return collectionData;707 }708709 710711712713714715716717 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {718 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();719720 return normalize721 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())722 : admins;723 }724725 726727728729730731732 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {733 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();734 return normalize735 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())736 : allowListed;737 }738739 740741742743744745746 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {747 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();748 }749750 751752753754755756757758 async burn(signer: TSigner, collectionId: number): Promise<boolean> {759 const result = await this.helper.executeExtrinsic(760 signer,761 'api.tx.unique.destroyCollection', [collectionId],762 true,763 );764765 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');766 }767768 769770771772773774775776777 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {778 const result = await this.helper.executeExtrinsic(779 signer,780 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],781 true,782 );783784 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');785 }786787 788789790791792793794795 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {796 const result = await this.helper.executeExtrinsic(797 signer,798 'api.tx.unique.confirmSponsorship', [collectionId],799 true,800 );801802 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');803 }804805 806807808809810811812813 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {814 const result = await this.helper.executeExtrinsic(815 signer,816 'api.tx.unique.removeCollectionSponsor', [collectionId],817 true,818 );819820 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');821 }822823 824825826827828829830831832833834835836837838839840 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {841 const result = await this.helper.executeExtrinsic(842 signer,843 'api.tx.unique.setCollectionLimits', [collectionId, limits],844 true,845 );846847 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');848 }849850 851852853854855856857858859 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {860 const result = await this.helper.executeExtrinsic(861 signer,862 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],863 true,864 );865866 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');867 }868869 870871872873874875876877878 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {879 const result = await this.helper.executeExtrinsic(880 signer,881 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],882 true,883 );884885 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');886 }887888 889890891892893894895896897 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {898 const result = await this.helper.executeExtrinsic(899 signer,900 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],901 true,902 );903904 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');905 }906907 908909910911912913914915 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {916 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();917 }918919 920921922923924925926 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {927 const result = await this.helper.executeExtrinsic(928 signer,929 'api.tx.unique.addToAllowList', [collectionId, addressObj],930 true,931 );932933 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');934 }935936 937938939940941942943944 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {945 const result = await this.helper.executeExtrinsic(946 signer,947 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],948 true,949 );950951 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');952 }953954 955956957958959960961962963 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {964 const result = await this.helper.executeExtrinsic(965 signer,966 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],967 true,968 );969970 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');971 }972973 974975976977978979980981982 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {983 return await this.setPermissions(signer, collectionId, {nesting: permissions});984 }985986 987988989990991992993994 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {995 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});996 }997998 99910001001100210031004100510061007 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1008 const result = await this.helper.executeExtrinsic(1009 signer,1010 'api.tx.unique.setCollectionProperties', [collectionId, properties],1011 true,1012 );10131014 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1015 }10161017 10181019102010211022102310241025 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1026 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1027 }10281029 async getCollectionOptions(collectionId: number) {1030 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1031 }10321033 103410351036103710381039104010411042 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1043 const result = await this.helper.executeExtrinsic(1044 signer,1045 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1046 true,1047 );10481049 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1050 }10511052 10531054105510561057105810591060106110621063 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1064 const result = await this.helper.executeExtrinsic(1065 signer,1066 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1067 true, 1068 );10691070 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1071 }10721073 1074107510761077107810791080108110821083108410851086 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1087 const result = await this.helper.executeExtrinsic(1088 signer,1089 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1090 true, 1091 );1092 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1093 }10941095 10961097109810991100110111021103110411051106 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1107 const burnResult = await this.helper.executeExtrinsic(1108 signer,1109 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1110 true, 1111 );1112 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1113 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1114 return burnedTokens.success;1115 }11161117 11181119112011211122112311241125112611271128 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1129 const burnResult = await this.helper.executeExtrinsic(1130 signer,1131 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1132 true, 1133 );1134 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1135 return burnedTokens.success && burnedTokens.tokens.length > 0;1136 }11371138 1139114011411142114311441145114611471148 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1149 const approveResult = await this.helper.executeExtrinsic(1150 signer,1151 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1152 true, 1153 );11541155 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1156 }11571158 1159116011611162116311641165116611671168 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1169 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1170 }11711172 1173117411751176117711781179 async getLastTokenId(collectionId: number): Promise<number> {1180 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1181 }11821183 11841185118611871188118911901191 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1192 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1193 }1194}11951196class NFTnRFT extends CollectionGroup {1197 11981199120012011202120312041205 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1206 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1207 }12081209 1210121112121213121412151216121712181219 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1220 properties: IProperty[];1221 owner: CrossAccountId;1222 normalizedOwner: CrossAccountId;1223 }| null> {1224 let tokenData;1225 if(typeof blockHashAt === 'undefined') {1226 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1227 }1228 else {1229 if(propertyKeys.length == 0) {1230 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1231 if(!collection) return null;1232 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1233 }1234 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1235 }1236 tokenData = tokenData.toHuman();1237 if (tokenData === null || tokenData.owner === null) return null;1238 const owner = {} as any;1239 for (const key of Object.keys(tokenData.owner)) {1240 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1241 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1242 : tokenData.owner[key];1243 }1244 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1245 return tokenData;1246 }12471248 12491250125112521253125412551256125712581259 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1260 const result = await this.helper.executeExtrinsic(1261 signer,1262 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1263 true,1264 );12651266 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1267 }12681269 12701271127212731274127512761277 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1278 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1279 }12801281 1282128312841285128612871288128912901291 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1292 const result = await this.helper.executeExtrinsic(1293 signer,1294 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1295 true,1296 );12971298 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1299 }13001301 130213031304130513061307130813091310 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1311 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1312 }13131314 131513161317131813191320132113221323 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1324 const result = await this.helper.executeExtrinsic(1325 signer,1326 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1327 true,1328 );13291330 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1331 }13321333 133413351336133713381339134013411342 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1343 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1344 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1345 for (const key of ['name', 'description', 'tokenPrefix']) {1346 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);1347 }1348 const creationResult = await this.helper.executeExtrinsic(1349 signer,1350 'api.tx.unique.createCollectionEx', [collectionOptions],1351 true, 1352 );1353 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1354 }13551356 getCollectionObject(_collectionId: number): any {1357 return null;1358 }13591360 getTokenObject(_collectionId: number, _tokenId: number): any {1361 return null;1362 }1363}136413651366class NFTGroup extends NFTnRFT {1367 136813691370137113721373 getCollectionObject(collectionId: number): UniqueNFTCollection {1374 return new UniqueNFTCollection(collectionId, this.helper);1375 }13761377 1378137913801381138213831384 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1385 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1386 }13871388 13891390139113921393139413951396 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1397 let owner;1398 if (typeof blockHashAt === 'undefined') {1399 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1400 } else {1401 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1402 }1403 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1404 }14051406 1407140814091410141114121413 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1414 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1415 }14161417 1418141914201421142214231424142514261427 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1428 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1429 }14301431 143214331434143514361437143814391440144114421443 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1444 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1445 }14461447 14481449145014511452145314541455 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1456 let owner;1457 if (typeof blockHashAt === 'undefined') {1458 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1459 } else {1460 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1461 }14621463 if (owner === null) return null;14641465 return owner.toHuman();1466 }14671468 14691470147114721473147414751476 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1477 let children;1478 if(typeof blockHashAt === 'undefined') {1479 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1480 } else {1481 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1482 }14831484 return children.toJSON().map((x: any) => {1485 return {collectionId: x.collection, tokenId: x.token};1486 });1487 }14881489 14901491149214931494149514961497 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1498 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1499 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1500 if(!result) {1501 throw Error('Unable to nest token!');1502 }1503 return result;1504 }15051506 150715081509151015111512151315141515 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1516 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1517 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1518 if(!result) {1519 throw Error('Unable to unnest token!');1520 }1521 return result;1522 }15231524 152515261527152815291530153115321533153415351536 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1537 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1538 }15391540 154115421543154415451546 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1547 const creationResult = await this.helper.executeExtrinsic(1548 signer,1549 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1550 nft: {1551 properties: data.properties,1552 },1553 }],1554 true,1555 );1556 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1557 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1558 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1559 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1560 }15611562 156315641565156615671568156915701571157215731574157515761577 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1578 const creationResult = await this.helper.executeExtrinsic(1579 signer,1580 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1581 true,1582 );1583 const collection = this.getCollectionObject(collectionId);1584 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1585 }15861587 158815891590159115921593159415951596159715981599160016011602160316041605 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1606 const rawTokens = [];1607 for (const token of tokens) {1608 const raw = {NFT: {properties: token.properties}};1609 rawTokens.push(raw);1610 }1611 const creationResult = await this.helper.executeExtrinsic(1612 signer,1613 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1614 true,1615 );1616 const collection = this.getCollectionObject(collectionId);1617 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1618 }16191620 1621162216231624162516261627162816291630 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1631 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1632 }1633}163416351636class RFTGroup extends NFTnRFT {1637 163816391640164116421643 getCollectionObject(collectionId: number): UniqueRFTCollection {1644 return new UniqueRFTCollection(collectionId, this.helper);1645 }16461647 1648164916501651165216531654 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1655 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1656 }16571658 1659166016611662166316641665 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1666 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1667 }16681669 16701671167216731674167516761677 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1678 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1679 }16801681 1682168316841685168616871688168916901691 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1692 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1693 }16941695 16961697169816991700170117021703170417051706 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1707 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1708 }17091710 171117121713171417151716171717181719172017211722 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1723 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1724 }17251726 1727172817291730173117321733 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1734 const creationResult = await this.helper.executeExtrinsic(1735 signer,1736 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1737 refungible: {1738 pieces: data.pieces,1739 properties: data.properties,1740 },1741 }],1742 true,1743 );1744 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1745 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1746 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1747 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1748 }17491750 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1751 throw Error('Not implemented');1752 const creationResult = await this.helper.executeExtrinsic(1753 signer,1754 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1755 true, 1756 );1757 const collection = this.getCollectionObject(collectionId);1758 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1759 }17601761 176217631764176517661767176817691770 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1771 const rawTokens = [];1772 for (const token of tokens) {1773 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1774 rawTokens.push(raw);1775 }1776 const creationResult = await this.helper.executeExtrinsic(1777 signer,1778 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1779 true,1780 );1781 const collection = this.getCollectionObject(collectionId);1782 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1783 }17841785 178617871788178917901791179217931794 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1795 return await super.burnToken(signer, collectionId, tokenId, amount);1796 }17971798 1799180018011802180318041805180618071808 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1809 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1810 }18111812 18131814181518161817181818191820182118221823 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1824 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1825 }18261827 1828182918301831183218331834 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1835 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1836 }18371838 183918401841184218431844184518461847 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1848 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1849 const repartitionResult = await this.helper.executeExtrinsic(1850 signer,1851 'api.tx.unique.repartition', [collectionId, tokenId, amount],1852 true,1853 );1854 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1855 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1856 }1857}185818591860class FTGroup extends CollectionGroup {1861 186218631864186518661867 getCollectionObject(collectionId: number): UniqueFTCollection {1868 return new UniqueFTCollection(collectionId, this.helper);1869 }18701871 1872187318741875187618771878187918801881188218831884 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1885 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1886 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1887 collectionOptions.mode = {fungible: decimalPoints};1888 for (const key of ['name', 'description', 'tokenPrefix']) {1889 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);1890 }1891 const creationResult = await this.helper.executeExtrinsic(1892 signer,1893 'api.tx.unique.createCollectionEx', [collectionOptions],1894 true,1895 );1896 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1897 }18981899 190019011902190319041905190619071908 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1909 const creationResult = await this.helper.executeExtrinsic(1910 signer,1911 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1912 fungible: {1913 value: amount,1914 },1915 }],1916 true, 1917 );1918 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1919 }19201921 19221923192419251926192719281929 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1930 const rawTokens = [];1931 for (const token of tokens) {1932 const raw = {Fungible: {Value: token.value}};1933 rawTokens.push(raw);1934 }1935 const creationResult = await this.helper.executeExtrinsic(1936 signer,1937 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1938 true,1939 );1940 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1941 }19421943 194419451946194719481949 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1950 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1951 }19521953 1954195519561957195819591960 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1961 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1962 }19631964 196519661967196819691970197119721973 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1974 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1975 }19761977 1978197919801981198219831984198519861987 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1988 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1989 }19901991 19921993199419951996199719981999 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2000 return await super.burnToken(signer, collectionId, 0, amount);2001 }20022003 200420052006200720082009201020112012 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2013 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2014 }20152016 20172018201920202021 async getTotalPieces(collectionId: number): Promise<bigint> {2022 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2023 }20242025 2026202720282029203020312032203320342035 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2036 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2037 }20382039 2040204120422043204420452046 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2047 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2048 }2049}205020512052class ChainGroup extends HelperGroup<ChainHelperBase> {2053 20542055205620572058 getChainProperties(): IChainProperties {2059 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2060 return {2061 ss58Format: properties.ss58Format.toJSON(),2062 tokenDecimals: properties.tokenDecimals.toJSON(),2063 tokenSymbol: properties.tokenSymbol.toJSON(),2064 };2065 }20662067 20682069207020712072 async getLatestBlockNumber(): Promise<number> {2073 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2074 }20752076 207720782079208020812082 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2083 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2084 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2085 return blockHash;2086 }20872088 2089 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2090 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2091 if (!blockHash) return null;2092 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2093 }20942095 209620972098209921002101 async getNonce(address: TSubstrateAccount): Promise<number> {2102 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2103 }2104}21052106class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2107 210821092110211121122113 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2114 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2115 }21162117 21182119212021212122212321242125 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2126 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);21272128 let transfer = {from: null, to: null, amount: 0n} as any;2129 result.result.events.forEach(({event: {data, method, section}}) => {2130 if ((section === 'balances') && (method === 'Transfer')) {2131 transfer = {2132 from: this.helper.address.normalizeSubstrate(data[0]),2133 to: this.helper.address.normalizeSubstrate(data[1]),2134 amount: BigInt(data[2]),2135 };2136 }2137 });2138 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2139 && this.helper.address.normalizeSubstrate(address) === transfer.to 2140 && BigInt(amount) === transfer.amount;2141 return isSuccess;2142 }21432144 21452146214721482149 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2150 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2151 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2152 }2153}21542155class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2156 215721582159216021612162 async getEthereum(address: TEthereumAccount): Promise<bigint> {2163 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2164 }21652166 21672168216921702171217221732174 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2175 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);21762177 let transfer = {from: null, to: null, amount: 0n} as any;2178 result.result.events.forEach(({event: {data, method, section}}) => {2179 if ((section === 'balances') && (method === 'Transfer')) {2180 transfer = {2181 from: data[0].toString(),2182 to: data[1].toString(),2183 amount: BigInt(data[2]),2184 };2185 }2186 });2187 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from 2188 && address === transfer.to 2189 && BigInt(amount) === transfer.amount;2190 return isSuccess;2191 }2192}21932194class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2195 subBalanceGroup: SubstrateBalanceGroup<T>;2196 ethBalanceGroup: EthereumBalanceGroup<T>;21972198 constructor(helper: T) {2199 super(helper);2200 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2201 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2202 }22032204 getCollectionCreationPrice(): bigint {2205 return 2n * this.getOneTokenNominal();2206 }2207 22082209221022112212 getOneTokenNominal(): bigint {2213 const chainProperties = this.helper.chain.getChainProperties();2214 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2215 }22162217 221822192220222122222223 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2224 return this.subBalanceGroup.getSubstrate(address);2225 }22262227 22282229223022312232 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2233 return this.subBalanceGroup.getSubstrateFull(address);2234 }22352236 223722382239224022412242 getEthereum(address: TEthereumAccount): Promise<bigint> {2243 return this.ethBalanceGroup.getEthereum(address);2244 }22452246 22472248224922502251225222532254 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2255 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2256 }2257}22582259class AddressGroup extends HelperGroup<ChainHelperBase> {2260 2261226222632264226522662267 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2268 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2269 }22702271 227222732274227522762277 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2278 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2279 }22802281 2282228322842285228622872288 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2289 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2290 }22912292 229322942295229622972298 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2299 return CrossAccountId.translateSubToEth(subAddress);2300 }23012302 paraSiblingSovereignAccount(paraid: number) {2303 2304 2305 const siblingPrefix = '0x7369626c';23062307 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2308 const suffix = '000000000000000000000000000000000000000000000000';23092310 return siblingPrefix + encodedParaId + suffix;2311 }2312}23132314class StakingGroup extends HelperGroup<UniqueHelper> {2315 2316231723182319232023212322 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2323 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2324 const _stakeResult = await this.helper.executeExtrinsic(2325 signer, 'api.tx.appPromotion.stake',2326 [amountToStake], true,2327 );2328 2329 return true;2330 }23312332 2333233423352336233723382339 async unstake(signer: TSigner, label?: string): Promise<number> {2340 if(typeof label === 'undefined') label = `${signer.address}`;2341 const _unstakeResult = await this.helper.executeExtrinsic(2342 signer, 'api.tx.appPromotion.unstake',2343 [], true,2344 );2345 2346 return 1;2347 }23482349 23502351235223532354 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2355 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2356 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2357 }23582359 23602361236223632364 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2365 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2366 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2367 return { 2368 block: block.toBigInt(),2369 amount: amount.toBigInt(),2370 };2371 });2372 }23732374 23752376237723782379 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2380 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2381 }23822383 23842385238623872388 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2389 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2390 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2391 return {2392 block: block.toBigInt(),2393 amount: amount.toBigInt(),2394 };2395 });2396 return result;2397 }2398}23992400class SchedulerGroup extends HelperGroup<UniqueHelper> {2401 constructor(helper: UniqueHelper) {2402 super(helper);2403 }24042405 cancelScheduled(signer: TSigner, scheduledId: string) {2406 return this.helper.executeExtrinsic(2407 signer,2408 'api.tx.scheduler.cancelNamed',2409 [scheduledId],2410 true,2411 );2412 }24132414 changePriority(signer: TSigner, scheduledId: string, priority: number) {2415 return this.helper.executeExtrinsic(2416 signer,2417 'api.tx.scheduler.changeNamedPriority',2418 [scheduledId, priority],2419 true,2420 );2421 }24222423 scheduleAt<T extends UniqueHelper>(2424 scheduledId: string,2425 executionBlockNumber: number,2426 options: ISchedulerOptions = {},2427 ) {2428 return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2429 }24302431 scheduleAfter<T extends UniqueHelper>(2432 scheduledId: string,2433 blocksBeforeExecution: number,2434 options: ISchedulerOptions = {},2435 ) {2436 return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2437 }24382439 schedule<T extends UniqueHelper>(2440 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2441 scheduledId: string,2442 blocksNum: number,2443 options: ISchedulerOptions = {},2444 ) {2445 2446 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2447 return this.helper.clone(ScheduledHelperType, {2448 scheduleFn,2449 scheduledId,2450 blocksNum,2451 options,2452 }) as T;2453 }2454}24552456class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2457 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2458 await this.helper.executeExtrinsic(2459 signer,2460 'api.tx.foreignAssets.registerForeignAsset',2461 [ownerAddress, location, metadata],2462 true,2463 );2464 }24652466 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2467 await this.helper.executeExtrinsic(2468 signer,2469 'api.tx.foreignAssets.updateForeignAsset',2470 [foreignAssetId, location, metadata],2471 true,2472 );2473 }2474}24752476class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2477 palletName: string;24782479 constructor(helper: T, palletName: string) {2480 super(helper);24812482 this.palletName = palletName;2483 }24842485 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2486 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2487 }2488}24892490class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2491 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2492 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2493 }24942495 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2496 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2497 }24982499 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2500 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2501 }2502}25032504class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2505 async accounts(address: string, currencyId: any) {2506 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2507 return BigInt(free);2508 }2509}25102511class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2512 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2513 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2514 }25152516 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2517 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2518 }25192520 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2521 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2522 }25232524 async account(assetId: string | number, address: string) {2525 const accountAsset = (2526 await this.helper.callRpc('api.query.assets.account', [assetId, address])2527 ).toJSON()! as any;25282529 if (accountAsset !== null) {2530 return BigInt(accountAsset['balance']);2531 } else {2532 return null;2533 }2534 }2535}25362537class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2538 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2539 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2540 }2541}25422543class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2544 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2545 const apiPrefix = 'api.tx.assetManager.';25462547 const registerTx = this.helper.constructApiCall(2548 apiPrefix + 'registerForeignAsset',2549 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2550 );25512552 const setUnitsTx = this.helper.constructApiCall(2553 apiPrefix + 'setAssetUnitsPerSecond',2554 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2555 );25562557 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2558 const encodedProposal = batchCall?.method.toHex() || '';2559 return encodedProposal;2560 }25612562 async assetTypeId(location: any) {2563 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2564 }2565}25662567class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2568 async notePreimage(signer: TSigner, encodedProposal: string) {2569 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2570 }25712572 externalProposeMajority(proposalHash: string) {2573 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2574 }25752576 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2577 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2578 }25792580 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2581 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2582 }2583}25842585class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2586 collective: string;25872588 constructor(helper: MoonbeamHelper, collective: string) {2589 super(helper);25902591 this.collective = collective;2592 }25932594 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2595 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2596 }25972598 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2599 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2600 }26012602 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2603 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2604 }26052606 async proposalCount() {2607 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2608 }2609}26102611export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2612export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;26132614export class UniqueHelper extends ChainHelperBase {2615 balance: BalanceGroup<UniqueHelper>;2616 collection: CollectionGroup;2617 nft: NFTGroup;2618 rft: RFTGroup;2619 ft: FTGroup;2620 staking: StakingGroup;2621 scheduler: SchedulerGroup;2622 foreignAssets: ForeignAssetsGroup;2623 xcm: XcmGroup<UniqueHelper>;2624 xTokens: XTokensGroup<UniqueHelper>;2625 tokens: TokensGroup<UniqueHelper>;26262627 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2628 super(logger, options.helperBase ?? UniqueHelper);26292630 this.balance = new BalanceGroup(this);2631 this.collection = new CollectionGroup(this);2632 this.nft = new NFTGroup(this);2633 this.rft = new RFTGroup(this);2634 this.ft = new FTGroup(this);2635 this.staking = new StakingGroup(this);2636 this.scheduler = new SchedulerGroup(this);2637 this.foreignAssets = new ForeignAssetsGroup(this);2638 this.xcm = new XcmGroup(this, 'polkadotXcm');2639 this.xTokens = new XTokensGroup(this);2640 this.tokens = new TokensGroup(this);2641 }26422643 getSudo<T extends UniqueHelper>() {2644 2645 const SudoHelperType = SudoHelper(this.helperBase);2646 return this.clone(SudoHelperType) as T;2647 }2648}26492650export class XcmChainHelper extends ChainHelperBase {2651 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2652 const wsProvider = new WsProvider(wsEndpoint);2653 this.api = new ApiPromise({2654 provider: wsProvider,2655 });2656 await this.api.isReadyOrError;2657 this.network = await UniqueHelper.detectNetwork(this.api);2658 }2659}26602661export class RelayHelper extends XcmChainHelper {2662 xcm: XcmGroup<RelayHelper>;26632664 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2665 super(logger, options.helperBase ?? RelayHelper);26662667 this.xcm = new XcmGroup(this, 'xcmPallet');2668 }2669}26702671export class WestmintHelper extends XcmChainHelper {2672 balance: SubstrateBalanceGroup<WestmintHelper>;2673 xcm: XcmGroup<WestmintHelper>;2674 assets: AssetsGroup<WestmintHelper>;2675 xTokens: XTokensGroup<WestmintHelper>;26762677 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2678 super(logger, options.helperBase ?? WestmintHelper);26792680 this.balance = new SubstrateBalanceGroup(this);2681 this.xcm = new XcmGroup(this, 'polkadotXcm');2682 this.assets = new AssetsGroup(this);2683 this.xTokens = new XTokensGroup(this);2684 }2685}26862687export class MoonbeamHelper extends XcmChainHelper {2688 balance: EthereumBalanceGroup<MoonbeamHelper>;2689 assetManager: MoonbeamAssetManagerGroup;2690 assets: AssetsGroup<MoonbeamHelper>;2691 xTokens: XTokensGroup<MoonbeamHelper>;2692 democracy: MoonbeamDemocracyGroup;2693 collective: {2694 council: MoonbeamCollectiveGroup,2695 techCommittee: MoonbeamCollectiveGroup,2696 };26972698 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2699 super(logger, options.helperBase ?? MoonbeamHelper);27002701 this.balance = new EthereumBalanceGroup(this);2702 this.assetManager = new MoonbeamAssetManagerGroup(this);2703 this.assets = new AssetsGroup(this);2704 this.xTokens = new XTokensGroup(this);2705 this.democracy = new MoonbeamDemocracyGroup(this);2706 this.collective = {2707 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2708 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2709 };2710 }2711}27122713export class AcalaHelper extends XcmChainHelper {2714 balance: SubstrateBalanceGroup<AcalaHelper>;2715 assetRegistry: AcalaAssetRegistryGroup;2716 xTokens: XTokensGroup<AcalaHelper>;2717 tokens: TokensGroup<AcalaHelper>;27182719 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2720 super(logger, options.helperBase ?? AcalaHelper);27212722 this.balance = new SubstrateBalanceGroup(this);2723 this.assetRegistry = new AcalaAssetRegistryGroup(this);2724 this.xTokens = new XTokensGroup(this);2725 this.tokens = new TokensGroup(this);2726 }27272728 getSudo<T extends AcalaHelper>() {2729 2730 const SudoHelperType = SudoHelper(this.helperBase);2731 return this.clone(SudoHelperType) as T;2732 }2733}273427352736function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2737 return class extends Base {2738 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2739 scheduledId: string;2740 blocksNum: number;2741 options: ISchedulerOptions;27422743 constructor(...args: any[]) {2744 const logger = args[0] as ILogger;2745 const options = args[1] as {2746 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2747 scheduledId: string,2748 blocksNum: number,2749 options: ISchedulerOptions2750 };27512752 super(logger);27532754 this.scheduleFn = options.scheduleFn;2755 this.scheduledId = options.scheduledId;2756 this.blocksNum = options.blocksNum;2757 this.options = options.options;2758 }27592760 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2761 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2762 const extrinsic = 'api.tx.scheduler.' + this.scheduleFn;27632764 return super.executeExtrinsic(2765 sender,2766 extrinsic,2767 [2768 this.scheduledId,2769 this.blocksNum,2770 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2771 this.options.priority ?? null,2772 {Value: scheduledTx},2773 ],2774 expectSuccess,2775 );2776 }2777 };2778}277927802781function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2782 return class extends Base {2783 constructor(...args: any[]) {2784 super(...args);2785 }27862787 executeExtrinsic (2788 sender: IKeyringPair,2789 extrinsic: string,2790 params: any[],2791 expectSuccess?: boolean,2792 ): Promise<ITransactionResult> {2793 const call = this.constructApiCall(extrinsic, params);27942795 return super.executeExtrinsic(2796 sender,2797 'api.tx.sudo.sudo',2798 [call],2799 expectSuccess,2800 );2801 }2802 };2803}28042805export class UniqueBaseCollection {2806 helper: UniqueHelper;2807 collectionId: number;28082809 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2810 this.collectionId = collectionId;2811 this.helper = uniqueHelper;2812 }28132814 async getData() {2815 return await this.helper.collection.getData(this.collectionId);2816 }28172818 async getLastTokenId() {2819 return await this.helper.collection.getLastTokenId(this.collectionId);2820 }28212822 async doesTokenExist(tokenId: number) {2823 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2824 }28252826 async getAdmins() {2827 return await this.helper.collection.getAdmins(this.collectionId);2828 }28292830 async getAllowList() {2831 return await this.helper.collection.getAllowList(this.collectionId);2832 }28332834 async getEffectiveLimits() {2835 return await this.helper.collection.getEffectiveLimits(this.collectionId);2836 }28372838 async getProperties(propertyKeys?: string[] | null) {2839 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2840 }28412842 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2843 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2844 }28452846 async getOptions() {2847 return await this.helper.collection.getCollectionOptions(this.collectionId);2848 }28492850 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2851 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2852 }28532854 async confirmSponsorship(signer: TSigner) {2855 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2856 }28572858 async removeSponsor(signer: TSigner) {2859 return await this.helper.collection.removeSponsor(signer, this.collectionId);2860 }28612862 async setLimits(signer: TSigner, limits: ICollectionLimits) {2863 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2864 }28652866 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2867 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2868 }28692870 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2871 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2872 }28732874 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2875 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2876 }28772878 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2879 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2880 }28812882 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2883 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2884 }28852886 async setProperties(signer: TSigner, properties: IProperty[]) {2887 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2888 }28892890 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2891 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2892 }28932894 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2895 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2896 }28972898 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2899 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2900 }29012902 async disableNesting(signer: TSigner) {2903 return await this.helper.collection.disableNesting(signer, this.collectionId);2904 }29052906 async burn(signer: TSigner) {2907 return await this.helper.collection.burn(signer, this.collectionId);2908 }29092910 scheduleAt<T extends UniqueHelper>(2911 scheduledId: string,2912 executionBlockNumber: number,2913 options: ISchedulerOptions = {},2914 ) {2915 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2916 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2917 }29182919 scheduleAfter<T extends UniqueHelper>(2920 scheduledId: string,2921 blocksBeforeExecution: number,2922 options: ISchedulerOptions = {},2923 ) {2924 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2925 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2926 }29272928 getSudo<T extends UniqueHelper>() {2929 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2930 }2931}293229332934export class UniqueNFTCollection extends UniqueBaseCollection {2935 getTokenObject(tokenId: number) {2936 return new UniqueNFToken(tokenId, this);2937 }29382939 async getTokensByAddress(addressObj: ICrossAccountId) {2940 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2941 }29422943 async getToken(tokenId: number, blockHashAt?: string) {2944 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2945 }29462947 async getTokenOwner(tokenId: number, blockHashAt?: string) {2948 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2949 }29502951 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2952 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2953 }29542955 async getTokenChildren(tokenId: number, blockHashAt?: string) {2956 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2957 }29582959 async getPropertyPermissions(propertyKeys: string[] | null = null) {2960 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2961 }29622963 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2964 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2965 }29662967 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2968 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2969 }29702971 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2972 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2973 }29742975 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2976 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2977 }29782979 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2980 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2981 }29822983 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2984 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2985 }29862987 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2988 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2989 }29902991 async burnToken(signer: TSigner, tokenId: number) {2992 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2993 }29942995 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2996 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2997 }29982999 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3000 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3001 }30023003 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3004 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3005 }30063007 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3008 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3009 }30103011 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3012 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3013 }30143015 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3016 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3017 }30183019 scheduleAt<T extends UniqueHelper>(3020 scheduledId: string,3021 executionBlockNumber: number,3022 options: ISchedulerOptions = {},3023 ) {3024 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3025 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3026 }30273028 scheduleAfter<T extends UniqueHelper>(3029 scheduledId: string,3030 blocksBeforeExecution: number,3031 options: ISchedulerOptions = {},3032 ) {3033 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3034 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3035 }30363037 getSudo<T extends UniqueHelper>() {3038 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3039 }3040}304130423043export class UniqueRFTCollection extends UniqueBaseCollection {3044 getTokenObject(tokenId: number) {3045 return new UniqueRFToken(tokenId, this);3046 }30473048 async getToken(tokenId: number, blockHashAt?: string) {3049 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3050 }30513052 async getTokensByAddress(addressObj: ICrossAccountId) {3053 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3054 }30553056 async getTop10TokenOwners(tokenId: number) {3057 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3058 }30593060 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3061 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3062 }30633064 async getTokenTotalPieces(tokenId: number) {3065 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3066 }30673068 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3069 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3070 }30713072 async getPropertyPermissions(propertyKeys: string[] | null = null) {3073 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3074 }30753076 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3077 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3078 }30793080 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3081 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3082 }30833084 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3085 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3086 }30873088 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3089 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3090 }30913092 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3093 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3094 }30953096 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3097 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3098 }30993100 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3101 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3102 }31033104 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3105 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3106 }31073108 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3109 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3110 }31113112 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3113 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3114 }31153116 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3117 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3118 }31193120 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3121 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3122 }31233124 scheduleAt<T extends UniqueHelper>(3125 scheduledId: string,3126 executionBlockNumber: number,3127 options: ISchedulerOptions = {},3128 ) {3129 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3130 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3131 }31323133 scheduleAfter<T extends UniqueHelper>(3134 scheduledId: string,3135 blocksBeforeExecution: number,3136 options: ISchedulerOptions = {},3137 ) {3138 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3139 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3140 }31413142 getSudo<T extends UniqueHelper>() {3143 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3144 }3145}314631473148export class UniqueFTCollection extends UniqueBaseCollection {3149 async getBalance(addressObj: ICrossAccountId) {3150 return await this.helper.ft.getBalance(this.collectionId, addressObj);3151 }31523153 async getTotalPieces() {3154 return await this.helper.ft.getTotalPieces(this.collectionId);3155 }31563157 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3158 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3159 }31603161 async getTop10Owners() {3162 return await this.helper.ft.getTop10Owners(this.collectionId);3163 }31643165 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3166 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3167 }31683169 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3170 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3171 }31723173 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3174 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3175 }31763177 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3178 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3179 }31803181 async burnTokens(signer: TSigner, amount=1n) {3182 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3183 }31843185 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3186 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3187 }31883189 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3190 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3191 }31923193 scheduleAt<T extends UniqueHelper>(3194 scheduledId: string,3195 executionBlockNumber: number,3196 options: ISchedulerOptions = {},3197 ) {3198 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3199 return new UniqueFTCollection(this.collectionId, scheduledHelper);3200 }32013202 scheduleAfter<T extends UniqueHelper>(3203 scheduledId: string,3204 blocksBeforeExecution: number,3205 options: ISchedulerOptions = {},3206 ) {3207 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3208 return new UniqueFTCollection(this.collectionId, scheduledHelper);3209 }32103211 getSudo<T extends UniqueHelper>() {3212 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3213 }3214}321532163217export class UniqueBaseToken {3218 collection: UniqueNFTCollection | UniqueRFTCollection;3219 collectionId: number;3220 tokenId: number;32213222 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3223 this.collection = collection;3224 this.collectionId = collection.collectionId;3225 this.tokenId = tokenId;3226 }32273228 async getNextSponsored(addressObj: ICrossAccountId) {3229 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3230 }32313232 async getProperties(propertyKeys?: string[] | null) {3233 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3234 }32353236 async setProperties(signer: TSigner, properties: IProperty[]) {3237 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3238 }32393240 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3241 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3242 }32433244 async doesExist() {3245 return await this.collection.doesTokenExist(this.tokenId);3246 }32473248 nestingAccount() {3249 return this.collection.helper.util.getTokenAccount(this);3250 }32513252 scheduleAt<T extends UniqueHelper>(3253 scheduledId: string,3254 executionBlockNumber: number,3255 options: ISchedulerOptions = {},3256 ) {3257 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3258 return new UniqueBaseToken(this.tokenId, scheduledCollection);3259 }32603261 scheduleAfter<T extends UniqueHelper>(3262 scheduledId: string,3263 blocksBeforeExecution: number,3264 options: ISchedulerOptions = {},3265 ) {3266 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3267 return new UniqueBaseToken(this.tokenId, scheduledCollection);3268 }32693270 getSudo<T extends UniqueHelper>() {3271 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3272 }3273}327432753276export class UniqueNFToken extends UniqueBaseToken {3277 collection: UniqueNFTCollection;32783279 constructor(tokenId: number, collection: UniqueNFTCollection) {3280 super(tokenId, collection);3281 this.collection = collection;3282 }32833284 async getData(blockHashAt?: string) {3285 return await this.collection.getToken(this.tokenId, blockHashAt);3286 }32873288 async getOwner(blockHashAt?: string) {3289 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3290 }32913292 async getTopmostOwner(blockHashAt?: string) {3293 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3294 }32953296 async getChildren(blockHashAt?: string) {3297 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3298 }32993300 async nest(signer: TSigner, toTokenObj: IToken) {3301 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3302 }33033304 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3305 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3306 }33073308 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3309 return await this.collection.transferToken(signer, this.tokenId, addressObj);3310 }33113312 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3313 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3314 }33153316 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3317 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3318 }33193320 async isApproved(toAddressObj: ICrossAccountId) {3321 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3322 }33233324 async burn(signer: TSigner) {3325 return await this.collection.burnToken(signer, this.tokenId);3326 }33273328 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3329 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3330 }33313332 scheduleAt<T extends UniqueHelper>(3333 scheduledId: string,3334 executionBlockNumber: number,3335 options: ISchedulerOptions = {},3336 ) {3337 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3338 return new UniqueNFToken(this.tokenId, scheduledCollection);3339 }33403341 scheduleAfter<T extends UniqueHelper>(3342 scheduledId: string,3343 blocksBeforeExecution: number,3344 options: ISchedulerOptions = {},3345 ) {3346 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3347 return new UniqueNFToken(this.tokenId, scheduledCollection);3348 }33493350 getSudo<T extends UniqueHelper>() {3351 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3352 }3353}33543355export class UniqueRFToken extends UniqueBaseToken {3356 collection: UniqueRFTCollection;33573358 constructor(tokenId: number, collection: UniqueRFTCollection) {3359 super(tokenId, collection);3360 this.collection = collection;3361 }33623363 async getData(blockHashAt?: string) {3364 return await this.collection.getToken(this.tokenId, blockHashAt);3365 }33663367 async getTop10Owners() {3368 return await this.collection.getTop10TokenOwners(this.tokenId);3369 }33703371 async getBalance(addressObj: ICrossAccountId) {3372 return await this.collection.getTokenBalance(this.tokenId, addressObj);3373 }33743375 async getTotalPieces() {3376 return await this.collection.getTokenTotalPieces(this.tokenId);3377 }33783379 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3380 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3381 }33823383 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3384 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3385 }33863387 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3388 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3389 }33903391 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3392 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3393 }33943395 async repartition(signer: TSigner, amount: bigint) {3396 return await this.collection.repartitionToken(signer, this.tokenId, amount);3397 }33983399 async burn(signer: TSigner, amount=1n) {3400 return await this.collection.burnToken(signer, this.tokenId, amount);3401 }34023403 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3404 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3405 }34063407 scheduleAt<T extends UniqueHelper>(3408 scheduledId: string,3409 executionBlockNumber: number,3410 options: ISchedulerOptions = {},3411 ) {3412 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3413 return new UniqueRFToken(this.tokenId, scheduledCollection);3414 }34153416 scheduleAfter<T extends UniqueHelper>(3417 scheduledId: string,3418 blocksBeforeExecution: number,3419 options: ISchedulerOptions = {},3420 ) {3421 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3422 return new UniqueRFToken(this.tokenId, scheduledCollection);3423 }34243425 getSudo<T extends UniqueHelper>() {3426 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3427 }3428}