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(records: ITransactionResult): IEvent[] {299 const parsedEvents: IEvent[] = [];300301 records.result.events.forEach((record) => {302 const {event, phase} = record;303 const types = (event as any).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);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 103010311032103310341035103610371038 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1039 const result = await this.helper.executeExtrinsic(1040 signer,1041 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1042 true,1043 );10441045 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1046 }10471048 10491050105110521053105410551056105710581059 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1060 const result = await this.helper.executeExtrinsic(1061 signer,1062 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1063 true, 1064 );10651066 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1067 }10681069 1070107110721073107410751076107710781079108010811082 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1083 const result = await this.helper.executeExtrinsic(1084 signer,1085 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1086 true, 1087 );1088 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1089 }10901091 10921093109410951096109710981099110011011102 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1103 const burnResult = await this.helper.executeExtrinsic(1104 signer,1105 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1106 true, 1107 );1108 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1109 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1110 return burnedTokens.success;1111 }11121113 11141115111611171118111911201121112211231124 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1125 const burnResult = await this.helper.executeExtrinsic(1126 signer,1127 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1128 true, 1129 );1130 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1131 return burnedTokens.success && burnedTokens.tokens.length > 0;1132 }11331134 1135113611371138113911401141114211431144 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1145 const approveResult = await this.helper.executeExtrinsic(1146 signer,1147 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1148 true, 1149 );11501151 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1152 }11531154 1155115611571158115911601161116211631164 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1165 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1166 }11671168 1169117011711172117311741175 async getLastTokenId(collectionId: number): Promise<number> {1176 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1177 }11781179 11801181118211831184118511861187 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1188 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1189 }1190}11911192class NFTnRFT extends CollectionGroup {1193 11941195119611971198119912001201 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1202 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1203 }12041205 1206120712081209121012111212121312141215 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1216 properties: IProperty[];1217 owner: CrossAccountId;1218 normalizedOwner: CrossAccountId;1219 }| null> {1220 let tokenData;1221 if(typeof blockHashAt === 'undefined') {1222 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1223 }1224 else {1225 if(propertyKeys.length == 0) {1226 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1227 if(!collection) return null;1228 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1229 }1230 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1231 }1232 tokenData = tokenData.toHuman();1233 if (tokenData === null || tokenData.owner === null) return null;1234 const owner = {} as any;1235 for (const key of Object.keys(tokenData.owner)) {1236 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1237 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1238 : tokenData.owner[key];1239 }1240 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1241 return tokenData;1242 }12431244 12451246124712481249125012511252125312541255 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1256 const result = await this.helper.executeExtrinsic(1257 signer,1258 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1259 true,1260 );12611262 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1263 }12641265 12661267126812691270127112721273 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1274 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1275 }12761277 1278127912801281128212831284128512861287 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1288 const result = await this.helper.executeExtrinsic(1289 signer,1290 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1291 true,1292 );12931294 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1295 }12961297 129812991300130113021303130413051306 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1307 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1308 }13091310 131113121313131413151316131713181319 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1320 const result = await this.helper.executeExtrinsic(1321 signer,1322 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1323 true,1324 );13251326 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1327 }13281329 133013311332133313341335133613371338 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1339 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1340 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1341 for (const key of ['name', 'description', 'tokenPrefix']) {1342 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);1343 }1344 const creationResult = await this.helper.executeExtrinsic(1345 signer,1346 'api.tx.unique.createCollectionEx', [collectionOptions],1347 true, 1348 );1349 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1350 }13511352 getCollectionObject(_collectionId: number): any {1353 return null;1354 }13551356 getTokenObject(_collectionId: number, _tokenId: number): any {1357 return null;1358 }1359}136013611362class NFTGroup extends NFTnRFT {1363 136413651366136713681369 getCollectionObject(collectionId: number): UniqueNFTCollection {1370 return new UniqueNFTCollection(collectionId, this.helper);1371 }13721373 1374137513761377137813791380 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1381 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1382 }13831384 13851386138713881389139013911392 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1393 let owner;1394 if (typeof blockHashAt === 'undefined') {1395 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1396 } else {1397 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1398 }1399 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1400 }14011402 1403140414051406140714081409 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1410 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1411 }14121413 1414141514161417141814191420142114221423 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1424 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1425 }14261427 142814291430143114321433143414351436143714381439 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1440 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1441 }14421443 14441445144614471448144914501451 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1452 let owner;1453 if (typeof blockHashAt === 'undefined') {1454 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1455 } else {1456 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1457 }14581459 if (owner === null) return null;14601461 return owner.toHuman();1462 }14631464 14651466146714681469147014711472 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1473 let children;1474 if(typeof blockHashAt === 'undefined') {1475 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1476 } else {1477 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1478 }14791480 return children.toJSON().map((x: any) => {1481 return {collectionId: x.collection, tokenId: x.token};1482 });1483 }14841485 14861487148814891490149114921493 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1494 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1495 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1496 if(!result) {1497 throw Error('Unable to nest token!');1498 }1499 return result;1500 }15011502 150315041505150615071508150915101511 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1512 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1513 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1514 if(!result) {1515 throw Error('Unable to unnest token!');1516 }1517 return result;1518 }15191520 152115221523152415251526152715281529153015311532 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1533 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1534 }15351536 153715381539154015411542 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1543 const creationResult = await this.helper.executeExtrinsic(1544 signer,1545 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1546 nft: {1547 properties: data.properties,1548 },1549 }],1550 true,1551 );1552 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1553 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1554 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1555 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1556 }15571558 155915601561156215631564156515661567156815691570157115721573 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1574 const creationResult = await this.helper.executeExtrinsic(1575 signer,1576 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1577 true,1578 );1579 const collection = this.getCollectionObject(collectionId);1580 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1581 }15821583 158415851586158715881589159015911592159315941595159615971598159916001601 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1602 const rawTokens = [];1603 for (const token of tokens) {1604 const raw = {NFT: {properties: token.properties}};1605 rawTokens.push(raw);1606 }1607 const creationResult = await this.helper.executeExtrinsic(1608 signer,1609 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1610 true,1611 );1612 const collection = this.getCollectionObject(collectionId);1613 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1614 }16151616 1617161816191620162116221623162416251626 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1627 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1628 }1629}163016311632class RFTGroup extends NFTnRFT {1633 163416351636163716381639 getCollectionObject(collectionId: number): UniqueRFTCollection {1640 return new UniqueRFTCollection(collectionId, this.helper);1641 }16421643 1644164516461647164816491650 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1651 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1652 }16531654 1655165616571658165916601661 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1662 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1663 }16641665 16661667166816691670167116721673 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1674 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1675 }16761677 1678167916801681168216831684168516861687 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1688 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1689 }16901691 16921693169416951696169716981699170017011702 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1703 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1704 }17051706 170717081709171017111712171317141715171617171718 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1719 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1720 }17211722 1723172417251726172717281729 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1730 const creationResult = await this.helper.executeExtrinsic(1731 signer,1732 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1733 refungible: {1734 pieces: data.pieces,1735 properties: data.properties,1736 },1737 }],1738 true,1739 );1740 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1741 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1742 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1743 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1744 }17451746 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1747 throw Error('Not implemented');1748 const creationResult = await this.helper.executeExtrinsic(1749 signer,1750 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1751 true, 1752 );1753 const collection = this.getCollectionObject(collectionId);1754 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1755 }17561757 175817591760176117621763176417651766 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1767 const rawTokens = [];1768 for (const token of tokens) {1769 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1770 rawTokens.push(raw);1771 }1772 const creationResult = await this.helper.executeExtrinsic(1773 signer,1774 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1775 true,1776 );1777 const collection = this.getCollectionObject(collectionId);1778 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1779 }17801781 178217831784178517861787178817891790 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1791 return await super.burnToken(signer, collectionId, tokenId, amount);1792 }17931794 1795179617971798179918001801180218031804 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1805 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1806 }18071808 18091810181118121813181418151816181718181819 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1820 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1821 }18221823 1824182518261827182818291830 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1831 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1832 }18331834 183518361837183818391840184118421843 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1844 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1845 const repartitionResult = await this.helper.executeExtrinsic(1846 signer,1847 'api.tx.unique.repartition', [collectionId, tokenId, amount],1848 true,1849 );1850 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1851 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1852 }1853}185418551856class FTGroup extends CollectionGroup {1857 185818591860186118621863 getCollectionObject(collectionId: number): UniqueFTCollection {1864 return new UniqueFTCollection(collectionId, this.helper);1865 }18661867 1868186918701871187218731874187518761877187818791880 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1881 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1882 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1883 collectionOptions.mode = {fungible: decimalPoints};1884 for (const key of ['name', 'description', 'tokenPrefix']) {1885 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);1886 }1887 const creationResult = await this.helper.executeExtrinsic(1888 signer,1889 'api.tx.unique.createCollectionEx', [collectionOptions],1890 true,1891 );1892 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1893 }18941895 189618971898189919001901190219031904 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1905 const creationResult = await this.helper.executeExtrinsic(1906 signer,1907 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1908 fungible: {1909 value: amount,1910 },1911 }],1912 true, 1913 );1914 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1915 }19161917 19181919192019211922192319241925 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1926 const rawTokens = [];1927 for (const token of tokens) {1928 const raw = {Fungible: {Value: token.value}};1929 rawTokens.push(raw);1930 }1931 const creationResult = await this.helper.executeExtrinsic(1932 signer,1933 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1934 true,1935 );1936 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1937 }19381939 194019411942194319441945 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1946 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1947 }19481949 1950195119521953195419551956 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1957 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1958 }19591960 196119621963196419651966196719681969 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1970 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1971 }19721973 1974197519761977197819791980198119821983 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1984 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1985 }19861987 19881989199019911992199319941995 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1996 return await super.burnToken(signer, collectionId, 0, amount);1997 }19981999 200020012002200320042005200620072008 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2009 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2010 }20112012 20132014201520162017 async getTotalPieces(collectionId: number): Promise<bigint> {2018 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2019 }20202021 2022202320242025202620272028202920302031 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2032 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2033 }20342035 2036203720382039204020412042 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2043 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2044 }2045}204620472048class ChainGroup extends HelperGroup<ChainHelperBase> {2049 20502051205220532054 getChainProperties(): IChainProperties {2055 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2056 return {2057 ss58Format: properties.ss58Format.toJSON(),2058 tokenDecimals: properties.tokenDecimals.toJSON(),2059 tokenSymbol: properties.tokenSymbol.toJSON(),2060 };2061 }20622063 20642065206620672068 async getLatestBlockNumber(): Promise<number> {2069 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2070 }20712072 207320742075207620772078 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2079 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2080 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2081 return blockHash;2082 }20832084 2085 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2086 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2087 if (!blockHash) return null;2088 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2089 }20902091 209220932094209520962097 async getNonce(address: TSubstrateAccount): Promise<number> {2098 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2099 }2100}21012102class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2103 210421052106210721082109 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2110 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2111 }21122113 21142115211621172118211921202121 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2122 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);21232124 let transfer = {from: null, to: null, amount: 0n} as any;2125 result.result.events.forEach(({event: {data, method, section}}) => {2126 if ((section === 'balances') && (method === 'Transfer')) {2127 transfer = {2128 from: this.helper.address.normalizeSubstrate(data[0]),2129 to: this.helper.address.normalizeSubstrate(data[1]),2130 amount: BigInt(data[2]),2131 };2132 }2133 });2134 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2135 && this.helper.address.normalizeSubstrate(address) === transfer.to 2136 && BigInt(amount) === transfer.amount;2137 return isSuccess;2138 }21392140 21412142214321442145 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2146 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2147 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2148 }2149}21502151class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2152 215321542155215621572158 async getEthereum(address: TEthereumAccount): Promise<bigint> {2159 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2160 }21612162 21632164216521662167216821692170 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2171 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);21722173 let transfer = {from: null, to: null, amount: 0n} as any;2174 result.result.events.forEach(({event: {data, method, section}}) => {2175 if ((section === 'balances') && (method === 'Transfer')) {2176 transfer = {2177 from: data[0].toString(),2178 to: data[1].toString(),2179 amount: BigInt(data[2]),2180 };2181 }2182 });2183 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from 2184 && address === transfer.to 2185 && BigInt(amount) === transfer.amount;2186 return isSuccess;2187 }2188}21892190class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2191 subBalanceGroup: SubstrateBalanceGroup<T>;2192 ethBalanceGroup: EthereumBalanceGroup<T>;21932194 constructor(helper: T) {2195 super(helper);2196 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2197 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2198 }21992200 getCollectionCreationPrice(): bigint {2201 return 2n * this.getOneTokenNominal();2202 }2203 22042205220622072208 getOneTokenNominal(): bigint {2209 const chainProperties = this.helper.chain.getChainProperties();2210 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2211 }22122213 221422152216221722182219 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2220 return this.subBalanceGroup.getSubstrate(address);2221 }22222223 22242225222622272228 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2229 return this.subBalanceGroup.getSubstrateFull(address);2230 }22312232 223322342235223622372238 async getEthereum(address: TEthereumAccount): Promise<bigint> {2239 return this.ethBalanceGroup.getEthereum(address);2240 }22412242 22432244224522462247224822492250 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2251 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2252 }2253}22542255class AddressGroup extends HelperGroup<ChainHelperBase> {2256 2257225822592260226122622263 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2264 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2265 }22662267 226822692270227122722273 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2274 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2275 }22762277 2278227922802281228222832284 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2285 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2286 }22872288 228922902291229222932294 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2295 return CrossAccountId.translateSubToEth(subAddress);2296 }22972298 paraSiblingSovereignAccount(paraid: number) {2299 2300 2301 const siblingPrefix = '0x7369626c';23022303 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2304 const suffix = '000000000000000000000000000000000000000000000000';23052306 return siblingPrefix + encodedParaId + suffix;2307 }2308}23092310class StakingGroup extends HelperGroup<UniqueHelper> {2311 2312231323142315231623172318 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2319 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2320 const _stakeResult = await this.helper.executeExtrinsic(2321 signer, 'api.tx.appPromotion.stake',2322 [amountToStake], true,2323 );2324 2325 return true;2326 }23272328 2329233023312332233323342335 async unstake(signer: TSigner, label?: string): Promise<number> {2336 if(typeof label === 'undefined') label = `${signer.address}`;2337 const _unstakeResult = await this.helper.executeExtrinsic(2338 signer, 'api.tx.appPromotion.unstake',2339 [], true,2340 );2341 2342 return 1;2343 }23442345 23462347234823492350 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2351 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2352 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2353 }23542355 23562357235823592360 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2361 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2362 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2363 return { 2364 block: block.toBigInt(),2365 amount: amount.toBigInt(),2366 };2367 });2368 }23692370 23712372237323742375 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2376 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2377 }23782379 23802381238223832384 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2385 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2386 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2387 return {2388 block: block.toBigInt(),2389 amount: amount.toBigInt(),2390 };2391 });2392 return result;2393 }2394}23952396class SchedulerGroup extends HelperGroup<UniqueHelper> {2397 constructor(helper: UniqueHelper) {2398 super(helper);2399 }24002401 async cancelScheduled(signer: TSigner, scheduledId: string) {2402 return this.helper.executeExtrinsic(2403 signer,2404 'api.tx.scheduler.cancelNamed',2405 [scheduledId],2406 true,2407 );2408 }24092410 async changePriority(signer: TSigner, scheduledId: string, priority: number) {2411 return this.helper.executeExtrinsic(2412 signer,2413 'api.tx.scheduler.changeNamedPriority',2414 [scheduledId, priority],2415 true,2416 );2417 }24182419 scheduleAt<T extends UniqueHelper>(2420 scheduledId: string,2421 executionBlockNumber: number,2422 options: ISchedulerOptions = {},2423 ) {2424 return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2425 }24262427 scheduleAfter<T extends UniqueHelper>(2428 scheduledId: string,2429 blocksBeforeExecution: number,2430 options: ISchedulerOptions = {},2431 ) {2432 return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2433 }24342435 schedule<T extends UniqueHelper>(2436 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2437 scheduledId: string,2438 blocksNum: number,2439 options: ISchedulerOptions = {},2440 ) {2441 2442 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2443 return this.helper.clone(ScheduledHelperType, {2444 scheduleFn,2445 scheduledId,2446 blocksNum,2447 options,2448 }) as T;2449 }2450}24512452class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2453 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2454 await this.helper.executeExtrinsic(2455 signer,2456 'api.tx.foreignAssets.registerForeignAsset',2457 [ownerAddress, location, metadata],2458 true,2459 );2460 }24612462 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2463 await this.helper.executeExtrinsic(2464 signer,2465 'api.tx.foreignAssets.updateForeignAsset',2466 [foreignAssetId, location, metadata],2467 true,2468 );2469 }2470}24712472class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2473 palletName: string;24742475 constructor(helper: T, palletName: string) {2476 super(helper);24772478 this.palletName = palletName;2479 }24802481 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2482 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2483 }2484}24852486class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2487 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2488 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2489 }24902491 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2492 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2493 }24942495 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2496 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2497 }2498}24992500class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2501 async accounts(address: string, currencyId: any) {2502 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2503 return BigInt(free);2504 }2505}25062507class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2508 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2509 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2510 }25112512 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2513 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2514 }25152516 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2517 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2518 }25192520 async account(assetId: string | number, address: string) {2521 const accountAsset = (2522 await this.helper.callRpc('api.query.assets.account', [assetId, address])2523 ).toJSON()! as any;25242525 if (accountAsset !== null) {2526 return BigInt(accountAsset['balance']);2527 } else {2528 return null;2529 }2530 }2531}25322533class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2534 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2535 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2536 }2537}25382539class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2540 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2541 const apiPrefix = 'api.tx.assetManager.';25422543 const registerTx = this.helper.constructApiCall(2544 apiPrefix + 'registerForeignAsset',2545 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2546 );25472548 const setUnitsTx = this.helper.constructApiCall(2549 apiPrefix + 'setAssetUnitsPerSecond',2550 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2551 );25522553 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2554 const encodedProposal = batchCall?.method.toHex() || '';2555 return encodedProposal;2556 }25572558 async assetTypeId(location: any) {2559 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2560 }2561}25622563class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2564 async notePreimage(signer: TSigner, encodedProposal: string) {2565 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2566 }25672568 externalProposeMajority(proposalHash: string) {2569 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2570 }25712572 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2573 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2574 }25752576 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2577 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2578 }2579}25802581class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2582 collective: string;25832584 constructor(helper: MoonbeamHelper, collective: string) {2585 super(helper);25862587 this.collective = collective;2588 }25892590 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2591 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2592 }25932594 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2595 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2596 }25972598 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2599 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2600 }26012602 async proposalCount() {2603 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2604 }2605}26062607export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2608export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;26092610export class UniqueHelper extends ChainHelperBase {2611 balance: BalanceGroup<UniqueHelper>;2612 collection: CollectionGroup;2613 nft: NFTGroup;2614 rft: RFTGroup;2615 ft: FTGroup;2616 staking: StakingGroup;2617 scheduler: SchedulerGroup;2618 foreignAssets: ForeignAssetsGroup;2619 xcm: XcmGroup<UniqueHelper>;2620 xTokens: XTokensGroup<UniqueHelper>;2621 tokens: TokensGroup<UniqueHelper>;26222623 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2624 super(logger, options.helperBase ?? UniqueHelper);26252626 this.balance = new BalanceGroup(this);2627 this.collection = new CollectionGroup(this);2628 this.nft = new NFTGroup(this);2629 this.rft = new RFTGroup(this);2630 this.ft = new FTGroup(this);2631 this.staking = new StakingGroup(this);2632 this.scheduler = new SchedulerGroup(this);2633 this.foreignAssets = new ForeignAssetsGroup(this);2634 this.xcm = new XcmGroup(this, 'polkadotXcm');2635 this.xTokens = new XTokensGroup(this);2636 this.tokens = new TokensGroup(this);2637 }26382639 getSudo<T extends UniqueHelper>() {2640 2641 const SudoHelperType = SudoHelper(this.helperBase);2642 return this.clone(SudoHelperType) as T;2643 }2644}26452646export class XcmChainHelper extends ChainHelperBase {2647 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2648 const wsProvider = new WsProvider(wsEndpoint);2649 this.api = new ApiPromise({2650 provider: wsProvider,2651 });2652 await this.api.isReadyOrError;2653 this.network = await UniqueHelper.detectNetwork(this.api);2654 }2655}26562657export class RelayHelper extends XcmChainHelper {2658 xcm: XcmGroup<RelayHelper>;26592660 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2661 super(logger, options.helperBase ?? RelayHelper);26622663 this.xcm = new XcmGroup(this, 'xcmPallet');2664 }2665}26662667export class WestmintHelper extends XcmChainHelper {2668 balance: SubstrateBalanceGroup<WestmintHelper>;2669 xcm: XcmGroup<WestmintHelper>;2670 assets: AssetsGroup<WestmintHelper>;2671 xTokens: XTokensGroup<WestmintHelper>;26722673 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2674 super(logger, options.helperBase ?? WestmintHelper);26752676 this.balance = new SubstrateBalanceGroup(this);2677 this.xcm = new XcmGroup(this, 'polkadotXcm');2678 this.assets = new AssetsGroup(this);2679 this.xTokens = new XTokensGroup(this);2680 }2681}26822683export class MoonbeamHelper extends XcmChainHelper {2684 balance: EthereumBalanceGroup<MoonbeamHelper>;2685 assetManager: MoonbeamAssetManagerGroup;2686 assets: AssetsGroup<MoonbeamHelper>;2687 xTokens: XTokensGroup<MoonbeamHelper>;2688 democracy: MoonbeamDemocracyGroup;2689 collective: {2690 council: MoonbeamCollectiveGroup,2691 techCommittee: MoonbeamCollectiveGroup,2692 };26932694 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2695 super(logger, options.helperBase ?? MoonbeamHelper);26962697 this.balance = new EthereumBalanceGroup(this);2698 this.assetManager = new MoonbeamAssetManagerGroup(this);2699 this.assets = new AssetsGroup(this);2700 this.xTokens = new XTokensGroup(this);2701 this.democracy = new MoonbeamDemocracyGroup(this);2702 this.collective = {2703 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2704 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2705 };2706 }2707}27082709export class AcalaHelper extends XcmChainHelper {2710 balance: SubstrateBalanceGroup<AcalaHelper>;2711 assetRegistry: AcalaAssetRegistryGroup;2712 xTokens: XTokensGroup<AcalaHelper>;2713 tokens: TokensGroup<AcalaHelper>;27142715 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2716 super(logger, options.helperBase ?? AcalaHelper);27172718 this.balance = new SubstrateBalanceGroup(this);2719 this.assetRegistry = new AcalaAssetRegistryGroup(this);2720 this.xTokens = new XTokensGroup(this);2721 this.tokens = new TokensGroup(this);2722 }27232724 getSudo<T extends AcalaHelper>() {2725 2726 const SudoHelperType = SudoHelper(this.helperBase);2727 return this.clone(SudoHelperType) as T;2728 }2729}273027312732function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2733 return class extends Base {2734 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2735 scheduledId: string;2736 blocksNum: number;2737 options: ISchedulerOptions;27382739 constructor(...args: any[]) {2740 const logger = args[0] as ILogger;2741 const options = args[1] as {2742 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2743 scheduledId: string,2744 blocksNum: number,2745 options: ISchedulerOptions2746 };27472748 super(logger);27492750 this.scheduleFn = options.scheduleFn;2751 this.scheduledId = options.scheduledId;2752 this.blocksNum = options.blocksNum;2753 this.options = options.options;2754 }27552756 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2757 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2758 const extrinsic = 'api.tx.scheduler.' + this.scheduleFn;27592760 return super.executeExtrinsic(2761 sender,2762 extrinsic,2763 [2764 this.scheduledId,2765 this.blocksNum,2766 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2767 this.options.priority ?? null,2768 {Value: scheduledTx},2769 ],2770 expectSuccess,2771 );2772 }2773 };2774}277527762777function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2778 return class extends Base {2779 constructor(...args: any[]) {2780 super(...args);2781 }27822783 executeExtrinsic (2784 sender: IKeyringPair,2785 extrinsic: string,2786 params: any[],2787 expectSuccess?: boolean,2788 ): Promise<ITransactionResult> {2789 const call = this.constructApiCall(extrinsic, params);27902791 return super.executeExtrinsic(2792 sender,2793 'api.tx.sudo.sudo',2794 [call],2795 expectSuccess,2796 );2797 }2798 };2799}28002801export class UniqueBaseCollection {2802 helper: UniqueHelper;2803 collectionId: number;28042805 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2806 this.collectionId = collectionId;2807 this.helper = uniqueHelper;2808 }28092810 async getData() {2811 return await this.helper.collection.getData(this.collectionId);2812 }28132814 async getLastTokenId() {2815 return await this.helper.collection.getLastTokenId(this.collectionId);2816 }28172818 async doesTokenExist(tokenId: number) {2819 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2820 }28212822 async getAdmins() {2823 return await this.helper.collection.getAdmins(this.collectionId);2824 }28252826 async getAllowList() {2827 return await this.helper.collection.getAllowList(this.collectionId);2828 }28292830 async getEffectiveLimits() {2831 return await this.helper.collection.getEffectiveLimits(this.collectionId);2832 }28332834 async getProperties(propertyKeys?: string[] | null) {2835 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2836 }28372838 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2839 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2840 }28412842 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2843 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2844 }28452846 async confirmSponsorship(signer: TSigner) {2847 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2848 }28492850 async removeSponsor(signer: TSigner) {2851 return await this.helper.collection.removeSponsor(signer, this.collectionId);2852 }28532854 async setLimits(signer: TSigner, limits: ICollectionLimits) {2855 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2856 }28572858 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2859 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2860 }28612862 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2863 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2864 }28652866 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2867 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2868 }28692870 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2871 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2872 }28732874 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2875 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2876 }28772878 async setProperties(signer: TSigner, properties: IProperty[]) {2879 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2880 }28812882 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2883 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2884 }28852886 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2887 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2888 }28892890 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2891 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2892 }28932894 async disableNesting(signer: TSigner) {2895 return await this.helper.collection.disableNesting(signer, this.collectionId);2896 }28972898 async burn(signer: TSigner) {2899 return await this.helper.collection.burn(signer, this.collectionId);2900 }29012902 scheduleAt<T extends UniqueHelper>(2903 scheduledId: string,2904 executionBlockNumber: number,2905 options: ISchedulerOptions = {},2906 ) {2907 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2908 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2909 }29102911 scheduleAfter<T extends UniqueHelper>(2912 scheduledId: string,2913 blocksBeforeExecution: number,2914 options: ISchedulerOptions = {},2915 ) {2916 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2917 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2918 }29192920 getSudo<T extends UniqueHelper>() {2921 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2922 }2923}292429252926export class UniqueNFTCollection extends UniqueBaseCollection {2927 getTokenObject(tokenId: number) {2928 return new UniqueNFToken(tokenId, this);2929 }29302931 async getTokensByAddress(addressObj: ICrossAccountId) {2932 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2933 }29342935 async getToken(tokenId: number, blockHashAt?: string) {2936 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2937 }29382939 async getTokenOwner(tokenId: number, blockHashAt?: string) {2940 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2941 }29422943 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2944 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2945 }29462947 async getTokenChildren(tokenId: number, blockHashAt?: string) {2948 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2949 }29502951 async getPropertyPermissions(propertyKeys: string[] | null = null) {2952 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2953 }29542955 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2956 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2957 }29582959 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2960 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2961 }29622963 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2964 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2965 }29662967 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2968 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2969 }29702971 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2972 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2973 }29742975 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2976 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2977 }29782979 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2980 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2981 }29822983 async burnToken(signer: TSigner, tokenId: number) {2984 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2985 }29862987 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2988 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2989 }29902991 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2992 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2993 }29942995 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2996 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2997 }29982999 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3000 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3001 }30023003 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3004 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3005 }30063007 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3008 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3009 }30103011 scheduleAt<T extends UniqueHelper>(3012 scheduledId: string,3013 executionBlockNumber: number,3014 options: ISchedulerOptions = {},3015 ) {3016 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3017 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3018 }30193020 scheduleAfter<T extends UniqueHelper>(3021 scheduledId: string,3022 blocksBeforeExecution: number,3023 options: ISchedulerOptions = {},3024 ) {3025 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3026 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3027 }30283029 getSudo<T extends UniqueHelper>() {3030 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3031 }3032}303330343035export class UniqueRFTCollection extends UniqueBaseCollection {3036 getTokenObject(tokenId: number) {3037 return new UniqueRFToken(tokenId, this);3038 }30393040 async getToken(tokenId: number, blockHashAt?: string) {3041 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3042 }30433044 async getTokensByAddress(addressObj: ICrossAccountId) {3045 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3046 }30473048 async getTop10TokenOwners(tokenId: number) {3049 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3050 }30513052 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3053 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3054 }30553056 async getTokenTotalPieces(tokenId: number) {3057 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3058 }30593060 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3061 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3062 }30633064 async getPropertyPermissions(propertyKeys: string[] | null = null) {3065 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3066 }30673068 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3069 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3070 }30713072 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3073 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3074 }30753076 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3077 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3078 }30793080 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3081 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3082 }30833084 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3085 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3086 }30873088 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3089 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3090 }30913092 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3093 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3094 }30953096 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3097 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3098 }30993100 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3101 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3102 }31033104 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3105 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3106 }31073108 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3109 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3110 }31113112 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3113 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3114 }31153116 scheduleAt<T extends UniqueHelper>(3117 scheduledId: string,3118 executionBlockNumber: number,3119 options: ISchedulerOptions = {},3120 ) {3121 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3122 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3123 }31243125 scheduleAfter<T extends UniqueHelper>(3126 scheduledId: string,3127 blocksBeforeExecution: number,3128 options: ISchedulerOptions = {},3129 ) {3130 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3131 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3132 }31333134 getSudo<T extends UniqueHelper>() {3135 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3136 }3137}313831393140export class UniqueFTCollection extends UniqueBaseCollection {3141 async getBalance(addressObj: ICrossAccountId) {3142 return await this.helper.ft.getBalance(this.collectionId, addressObj);3143 }31443145 async getTotalPieces() {3146 return await this.helper.ft.getTotalPieces(this.collectionId);3147 }31483149 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3150 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3151 }31523153 async getTop10Owners() {3154 return await this.helper.ft.getTop10Owners(this.collectionId);3155 }31563157 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3158 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3159 }31603161 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3162 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3163 }31643165 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3166 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3167 }31683169 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3170 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3171 }31723173 async burnTokens(signer: TSigner, amount=1n) {3174 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3175 }31763177 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3178 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3179 }31803181 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3182 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3183 }31843185 scheduleAt<T extends UniqueHelper>(3186 scheduledId: string,3187 executionBlockNumber: number,3188 options: ISchedulerOptions = {},3189 ) {3190 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3191 return new UniqueFTCollection(this.collectionId, scheduledHelper);3192 }31933194 scheduleAfter<T extends UniqueHelper>(3195 scheduledId: string,3196 blocksBeforeExecution: number,3197 options: ISchedulerOptions = {},3198 ) {3199 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3200 return new UniqueFTCollection(this.collectionId, scheduledHelper);3201 }32023203 getSudo<T extends UniqueHelper>() {3204 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3205 }3206}320732083209export class UniqueBaseToken {3210 collection: UniqueNFTCollection | UniqueRFTCollection;3211 collectionId: number;3212 tokenId: number;32133214 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3215 this.collection = collection;3216 this.collectionId = collection.collectionId;3217 this.tokenId = tokenId;3218 }32193220 async getNextSponsored(addressObj: ICrossAccountId) {3221 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3222 }32233224 async getProperties(propertyKeys?: string[] | null) {3225 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3226 }32273228 async setProperties(signer: TSigner, properties: IProperty[]) {3229 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3230 }32313232 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3233 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3234 }32353236 async doesExist() {3237 return await this.collection.doesTokenExist(this.tokenId);3238 }32393240 nestingAccount() {3241 return this.collection.helper.util.getTokenAccount(this);3242 }32433244 scheduleAt<T extends UniqueHelper>(3245 scheduledId: string,3246 executionBlockNumber: number,3247 options: ISchedulerOptions = {},3248 ) {3249 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3250 return new UniqueBaseToken(this.tokenId, scheduledCollection);3251 }32523253 scheduleAfter<T extends UniqueHelper>(3254 scheduledId: string,3255 blocksBeforeExecution: number,3256 options: ISchedulerOptions = {},3257 ) {3258 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3259 return new UniqueBaseToken(this.tokenId, scheduledCollection);3260 }32613262 getSudo<T extends UniqueHelper>() {3263 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3264 }3265}326632673268export class UniqueNFToken extends UniqueBaseToken {3269 collection: UniqueNFTCollection;32703271 constructor(tokenId: number, collection: UniqueNFTCollection) {3272 super(tokenId, collection);3273 this.collection = collection;3274 }32753276 async getData(blockHashAt?: string) {3277 return await this.collection.getToken(this.tokenId, blockHashAt);3278 }32793280 async getOwner(blockHashAt?: string) {3281 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3282 }32833284 async getTopmostOwner(blockHashAt?: string) {3285 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3286 }32873288 async getChildren(blockHashAt?: string) {3289 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3290 }32913292 async nest(signer: TSigner, toTokenObj: IToken) {3293 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3294 }32953296 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3297 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3298 }32993300 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3301 return await this.collection.transferToken(signer, this.tokenId, addressObj);3302 }33033304 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3305 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3306 }33073308 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3309 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3310 }33113312 async isApproved(toAddressObj: ICrossAccountId) {3313 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3314 }33153316 async burn(signer: TSigner) {3317 return await this.collection.burnToken(signer, this.tokenId);3318 }33193320 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3321 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3322 }33233324 scheduleAt<T extends UniqueHelper>(3325 scheduledId: string,3326 executionBlockNumber: number,3327 options: ISchedulerOptions = {},3328 ) {3329 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3330 return new UniqueNFToken(this.tokenId, scheduledCollection);3331 }33323333 scheduleAfter<T extends UniqueHelper>(3334 scheduledId: string,3335 blocksBeforeExecution: number,3336 options: ISchedulerOptions = {},3337 ) {3338 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3339 return new UniqueNFToken(this.tokenId, scheduledCollection);3340 }33413342 getSudo<T extends UniqueHelper>() {3343 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3344 }3345}33463347export class UniqueRFToken extends UniqueBaseToken {3348 collection: UniqueRFTCollection;33493350 constructor(tokenId: number, collection: UniqueRFTCollection) {3351 super(tokenId, collection);3352 this.collection = collection;3353 }33543355 async getData(blockHashAt?: string) {3356 return await this.collection.getToken(this.tokenId, blockHashAt);3357 }33583359 async getTop10Owners() {3360 return await this.collection.getTop10TokenOwners(this.tokenId);3361 }33623363 async getBalance(addressObj: ICrossAccountId) {3364 return await this.collection.getTokenBalance(this.tokenId, addressObj);3365 }33663367 async getTotalPieces() {3368 return await this.collection.getTokenTotalPieces(this.tokenId);3369 }33703371 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3372 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3373 }33743375 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3376 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3377 }33783379 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3380 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3381 }33823383 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3384 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3385 }33863387 async repartition(signer: TSigner, amount: bigint) {3388 return await this.collection.repartitionToken(signer, this.tokenId, amount);3389 }33903391 async burn(signer: TSigner, amount=1n) {3392 return await this.collection.burnToken(signer, this.tokenId, amount);3393 }33943395 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3396 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3397 }33983399 scheduleAt<T extends UniqueHelper>(3400 scheduledId: string,3401 executionBlockNumber: number,3402 options: ISchedulerOptions = {},3403 ) {3404 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3405 return new UniqueRFToken(this.tokenId, scheduledCollection);3406 }34073408 scheduleAfter<T extends UniqueHelper>(3409 scheduledId: string,3410 blocksBeforeExecution: number,3411 options: ISchedulerOptions = {},3412 ) {3413 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3414 return new UniqueRFToken(this.tokenId, scheduledCollection);3415 }34163417 getSudo<T extends UniqueHelper>() {3418 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3419 }3420}