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 }255}256257class UniqueEventHelper {258 private static extractIndex(index: any): [number, number] | string {259 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];260 return index.toJSON();261 }262263 private static extractSub(data: any, subTypes: any): {[key: string]: any} {264 let obj: any = {};265 let index = 0;266267 if (data.entries) {268 for(const [key, value] of data.entries()) {269 obj[key] = this.extractData(value, subTypes[index]);270 index++;271 }272 } else obj = data.toJSON();273274 return obj;275 }276 277 private static extractData(data: any, type: any): any {278 if(!type) return data.toHuman();279 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();280 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();281 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);282 return data.toHuman();283 }284285 public static extractEvents(records: ITransactionResult): IEvent[] {286 const parsedEvents: IEvent[] = [];287288 records.result.events.forEach((record) => {289 const {event, phase} = record;290 const types = (event as any).typeDef;291292 const eventData: IEvent = {293 section: event.section.toString(),294 method: event.method.toString(),295 index: this.extractIndex(event.index),296 data: [],297 phase: phase.toJSON(),298 };299300 event.data.forEach((val: any, index: number) => {301 eventData.data.push(this.extractData(val, types[index]));302 });303304 parsedEvents.push(eventData);305 });306307 return parsedEvents;308 }309}310311export class ChainHelperBase {312 helperBase: any;313314 transactionStatus = UniqueUtil.transactionStatus;315 chainLogType = UniqueUtil.chainLogType;316 util: typeof UniqueUtil;317 eventHelper: typeof UniqueEventHelper;318 logger: ILogger;319 api: ApiPromise | null;320 forcedNetwork: TNetworks | null;321 network: TNetworks | null;322 chainLog: IUniqueHelperLog[];323 children: ChainHelperBase[];324 address: AddressGroup;325 chain: ChainGroup;326327 constructor(logger?: ILogger, helperBase?: any) {328 this.helperBase = helperBase;329330 this.util = UniqueUtil;331 this.eventHelper = UniqueEventHelper;332 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();333 this.logger = logger;334 this.api = null;335 this.forcedNetwork = null;336 this.network = null;337 this.chainLog = [];338 this.children = [];339 this.address = new AddressGroup(this);340 this.chain = new ChainGroup(this);341 }342343 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {344 Object.setPrototypeOf(helperCls.prototype, this);345 const newHelper = new helperCls(this.logger, options);346347 newHelper.api = this.api;348 newHelper.network = this.network;349 newHelper.forceNetwork = this.forceNetwork;350351 this.children.push(newHelper);352353 return newHelper;354 }355356 getApi(): ApiPromise {357 if(this.api === null) throw Error('API not initialized');358 return this.api;359 }360361 clearChainLog(): void {362 this.chainLog = [];363 }364365 forceNetwork(value: TNetworks): void {366 this.forcedNetwork = value;367 }368369 async connect(wsEndpoint: string, listeners?: IApiListeners) {370 if (this.api !== null) throw Error('Already connected');371 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);372 this.api = api;373 this.network = network;374 }375376 async disconnect() {377 for (const child of this.children) {378 child.clearApi();379 }380381 if (this.api === null) return;382 await this.api.disconnect();383 this.clearApi();384 }385386 clearApi() {387 this.api = null;388 this.network = null;389 }390391 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {392 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;393 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];394395 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;396397 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;398 return 'opal';399 }400401 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {402 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});403 await api.isReady;404405 const network = await this.detectNetwork(api);406407 await api.disconnect();408409 return network;410 }411412 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{413 api: ApiPromise;414 network: TNetworks;415 }> {416 console.log('createConnection network = ', network);417 if(typeof network === 'undefined' || network === null) network = 'opal';418 const supportedRPC = {419 opal: {420 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,421 },422 quartz: {423 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,424 },425 unique: {426 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,427 },428 rococo: {},429 westend: {},430 moonbeam: {},431 moonriver: {},432 acala: {},433 karura: {},434 westmint: {},435 };436 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);437 const rpc = supportedRPC[network];438439 440 441442 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});443444 await api.isReadyOrError;445446 if (typeof listeners === 'undefined') listeners = {};447 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {448 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;449 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);450 }451452 return {api, network};453 }454455 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {456 const {events, status} = data;457 if (status.isReady) {458 return this.transactionStatus.NOT_READY;459 }460 if (status.isBroadcast) {461 return this.transactionStatus.NOT_READY;462 }463 if (status.isInBlock || status.isFinalized) {464 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');465 if (errors.length > 0) {466 return this.transactionStatus.FAIL;467 }468 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {469 return this.transactionStatus.SUCCESS;470 }471 }472473 return this.transactionStatus.FAIL;474 }475476 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {477 const sign = (callback: any) => {478 if(options !== null) return transaction.signAndSend(sender, options, callback);479 return transaction.signAndSend(sender, callback);480 };481 482 return new Promise(async (resolve, reject) => {483 try {484 const unsub = await sign((result: any) => {485 const status = this.getTransactionStatus(result);486487 if (status === this.transactionStatus.SUCCESS) {488 this.logger.log(`${label} successful`);489 unsub();490 resolve({result, status});491 } else if (status === this.transactionStatus.FAIL) {492 let moduleError = null;493494 if (result.hasOwnProperty('dispatchError')) {495 const dispatchError = result['dispatchError'];496497 if (dispatchError) {498 if (dispatchError.isModule) {499 const modErr = dispatchError.asModule;500 const errorMeta = dispatchError.registry.findMetaError(modErr);501502 moduleError = `${errorMeta.section}.${errorMeta.name}`;503 } else {504 moduleError = dispatchError.toHuman();505 }506 } else {507 this.logger.log(result, this.logger.level.ERROR);508 }509 }510511 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);512 unsub();513 reject({status, moduleError, result});514 }515 });516 } catch (e) {517 this.logger.log(e, this.logger.level.ERROR);518 reject(e);519 }520 });521 }522523 constructApiCall(apiCall: string, params: any[]) {524 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);525 let call = this.getApi() as any;526 for(const part of apiCall.slice(4).split('.')) {527 call = call[part];528 }529 return call(...params);530 }531532 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null) {533 if(this.api === null) throw Error('API not initialized');534 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);535536 const startTime = (new Date()).getTime();537 let result: ITransactionResult;538 let events: IEvent[] = [];539 try {540 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;541 events = this.eventHelper.extractEvents(result);542 }543 catch(e) {544 if(!(e as object).hasOwnProperty('status')) throw e;545 result = e as ITransactionResult;546 }547548 const endTime = (new Date()).getTime();549550 const log = {551 executedAt: endTime,552 executionTime: endTime - startTime,553 type: this.chainLogType.EXTRINSIC,554 status: result.status,555 call: extrinsic,556 signer: this.getSignerAddress(sender),557 params,558 } as IUniqueHelperLog;559560 if(result.status !== this.transactionStatus.SUCCESS) {561 if (result.moduleError) log.moduleError = result.moduleError;562 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;563 }564 if(events.length > 0) log.events = events;565566 this.chainLog.push(log);567568 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {569 if (result.moduleError) throw Error(`${result.moduleError}`);570 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));571 }572 return result;573 }574575 async callRpc(rpc: string, params?: any[]) {576 if(typeof params === 'undefined') params = [];577 if(this.api === null) throw Error('API not initialized');578 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);579580 const startTime = (new Date()).getTime();581 let result;582 let error = null;583 const log = {584 type: this.chainLogType.RPC,585 call: rpc,586 params,587 } as IUniqueHelperLog;588589 try {590 result = await this.constructApiCall(rpc, params);591 }592 catch(e) {593 error = e;594 }595596 const endTime = (new Date()).getTime();597598 log.executedAt = endTime;599 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';600 log.executionTime = endTime - startTime;601602 this.chainLog.push(log);603604 if(error !== null) throw error;605606 return result;607 }608609 getSignerAddress(signer: IKeyringPair | string): string {610 if(typeof signer === 'string') return signer;611 return signer.address;612 }613614 fetchAllPalletNames(): string[] {615 if(this.api === null) throw Error('API not initialized');616 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());617 }618619 fetchMissingPalletNames(requiredPallets: string[]): string[] {620 const palletNames = this.fetchAllPalletNames();621 return requiredPallets.filter(p => !palletNames.includes(p));622 }623}624625626class HelperGroup<T extends ChainHelperBase> {627 helper: T;628629 constructor(uniqueHelper: T) {630 this.helper = uniqueHelper;631 }632}633634635class CollectionGroup extends HelperGroup<UniqueHelper> {636 637638639640641642643644645 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {646 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();647 }648649 650651652653654 async getTotalCount(): Promise<number> {655 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();656 }657658 659660661662663664665666667 async getData(collectionId: number): Promise<{668 id: number;669 name: string;670 description: string;671 tokensCount: number;672 admins: CrossAccountId[];673 normalizedOwner: TSubstrateAccount;674 raw: any675 } | null> {676 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);677 const humanCollection = collection.toHuman(), collectionData = {678 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],679 raw: humanCollection,680 } as any, jsonCollection = collection.toJSON();681 if (humanCollection === null) return null;682 collectionData.raw.limits = jsonCollection.limits;683 collectionData.raw.permissions = jsonCollection.permissions;684 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);685 for (const key of ['name', 'description']) {686 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);687 }688689 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))690 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)691 : 0;692 collectionData.admins = await this.getAdmins(collectionId);693694 return collectionData;695 }696697 698699700701702703704705 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {706 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();707708 return normalize709 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())710 : admins;711 }712713 714715716717718719720 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {721 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();722 return normalize723 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())724 : allowListed;725 }726727 728729730731732733734 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {735 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();736 }737738 739740741742743744745746 async burn(signer: TSigner, collectionId: number): Promise<boolean> {747 const result = await this.helper.executeExtrinsic(748 signer,749 'api.tx.unique.destroyCollection', [collectionId],750 true,751 );752753 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');754 }755756 757758759760761762763764765 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {766 const result = await this.helper.executeExtrinsic(767 signer,768 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],769 true,770 );771772 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');773 }774775 776777778779780781782783 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {784 const result = await this.helper.executeExtrinsic(785 signer,786 'api.tx.unique.confirmSponsorship', [collectionId],787 true,788 );789790 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');791 }792793 794795796797798799800801 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {802 const result = await this.helper.executeExtrinsic(803 signer,804 'api.tx.unique.removeCollectionSponsor', [collectionId],805 true,806 );807808 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');809 }810811 812813814815816817818819820821822823824825826827828 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {829 const result = await this.helper.executeExtrinsic(830 signer,831 'api.tx.unique.setCollectionLimits', [collectionId, limits],832 true,833 );834835 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');836 }837838 839840841842843844845846847 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {848 const result = await this.helper.executeExtrinsic(849 signer,850 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],851 true,852 );853854 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');855 }856857 858859860861862863864865866 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {867 const result = await this.helper.executeExtrinsic(868 signer,869 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],870 true,871 );872873 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');874 }875876 877878879880881882883884885 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {886 const result = await this.helper.executeExtrinsic(887 signer,888 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],889 true,890 );891892 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');893 }894895 896897898899900901902903 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {904 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();905 }906907 908909910911912913914 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {915 const result = await this.helper.executeExtrinsic(916 signer,917 'api.tx.unique.addToAllowList', [collectionId, addressObj],918 true,919 );920921 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');922 }923924 925926927928929930931932 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {933 const result = await this.helper.executeExtrinsic(934 signer,935 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],936 true,937 );938939 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');940 }941942 943944945946947948949950951 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {952 const result = await this.helper.executeExtrinsic(953 signer,954 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],955 true,956 );957958 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');959 }960961 962963964965966967968969970 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {971 return await this.setPermissions(signer, collectionId, {nesting: permissions});972 }973974 975976977978979980981982 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {983 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});984 }985986 987988989990991992993994995 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {996 const result = await this.helper.executeExtrinsic(997 signer,998 'api.tx.unique.setCollectionProperties', [collectionId, properties],999 true,1000 );10011002 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1003 }10041005 10061007100810091010101110121013 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1014 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1015 }10161017 101810191020102110221023102410251026 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1027 const result = await this.helper.executeExtrinsic(1028 signer,1029 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1030 true,1031 );10321033 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1034 }10351036 10371038103910401041104210431044104510461047 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1048 const result = await this.helper.executeExtrinsic(1049 signer,1050 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1051 true, 1052 );10531054 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1055 }10561057 1058105910601061106210631064106510661067106810691070 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1071 const result = await this.helper.executeExtrinsic(1072 signer,1073 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1074 true, 1075 );1076 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1077 }10781079 10801081108210831084108510861087108810891090 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1091 const burnResult = await this.helper.executeExtrinsic(1092 signer,1093 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1094 true, 1095 );1096 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1097 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1098 return burnedTokens.success;1099 }11001101 11021103110411051106110711081109111011111112 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1113 const burnResult = await this.helper.executeExtrinsic(1114 signer,1115 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1116 true, 1117 );1118 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1119 return burnedTokens.success && burnedTokens.tokens.length > 0;1120 }11211122 1123112411251126112711281129113011311132 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1133 const approveResult = await this.helper.executeExtrinsic(1134 signer,1135 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1136 true, 1137 );11381139 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1140 }11411142 1143114411451146114711481149115011511152 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1153 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1154 }11551156 1157115811591160116111621163 async getLastTokenId(collectionId: number): Promise<number> {1164 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1165 }11661167 11681169117011711172117311741175 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1176 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1177 }1178}11791180class NFTnRFT extends CollectionGroup {1181 11821183118411851186118711881189 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1190 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1191 }11921193 1194119511961197119811991200120112021203 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1204 properties: IProperty[];1205 owner: CrossAccountId;1206 normalizedOwner: CrossAccountId;1207 }| null> {1208 let tokenData;1209 if(typeof blockHashAt === 'undefined') {1210 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1211 }1212 else {1213 if(propertyKeys.length == 0) {1214 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1215 if(!collection) return null;1216 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1217 }1218 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1219 }1220 tokenData = tokenData.toHuman();1221 if (tokenData === null || tokenData.owner === null) return null;1222 const owner = {} as any;1223 for (const key of Object.keys(tokenData.owner)) {1224 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1225 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1226 : tokenData.owner[key];1227 }1228 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1229 return tokenData;1230 }12311232 12331234123512361237123812391240124112421243 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1244 const result = await this.helper.executeExtrinsic(1245 signer,1246 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1247 true,1248 );12491250 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1251 }12521253 12541255125612571258125912601261 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1262 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1263 }12641265 1266126712681269127012711272127312741275 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1276 const result = await this.helper.executeExtrinsic(1277 signer,1278 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1279 true,1280 );12811282 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1283 }12841285 128612871288128912901291129212931294 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1295 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1296 }12971298 129913001301130213031304130513061307 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1308 const result = await this.helper.executeExtrinsic(1309 signer,1310 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1311 true,1312 );13131314 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1315 }13161317 131813191320132113221323132413251326 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1327 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1328 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1329 for (const key of ['name', 'description', 'tokenPrefix']) {1330 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);1331 }1332 const creationResult = await this.helper.executeExtrinsic(1333 signer,1334 'api.tx.unique.createCollectionEx', [collectionOptions],1335 true, 1336 );1337 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1338 }13391340 getCollectionObject(_collectionId: number): any {1341 return null;1342 }13431344 getTokenObject(_collectionId: number, _tokenId: number): any {1345 return null;1346 }1347}134813491350class NFTGroup extends NFTnRFT {1351 135213531354135513561357 getCollectionObject(collectionId: number): UniqueNFTCollection {1358 return new UniqueNFTCollection(collectionId, this.helper);1359 }13601361 1362136313641365136613671368 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1369 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1370 }13711372 13731374137513761377137813791380 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1381 let owner;1382 if (typeof blockHashAt === 'undefined') {1383 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1384 } else {1385 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1386 }1387 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1388 }13891390 1391139213931394139513961397 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1398 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1399 }14001401 1402140314041405140614071408140914101411 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1412 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1413 }14141415 141614171418141914201421142214231424142514261427 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1428 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1429 }14301431 14321433143414351436143714381439 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1440 let owner;1441 if (typeof blockHashAt === 'undefined') {1442 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1443 } else {1444 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1445 }14461447 if (owner === null) return null;14481449 return owner.toHuman();1450 }14511452 14531454145514561457145814591460 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1461 let children;1462 if(typeof blockHashAt === 'undefined') {1463 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1464 } else {1465 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1466 }14671468 return children.toJSON().map((x: any) => {1469 return {collectionId: x.collection, tokenId: x.token};1470 });1471 }14721473 14741475147614771478147914801481 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1482 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1483 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1484 if(!result) {1485 throw Error('Unable to nest token!');1486 }1487 return result;1488 }14891490 149114921493149414951496149714981499 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1500 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1501 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1502 if(!result) {1503 throw Error('Unable to unnest token!');1504 }1505 return result;1506 }15071508 150915101511151215131514151515161517151815191520 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1521 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1522 }15231524 152515261527152815291530 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1531 const creationResult = await this.helper.executeExtrinsic(1532 signer,1533 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1534 nft: {1535 properties: data.properties,1536 },1537 }],1538 true,1539 );1540 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1541 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1542 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1543 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1544 }15451546 154715481549155015511552155315541555155615571558155915601561 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1562 const creationResult = await this.helper.executeExtrinsic(1563 signer,1564 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1565 true,1566 );1567 const collection = this.getCollectionObject(collectionId);1568 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1569 }15701571 157215731574157515761577157815791580158115821583158415851586158715881589 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1590 const rawTokens = [];1591 for (const token of tokens) {1592 const raw = {NFT: {properties: token.properties}};1593 rawTokens.push(raw);1594 }1595 const creationResult = await this.helper.executeExtrinsic(1596 signer,1597 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1598 true,1599 );1600 const collection = this.getCollectionObject(collectionId);1601 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1602 }16031604 1605160616071608160916101611161216131614 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1615 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1616 }1617}161816191620class RFTGroup extends NFTnRFT {1621 162216231624162516261627 getCollectionObject(collectionId: number): UniqueRFTCollection {1628 return new UniqueRFTCollection(collectionId, this.helper);1629 }16301631 1632163316341635163616371638 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1639 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1640 }16411642 1643164416451646164716481649 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1650 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1651 }16521653 16541655165616571658165916601661 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1662 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1663 }16641665 1666166716681669167016711672167316741675 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1676 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1677 }16781679 16801681168216831684168516861687168816891690 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1691 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1692 }16931694 169516961697169816991700170117021703170417051706 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1707 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1708 }17091710 1711171217131714171517161717 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1718 const creationResult = await this.helper.executeExtrinsic(1719 signer,1720 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1721 refungible: {1722 pieces: data.pieces,1723 properties: data.properties,1724 },1725 }],1726 true,1727 );1728 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1729 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1730 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1731 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1732 }17331734 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1735 throw Error('Not implemented');1736 const creationResult = await this.helper.executeExtrinsic(1737 signer,1738 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1739 true, 1740 );1741 const collection = this.getCollectionObject(collectionId);1742 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1743 }17441745 174617471748174917501751175217531754 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1755 const rawTokens = [];1756 for (const token of tokens) {1757 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1758 rawTokens.push(raw);1759 }1760 const creationResult = await this.helper.executeExtrinsic(1761 signer,1762 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1763 true,1764 );1765 const collection = this.getCollectionObject(collectionId);1766 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1767 }17681769 177017711772177317741775177617771778 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1779 return await super.burnToken(signer, collectionId, tokenId, amount);1780 }17811782 1783178417851786178717881789179017911792 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1793 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1794 }17951796 17971798179918001801180218031804180518061807 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1808 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1809 }18101811 1812181318141815181618171818 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1819 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1820 }18211822 182318241825182618271828182918301831 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1832 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1833 const repartitionResult = await this.helper.executeExtrinsic(1834 signer,1835 'api.tx.unique.repartition', [collectionId, tokenId, amount],1836 true,1837 );1838 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1839 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1840 }1841}184218431844class FTGroup extends CollectionGroup {1845 184618471848184918501851 getCollectionObject(collectionId: number): UniqueFTCollection {1852 return new UniqueFTCollection(collectionId, this.helper);1853 }18541855 1856185718581859186018611862186318641865186618671868 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1869 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1870 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1871 collectionOptions.mode = {fungible: decimalPoints};1872 for (const key of ['name', 'description', 'tokenPrefix']) {1873 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);1874 }1875 const creationResult = await this.helper.executeExtrinsic(1876 signer,1877 'api.tx.unique.createCollectionEx', [collectionOptions],1878 true,1879 );1880 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1881 }18821883 188418851886188718881889189018911892 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1893 const creationResult = await this.helper.executeExtrinsic(1894 signer,1895 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1896 fungible: {1897 value: amount,1898 },1899 }],1900 true, 1901 );1902 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1903 }19041905 19061907190819091910191119121913 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1914 const rawTokens = [];1915 for (const token of tokens) {1916 const raw = {Fungible: {Value: token.value}};1917 rawTokens.push(raw);1918 }1919 const creationResult = await this.helper.executeExtrinsic(1920 signer,1921 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1922 true,1923 );1924 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1925 }19261927 192819291930193119321933 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1934 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1935 }19361937 1938193919401941194219431944 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1945 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1946 }19471948 194919501951195219531954195519561957 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1958 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1959 }19601961 1962196319641965196619671968196919701971 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1972 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1973 }19741975 19761977197819791980198119821983 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1984 return await super.burnToken(signer, collectionId, 0, amount);1985 }19861987 198819891990199119921993199419951996 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1997 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);1998 }19992000 20012002200320042005 async getTotalPieces(collectionId: number): Promise<bigint> {2006 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2007 }20082009 2010201120122013201420152016201720182019 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2020 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2021 }20222023 2024202520262027202820292030 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2031 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2032 }2033}203420352036class ChainGroup extends HelperGroup<ChainHelperBase> {2037 20382039204020412042 getChainProperties(): IChainProperties {2043 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2044 return {2045 ss58Format: properties.ss58Format.toJSON(),2046 tokenDecimals: properties.tokenDecimals.toJSON(),2047 tokenSymbol: properties.tokenSymbol.toJSON(),2048 };2049 }20502051 20522053205420552056 async getLatestBlockNumber(): Promise<number> {2057 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2058 }20592060 206120622063206420652066 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2067 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2068 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2069 return blockHash;2070 }20712072 2073 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2074 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2075 if (!blockHash) return null;2076 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2077 }20782079 208020812082208320842085 async getNonce(address: TSubstrateAccount): Promise<number> {2086 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2087 }2088}20892090class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2091 209220932094209520962097 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2098 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2099 }21002101 21022103210421052106210721082109 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2110 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);21112112 let transfer = {from: null, to: null, amount: 0n} as any;2113 result.result.events.forEach(({event: {data, method, section}}) => {2114 if ((section === 'balances') && (method === 'Transfer')) {2115 transfer = {2116 from: this.helper.address.normalizeSubstrate(data[0]),2117 to: this.helper.address.normalizeSubstrate(data[1]),2118 amount: BigInt(data[2]),2119 };2120 }2121 });2122 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2123 && this.helper.address.normalizeSubstrate(address) === transfer.to 2124 && BigInt(amount) === transfer.amount;2125 return isSuccess;2126 }21272128 21292130213121322133 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2134 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2135 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2136 }2137}21382139class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2140 214121422143214421452146 async getEthereum(address: TEthereumAccount): Promise<bigint> {2147 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2148 }21492150 21512152215321542155215621572158 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2159 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);21602161 let transfer = {from: null, to: null, amount: 0n} as any;2162 result.result.events.forEach(({event: {data, method, section}}) => {2163 if ((section === 'balances') && (method === 'Transfer')) {2164 transfer = {2165 from: data[0].toString(),2166 to: data[1].toString(),2167 amount: BigInt(data[2]),2168 };2169 }2170 });2171 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from 2172 && address === transfer.to 2173 && BigInt(amount) === transfer.amount;2174 return isSuccess;2175 }2176}21772178class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2179 subBalanceGroup: SubstrateBalanceGroup<T>;2180 ethBalanceGroup: EthereumBalanceGroup<T>;21812182 constructor(helper: T) {2183 super(helper);2184 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2185 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2186 }21872188 getCollectionCreationPrice(): bigint {2189 return 2n * this.getOneTokenNominal();2190 }2191 21922193219421952196 getOneTokenNominal(): bigint {2197 const chainProperties = this.helper.chain.getChainProperties();2198 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2199 }22002201 220222032204220522062207 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2208 return this.subBalanceGroup.getSubstrate(address);2209 }22102211 22122213221422152216 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2217 return this.subBalanceGroup.getSubstrateFull(address);2218 }22192220 222122222223222422252226 async getEthereum(address: TEthereumAccount): Promise<bigint> {2227 return this.ethBalanceGroup.getEthereum(address);2228 }22292230 22312232223322342235223622372238 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2239 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2240 }2241}22422243class AddressGroup extends HelperGroup<ChainHelperBase> {2244 2245224622472248224922502251 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2252 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2253 }22542255 225622572258225922602261 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2262 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2263 }22642265 2266226722682269227022712272 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2273 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2274 }22752276 227722782279228022812282 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2283 return CrossAccountId.translateSubToEth(subAddress);2284 }2285}22862287class StakingGroup extends HelperGroup<UniqueHelper> {2288 2289229022912292229322942295 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2296 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2297 const _stakeResult = await this.helper.executeExtrinsic(2298 signer, 'api.tx.appPromotion.stake',2299 [amountToStake], true,2300 );2301 2302 return true;2303 }23042305 2306230723082309231023112312 async unstake(signer: TSigner, label?: string): Promise<number> {2313 if(typeof label === 'undefined') label = `${signer.address}`;2314 const _unstakeResult = await this.helper.executeExtrinsic(2315 signer, 'api.tx.appPromotion.unstake',2316 [], true,2317 );2318 2319 return 1;2320 }23212322 23232324232523262327 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2328 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2329 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2330 }23312332 23332334233523362337 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2338 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2339 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2340 return { 2341 block: block.toBigInt(),2342 amount: amount.toBigInt(),2343 };2344 });2345 }23462347 23482349235023512352 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2353 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2354 }23552356 23572358235923602361 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2362 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2363 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2364 return {2365 block: block.toBigInt(),2366 amount: amount.toBigInt(),2367 };2368 });2369 return result;2370 }2371}23722373class SchedulerGroup extends HelperGroup<UniqueHelper> {2374 constructor(helper: UniqueHelper) {2375 super(helper);2376 }23772378 async cancelScheduled(signer: TSigner, scheduledId: string) {2379 return this.helper.executeExtrinsic(2380 signer,2381 'api.tx.scheduler.cancelNamed',2382 [scheduledId],2383 true,2384 );2385 }23862387 async changePriority(signer: TSigner, scheduledId: string, priority: number) {2388 return this.helper.executeExtrinsic(2389 signer,2390 'api.tx.scheduler.changeNamedPriority',2391 [scheduledId, priority],2392 true,2393 );2394 }23952396 scheduleAt<T extends UniqueHelper>(2397 scheduledId: string,2398 executionBlockNumber: number,2399 options: ISchedulerOptions = {},2400 ) {2401 return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2402 }24032404 scheduleAfter<T extends UniqueHelper>(2405 scheduledId: string,2406 blocksBeforeExecution: number,2407 options: ISchedulerOptions = {},2408 ) {2409 return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2410 }24112412 schedule<T extends UniqueHelper>(2413 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2414 scheduledId: string,2415 blocksNum: number,2416 options: ISchedulerOptions = {},2417 ) {2418 2419 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2420 return this.helper.clone(ScheduledHelperType, {2421 scheduleFn,2422 scheduledId,2423 blocksNum,2424 options,2425 }) as T;2426 }2427}24282429class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2430 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2431 await this.helper.executeExtrinsic(2432 signer,2433 'api.tx.foreignAssets.registerForeignAsset',2434 [ownerAddress, location, metadata],2435 true,2436 );2437 }24382439 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2440 await this.helper.executeExtrinsic(2441 signer,2442 'api.tx.foreignAssets.updateForeignAsset',2443 [foreignAssetId, location, metadata],2444 true,2445 );2446 }2447}24482449class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2450 palletName: string;24512452 constructor(helper: T, palletName: string) {2453 super(helper);24542455 this.palletName = palletName;2456 }24572458 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2459 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2460 }2461}24622463class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2464 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2465 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2466 }24672468 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2469 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2470 }2471}24722473class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2474 async accounts(address: string, currencyId: any) {2475 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2476 return BigInt(free);2477 }2478}24792480class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2481 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2482 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2483 }2484}24852486class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2487 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2488 const apiPrefix = 'api.tx.assetManager.';24892490 const registerTx = this.helper.constructApiCall(2491 apiPrefix + 'registerForeignAsset',2492 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2493 );24942495 const setUnitsTx = this.helper.constructApiCall(2496 apiPrefix + 'setAssetUnitsPerSecond',2497 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2498 );24992500 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2501 const encodedProposal = batchCall?.method.toHex() || '';2502 return encodedProposal;2503 }25042505 async assetTypeId(location: any) {2506 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2507 }2508}25092510class MoonbeamAssetsGroup extends HelperGroup<MoonbeamHelper> {2511 async account(assetId: string, address: string) {2512 const accountAsset = (2513 await this.helper.callRpc('api.query.assets.account', [assetId, address])2514 ).toJSON()! as any;25152516 if (accountAsset !== null) {2517 return BigInt(accountAsset['balance']);2518 } else {2519 return null;2520 }2521 }2522}25232524class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2525 async notePreimage(signer: TSigner, encodedProposal: string) {2526 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2527 }25282529 externalProposeMajority(proposalHash: string) {2530 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2531 }25322533 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2534 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2535 }25362537 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2538 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2539 }2540}25412542class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2543 collective: string;25442545 constructor(helper: MoonbeamHelper, collective: string) {2546 super(helper);25472548 this.collective = collective;2549 }25502551 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2552 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2553 }25542555 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2556 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2557 }25582559 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2560 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2561 }25622563 async proposalCount() {2564 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2565 }2566}25672568export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2569export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;25702571export class UniqueHelper extends ChainHelperBase {2572 balance: BalanceGroup<UniqueHelper>;2573 collection: CollectionGroup;2574 nft: NFTGroup;2575 rft: RFTGroup;2576 ft: FTGroup;2577 staking: StakingGroup;2578 scheduler: SchedulerGroup;2579 foreignAssets: ForeignAssetsGroup;2580 xcm: XcmGroup<UniqueHelper>;2581 xTokens: XTokensGroup<UniqueHelper>;2582 tokens: TokensGroup<UniqueHelper>;25832584 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2585 super(logger, options.helperBase ?? UniqueHelper);25862587 this.balance = new BalanceGroup(this);2588 this.address = new AddressGroup(this);2589 this.collection = new CollectionGroup(this);2590 this.nft = new NFTGroup(this);2591 this.rft = new RFTGroup(this);2592 this.ft = new FTGroup(this);2593 this.staking = new StakingGroup(this);2594 this.scheduler = new SchedulerGroup(this);2595 this.foreignAssets = new ForeignAssetsGroup(this);2596 this.xcm = new XcmGroup(this, 'polkadotXcm');2597 this.xTokens = new XTokensGroup(this);2598 this.tokens = new TokensGroup(this);2599 }26002601 getSudo<T extends UniqueHelper>() {2602 2603 const SudoHelperType = SudoHelper(this.helperBase);2604 return this.clone(SudoHelperType) as T;2605 }2606}26072608export class XcmChainHelper extends ChainHelperBase {2609 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2610 const wsProvider = new WsProvider(wsEndpoint);2611 this.api = new ApiPromise({2612 provider: wsProvider,2613 });2614 await this.api.isReadyOrError;2615 this.network = await UniqueHelper.detectNetwork(this.api);2616 }2617}26182619export class RelayHelper extends XcmChainHelper {2620 xcm: XcmGroup<RelayHelper>;26212622 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2623 super(logger, options.helperBase ?? RelayHelper);26242625 this.xcm = new XcmGroup(this, 'xcmPallet');2626 }2627}26282629export class MoonbeamHelper extends XcmChainHelper {2630 balance: EthereumBalanceGroup<MoonbeamHelper>;2631 assetManager: MoonbeamAssetManagerGroup;2632 assets: MoonbeamAssetsGroup;2633 xTokens: XTokensGroup<MoonbeamHelper>;2634 democracy: MoonbeamDemocracyGroup;2635 collective: {2636 council: MoonbeamCollectiveGroup,2637 techCommittee: MoonbeamCollectiveGroup,2638 };26392640 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2641 super(logger, options.helperBase ?? MoonbeamHelper);26422643 this.balance = new EthereumBalanceGroup(this);2644 this.assetManager = new MoonbeamAssetManagerGroup(this);2645 this.assets = new MoonbeamAssetsGroup(this);2646 this.xTokens = new XTokensGroup(this);2647 this.democracy = new MoonbeamDemocracyGroup(this);2648 this.collective = {2649 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2650 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2651 };2652 }2653}26542655export class AcalaHelper extends XcmChainHelper {2656 balance: SubstrateBalanceGroup<AcalaHelper>;2657 assetRegistry: AcalaAssetRegistryGroup;2658 xTokens: XTokensGroup<AcalaHelper>;2659 tokens: TokensGroup<AcalaHelper>;26602661 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2662 super(logger, options.helperBase ?? AcalaHelper);26632664 this.balance = new SubstrateBalanceGroup(this);2665 this.assetRegistry = new AcalaAssetRegistryGroup(this);2666 this.xTokens = new XTokensGroup(this);2667 this.tokens = new TokensGroup(this);2668 }26692670 getSudo<T extends AcalaHelper>() {2671 2672 const SudoHelperType = SudoHelper(this.helperBase);2673 return this.clone(SudoHelperType) as T;2674 }2675}267626772678function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2679 return class extends Base {2680 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2681 scheduledId: string;2682 blocksNum: number;2683 options: ISchedulerOptions;26842685 constructor(...args: any[]) {2686 const logger = args[0] as ILogger;2687 const options = args[1] as {2688 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2689 scheduledId: string,2690 blocksNum: number,2691 options: ISchedulerOptions2692 };26932694 super(logger);26952696 this.scheduleFn = options.scheduleFn;2697 this.scheduledId = options.scheduledId;2698 this.blocksNum = options.blocksNum;2699 this.options = options.options;2700 }27012702 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2703 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2704 const extrinsic = 'api.tx.scheduler.' + this.scheduleFn;27052706 return super.executeExtrinsic(2707 sender,2708 extrinsic,2709 [2710 this.scheduledId,2711 this.blocksNum,2712 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2713 this.options.priority ?? null,2714 {Value: scheduledTx},2715 ],2716 expectSuccess,2717 );2718 }2719 };2720}272127222723function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2724 return class extends Base {2725 constructor(...args: any[]) {2726 super(...args);2727 }27282729 executeExtrinsic (2730 sender: IKeyringPair,2731 extrinsic: string,2732 params: any[],2733 expectSuccess?: boolean,2734 ): Promise<ITransactionResult> {2735 const call = this.constructApiCall(extrinsic, params);27362737 return super.executeExtrinsic(2738 sender,2739 'api.tx.sudo.sudo',2740 [call],2741 expectSuccess,2742 );2743 }2744 };2745}27462747export class UniqueBaseCollection {2748 helper: UniqueHelper;2749 collectionId: number;27502751 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2752 this.collectionId = collectionId;2753 this.helper = uniqueHelper;2754 }27552756 async getData() {2757 return await this.helper.collection.getData(this.collectionId);2758 }27592760 async getLastTokenId() {2761 return await this.helper.collection.getLastTokenId(this.collectionId);2762 }27632764 async doesTokenExist(tokenId: number) {2765 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2766 }27672768 async getAdmins() {2769 return await this.helper.collection.getAdmins(this.collectionId);2770 }27712772 async getAllowList() {2773 return await this.helper.collection.getAllowList(this.collectionId);2774 }27752776 async getEffectiveLimits() {2777 return await this.helper.collection.getEffectiveLimits(this.collectionId);2778 }27792780 async getProperties(propertyKeys?: string[] | null) {2781 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2782 }27832784 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2785 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2786 }27872788 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2789 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2790 }27912792 async confirmSponsorship(signer: TSigner) {2793 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2794 }27952796 async removeSponsor(signer: TSigner) {2797 return await this.helper.collection.removeSponsor(signer, this.collectionId);2798 }27992800 async setLimits(signer: TSigner, limits: ICollectionLimits) {2801 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2802 }28032804 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2805 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2806 }28072808 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2809 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2810 }28112812 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2813 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2814 }28152816 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2817 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2818 }28192820 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2821 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2822 }28232824 async setProperties(signer: TSigner, properties: IProperty[]) {2825 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2826 }28272828 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2829 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2830 }28312832 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2833 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2834 }28352836 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2837 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2838 }28392840 async disableNesting(signer: TSigner) {2841 return await this.helper.collection.disableNesting(signer, this.collectionId);2842 }28432844 async burn(signer: TSigner) {2845 return await this.helper.collection.burn(signer, this.collectionId);2846 }28472848 scheduleAt<T extends UniqueHelper>(2849 scheduledId: string,2850 executionBlockNumber: number,2851 options: ISchedulerOptions = {},2852 ) {2853 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2854 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2855 }28562857 scheduleAfter<T extends UniqueHelper>(2858 scheduledId: string,2859 blocksBeforeExecution: number,2860 options: ISchedulerOptions = {},2861 ) {2862 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2863 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2864 }28652866 getSudo<T extends UniqueHelper>() {2867 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2868 }2869}287028712872export class UniqueNFTCollection extends UniqueBaseCollection {2873 getTokenObject(tokenId: number) {2874 return new UniqueNFToken(tokenId, this);2875 }28762877 async getTokensByAddress(addressObj: ICrossAccountId) {2878 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2879 }28802881 async getToken(tokenId: number, blockHashAt?: string) {2882 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2883 }28842885 async getTokenOwner(tokenId: number, blockHashAt?: string) {2886 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2887 }28882889 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2890 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2891 }28922893 async getTokenChildren(tokenId: number, blockHashAt?: string) {2894 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2895 }28962897 async getPropertyPermissions(propertyKeys: string[] | null = null) {2898 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2899 }29002901 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2902 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2903 }29042905 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2906 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2907 }29082909 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2910 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2911 }29122913 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2914 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2915 }29162917 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2918 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2919 }29202921 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2922 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2923 }29242925 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2926 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2927 }29282929 async burnToken(signer: TSigner, tokenId: number) {2930 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2931 }29322933 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2934 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2935 }29362937 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2938 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2939 }29402941 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2942 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2943 }29442945 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2946 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2947 }29482949 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2950 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2951 }29522953 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2954 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2955 }29562957 scheduleAt<T extends UniqueHelper>(2958 scheduledId: string,2959 executionBlockNumber: number,2960 options: ISchedulerOptions = {},2961 ) {2962 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2963 return new UniqueNFTCollection(this.collectionId, scheduledHelper);2964 }29652966 scheduleAfter<T extends UniqueHelper>(2967 scheduledId: string,2968 blocksBeforeExecution: number,2969 options: ISchedulerOptions = {},2970 ) {2971 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2972 return new UniqueNFTCollection(this.collectionId, scheduledHelper);2973 }29742975 getSudo<T extends UniqueHelper>() {2976 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());2977 }2978}297929802981export class UniqueRFTCollection extends UniqueBaseCollection {2982 getTokenObject(tokenId: number) {2983 return new UniqueRFToken(tokenId, this);2984 }29852986 async getToken(tokenId: number, blockHashAt?: string) {2987 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);2988 }29892990 async getTokensByAddress(addressObj: ICrossAccountId) {2991 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2992 }29932994 async getTop10TokenOwners(tokenId: number) {2995 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2996 }29972998 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2999 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3000 }30013002 async getTokenTotalPieces(tokenId: number) {3003 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3004 }30053006 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3007 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3008 }30093010 async getPropertyPermissions(propertyKeys: string[] | null = null) {3011 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3012 }30133014 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3015 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3016 }30173018 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3019 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3020 }30213022 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3023 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3024 }30253026 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3027 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3028 }30293030 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3031 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3032 }30333034 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3035 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3036 }30373038 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3039 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3040 }30413042 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3043 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3044 }30453046 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3047 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3048 }30493050 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3051 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3052 }30533054 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3055 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3056 }30573058 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3059 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3060 }30613062 scheduleAt<T extends UniqueHelper>(3063 scheduledId: string,3064 executionBlockNumber: number,3065 options: ISchedulerOptions = {},3066 ) {3067 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3068 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3069 }30703071 scheduleAfter<T extends UniqueHelper>(3072 scheduledId: string,3073 blocksBeforeExecution: number,3074 options: ISchedulerOptions = {},3075 ) {3076 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3077 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3078 }30793080 getSudo<T extends UniqueHelper>() {3081 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3082 }3083}308430853086export class UniqueFTCollection extends UniqueBaseCollection {3087 async getBalance(addressObj: ICrossAccountId) {3088 return await this.helper.ft.getBalance(this.collectionId, addressObj);3089 }30903091 async getTotalPieces() {3092 return await this.helper.ft.getTotalPieces(this.collectionId);3093 }30943095 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3096 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3097 }30983099 async getTop10Owners() {3100 return await this.helper.ft.getTop10Owners(this.collectionId);3101 }31023103 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3104 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3105 }31063107 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3108 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3109 }31103111 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3112 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3113 }31143115 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3116 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3117 }31183119 async burnTokens(signer: TSigner, amount=1n) {3120 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3121 }31223123 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3124 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3125 }31263127 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3128 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3129 }31303131 scheduleAt<T extends UniqueHelper>(3132 scheduledId: string,3133 executionBlockNumber: number,3134 options: ISchedulerOptions = {},3135 ) {3136 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3137 return new UniqueFTCollection(this.collectionId, scheduledHelper);3138 }31393140 scheduleAfter<T extends UniqueHelper>(3141 scheduledId: string,3142 blocksBeforeExecution: number,3143 options: ISchedulerOptions = {},3144 ) {3145 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3146 return new UniqueFTCollection(this.collectionId, scheduledHelper);3147 }31483149 getSudo<T extends UniqueHelper>() {3150 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3151 }3152}315331543155export class UniqueBaseToken {3156 collection: UniqueNFTCollection | UniqueRFTCollection;3157 collectionId: number;3158 tokenId: number;31593160 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3161 this.collection = collection;3162 this.collectionId = collection.collectionId;3163 this.tokenId = tokenId;3164 }31653166 async getNextSponsored(addressObj: ICrossAccountId) {3167 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3168 }31693170 async getProperties(propertyKeys?: string[] | null) {3171 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3172 }31733174 async setProperties(signer: TSigner, properties: IProperty[]) {3175 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3176 }31773178 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3179 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3180 }31813182 async doesExist() {3183 return await this.collection.doesTokenExist(this.tokenId);3184 }31853186 nestingAccount() {3187 return this.collection.helper.util.getTokenAccount(this);3188 }31893190 scheduleAt<T extends UniqueHelper>(3191 scheduledId: string,3192 executionBlockNumber: number,3193 options: ISchedulerOptions = {},3194 ) {3195 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3196 return new UniqueBaseToken(this.tokenId, scheduledCollection);3197 }31983199 scheduleAfter<T extends UniqueHelper>(3200 scheduledId: string,3201 blocksBeforeExecution: number,3202 options: ISchedulerOptions = {},3203 ) {3204 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3205 return new UniqueBaseToken(this.tokenId, scheduledCollection);3206 }32073208 getSudo<T extends UniqueHelper>() {3209 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3210 }3211}321232133214export class UniqueNFToken extends UniqueBaseToken {3215 collection: UniqueNFTCollection;32163217 constructor(tokenId: number, collection: UniqueNFTCollection) {3218 super(tokenId, collection);3219 this.collection = collection;3220 }32213222 async getData(blockHashAt?: string) {3223 return await this.collection.getToken(this.tokenId, blockHashAt);3224 }32253226 async getOwner(blockHashAt?: string) {3227 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3228 }32293230 async getTopmostOwner(blockHashAt?: string) {3231 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3232 }32333234 async getChildren(blockHashAt?: string) {3235 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3236 }32373238 async nest(signer: TSigner, toTokenObj: IToken) {3239 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3240 }32413242 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3243 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3244 }32453246 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3247 return await this.collection.transferToken(signer, this.tokenId, addressObj);3248 }32493250 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3251 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3252 }32533254 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3255 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3256 }32573258 async isApproved(toAddressObj: ICrossAccountId) {3259 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3260 }32613262 async burn(signer: TSigner) {3263 return await this.collection.burnToken(signer, this.tokenId);3264 }32653266 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3267 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3268 }32693270 scheduleAt<T extends UniqueHelper>(3271 scheduledId: string,3272 executionBlockNumber: number,3273 options: ISchedulerOptions = {},3274 ) {3275 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3276 return new UniqueNFToken(this.tokenId, scheduledCollection);3277 }32783279 scheduleAfter<T extends UniqueHelper>(3280 scheduledId: string,3281 blocksBeforeExecution: number,3282 options: ISchedulerOptions = {},3283 ) {3284 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3285 return new UniqueNFToken(this.tokenId, scheduledCollection);3286 }32873288 getSudo<T extends UniqueHelper>() {3289 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3290 }3291}32923293export class UniqueRFToken extends UniqueBaseToken {3294 collection: UniqueRFTCollection;32953296 constructor(tokenId: number, collection: UniqueRFTCollection) {3297 super(tokenId, collection);3298 this.collection = collection;3299 }33003301 async getData(blockHashAt?: string) {3302 return await this.collection.getToken(this.tokenId, blockHashAt);3303 }33043305 async getTop10Owners() {3306 return await this.collection.getTop10TokenOwners(this.tokenId);3307 }33083309 async getBalance(addressObj: ICrossAccountId) {3310 return await this.collection.getTokenBalance(this.tokenId, addressObj);3311 }33123313 async getTotalPieces() {3314 return await this.collection.getTokenTotalPieces(this.tokenId);3315 }33163317 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3318 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3319 }33203321 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3322 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3323 }33243325 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3326 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3327 }33283329 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3330 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3331 }33323333 async repartition(signer: TSigner, amount: bigint) {3334 return await this.collection.repartitionToken(signer, this.tokenId, amount);3335 }33363337 async burn(signer: TSigner, amount=1n) {3338 return await this.collection.burnToken(signer, this.tokenId, amount);3339 }33403341 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3342 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3343 }33443345 scheduleAt<T extends UniqueHelper>(3346 scheduledId: string,3347 executionBlockNumber: number,3348 options: ISchedulerOptions = {},3349 ) {3350 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3351 return new UniqueRFToken(this.tokenId, scheduledCollection);3352 }33533354 scheduleAfter<T extends UniqueHelper>(3355 scheduledId: string,3356 blocksBeforeExecution: number,3357 options: ISchedulerOptions = {},3358 ) {3359 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3360 return new UniqueRFToken(this.tokenId, scheduledCollection);3361 }33623363 getSudo<T extends UniqueHelper>() {3364 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3365 }3366}