12345678import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents} 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, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314export const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {15 const address = {} as ICrossAccountId;16 if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;17 if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;18 return address;19};2021const nesting = {22 toChecksumAddress(address: string): string {23 if (typeof address === 'undefined') return '';2425 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);2627 address = address.toLowerCase().replace(/^0x/i,'');28 const addressHash = keccakAsHex(address).replace(/^0x/i,'');29 const checksumAddress = ['0x'];3031 for (let i = 0; i < address.length; i++) {32 33 if (parseInt(addressHash[i], 16) > 7) {34 checksumAddress.push(address[i].toUpperCase());35 } else {36 checksumAddress.push(address[i]);37 }38 }39 return checksumAddress.join('');40 },41 tokenIdToAddress(collectionId: number, tokenId: number) {42 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);43 },44};4546class UniqueUtil {47 static transactionStatus = {48 NOT_READY: 'NotReady',49 FAIL: 'Fail',50 SUCCESS: 'Success',51 };5253 static chainLogType = {54 EXTRINSIC: 'extrinsic',55 RPC: 'rpc',56 };5758 static getNestingTokenAddress(collectionId: number, tokenId: number) {59 return nesting.tokenIdToAddress(collectionId, tokenId);60 }6162 static getDefaultLogger(): ILogger {63 return {64 log(msg: any, level = 'INFO') {65 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));66 },67 level: {68 ERROR: 'ERROR',69 WARNING: 'WARNING',70 INFO: 'INFO',71 },72 };73 }7475 static vec2str(arr: string[] | number[]) {76 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');77 }7879 static str2vec(string: string) {80 if (typeof string !== 'string') return string;81 return Array.from(string).map(x => x.charCodeAt(0));82 }8384 static fromSeed(seed: string, ss58Format = 42) {85 const keyring = new Keyring({type: 'sr25519', ss58Format});86 return keyring.addFromUri(seed);87 }8889 static normalizeSubstrateAddress(address: string, ss58Format = 42) {90 return encodeAddress(decodeAddress(address), ss58Format);91 }9293 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult) {94 if (creationResult.status !== this.transactionStatus.SUCCESS) {95 throw Error('Unable to create collection!');96 }9798 let collectionId = null;99 creationResult.result.events.forEach(({event: {data, method, section}}) => {100 if ((section === 'common') && (method === 'CollectionCreated')) {101 collectionId = parseInt(data[0].toString(), 10);102 }103 });104105 if (collectionId === null) {106 throw Error('No CollectionCreated event was found!');107 }108109 return collectionId;110 }111112 static extractTokensFromCreationResult(creationResult: ITransactionResult) {113 if (creationResult.status !== this.transactionStatus.SUCCESS) {114 throw Error('Unable to create tokens!');115 }116 let success = false;117 const tokens = [] as any;118 creationResult.result.events.forEach(({event: {data, method, section}}) => {119 if (method === 'ExtrinsicSuccess') {120 success = true;121 } else if ((section === 'common') && (method === 'ItemCreated')) {122 tokens.push({123 collectionId: parseInt(data[0].toString(), 10),124 tokenId: parseInt(data[1].toString(), 10),125 owner: data[2].toJSON(),126 });127 }128 });129 return {success, tokens};130 }131132 static extractTokensFromBurnResult(burnResult: ITransactionResult) {133 if (burnResult.status !== this.transactionStatus.SUCCESS) {134 throw Error('Unable to burn tokens!');135 }136 let success = false;137 const tokens = [] as any;138 burnResult.result.events.forEach(({event: {data, method, section}}) => {139 if (method === 'ExtrinsicSuccess') {140 success = true;141 } else if ((section === 'common') && (method === 'ItemDestroyed')) {142 tokens.push({143 collectionId: parseInt(data[0].toString(), 10),144 tokenId: parseInt(data[1].toString(), 10),145 owner: data[2].toJSON(),146 });147 }148 });149 return {success, tokens};150 }151152 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string) {153 let eventId = null;154 events.forEach(({event: {data, method, section}}) => {155 if ((section === expectedSection) && (method === expectedMethod)) {156 eventId = parseInt(data[0].toString(), 10);157 }158 });159160 if (eventId === null) {161 throw Error(`No ${expectedMethod} event was found!`);162 }163 return eventId === collectionId;164 }165166 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {167 const normalizeAddress = (address: string | ICrossAccountId) => {168 if(typeof address === 'string') return address;169 const obj = {} as any;170 Object.keys(address).forEach(k => {171 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];172 });173 if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};174 if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};175 return address;176 };177 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;178 events.forEach(({event: {data, method, section}}) => {179 if ((section === 'common') && (method === 'Transfer')) {180 const hData = (data as any).toJSON();181 transfer = {182 collectionId: hData[0],183 tokenId: hData[1],184 from: normalizeAddress(hData[2]),185 to: normalizeAddress(hData[3]),186 amount: BigInt(hData[4]),187 };188 }189 });190 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;191 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);192 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);193 isSuccess = isSuccess && amount === transfer.amount;194 return isSuccess;195 }196}197198class UniqueEventHelper {199 private static extractIndex(index: any): [number, number] | string {200 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];201 return index.toJSON();202 }203204 private static extractSub(data: any, subTypes: any): {[key: string]: any} {205 let obj: any = {};206 let index = 0;207208 if (data.entries)209 for(const [key, value] of data.entries()) {210 obj[key] = this.extractData(value, subTypes[index]);211 index++;212 }213 else obj = data.toJSON();214215 return obj;216 }217 218 private static extractData(data: any, type: any): any {219 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();220 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();221 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);222 return data.toHuman();223 }224225 public static extractEvents(records: ITransactionResult): IEvent[] {226 const parsedEvents: IEvent[] = [];227228 records.result.events.forEach((record) => {229 const {event, phase} = record;230 const types = (event as any).typeDef;231232 const eventData: IEvent = {233 section: event.section.toString(),234 method: event.method.toString(),235 index: this.extractIndex(event.index),236 data: [],237 phase: phase.toJSON(),238 };239240 event.data.forEach((val: any, index: number) => {241 eventData.data.push(this.extractData(val, types[index]));242 });243244 parsedEvents.push(eventData);245 });246247 return parsedEvents;248 }249}250251class ChainHelperBase {252 transactionStatus = UniqueUtil.transactionStatus;253 chainLogType = UniqueUtil.chainLogType;254 util: typeof UniqueUtil;255 eventHelper: typeof UniqueEventHelper;256 logger: ILogger;257 api: ApiPromise | null;258 forcedNetwork: TUniqueNetworks | null;259 network: TUniqueNetworks | null;260 chainLog: IUniqueHelperLog[];261262 constructor(logger?: ILogger) {263 this.util = UniqueUtil;264 this.eventHelper = UniqueEventHelper;265 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();266 this.logger = logger;267 this.api = null;268 this.forcedNetwork = null;269 this.network = null;270 this.chainLog = [];271 }272273 clearChainLog(): void {274 this.chainLog = [];275 }276277 forceNetwork(value: TUniqueNetworks): void {278 this.forcedNetwork = value;279 }280281 async connect(wsEndpoint: string, listeners?: IApiListeners) {282 if (this.api !== null) throw Error('Already connected');283 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);284 this.api = api;285 this.network = network;286 }287288 async disconnect() {289 if (this.api === null) return;290 await this.api.disconnect();291 this.api = null;292 this.network = null;293 }294295 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {296 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;297 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;298 return 'opal';299 }300301 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {302 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});303 await api.isReady;304305 const network = await this.detectNetwork(api);306307 await api.disconnect();308309 return network;310 }311312 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{313 api: ApiPromise;314 network: TUniqueNetworks;315 }> {316 if(typeof network === 'undefined' || network === null) network = 'opal';317 const supportedRPC = {318 opal: {319 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,320 },321 quartz: {322 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,323 },324 unique: {325 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,326 },327 };328 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);329 const rpc = supportedRPC[network];330331 332 333334 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});335336 await api.isReadyOrError;337338 if (typeof listeners === 'undefined') listeners = {};339 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {340 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;341 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);342 }343344 return {api, network};345 }346347 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {348 const {events, status} = data;349 if (status.isReady) {350 return this.transactionStatus.NOT_READY;351 }352 if (status.isBroadcast) {353 return this.transactionStatus.NOT_READY;354 }355 if (status.isInBlock || status.isFinalized) {356 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');357 if (errors.length > 0) {358 return this.transactionStatus.FAIL;359 }360 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {361 return this.transactionStatus.SUCCESS;362 }363 }364365 return this.transactionStatus.FAIL;366 }367368 signTransaction(sender: TSigner, transaction: any, label = 'transaction', options: any = null) {369 const sign = (callback: any) => {370 if(options !== null) return transaction.signAndSend(sender, options, callback);371 return transaction.signAndSend(sender, callback);372 };373 374 return new Promise(async (resolve, reject) => {375 try {376 const unsub = await sign((result: any) => {377 const status = this.getTransactionStatus(result);378379 if (status === this.transactionStatus.SUCCESS) {380 this.logger.log(`${label} successful`);381 unsub();382 resolve({result, status});383 } else if (status === this.transactionStatus.FAIL) {384 let moduleError = null;385386 if (result.hasOwnProperty('dispatchError')) {387 const dispatchError = result['dispatchError'];388389 if (dispatchError) {390 if (dispatchError.isModule) {391 const modErr = dispatchError.asModule;392 const errorMeta = dispatchError.registry.findMetaError(modErr);393394 moduleError = `${errorMeta.section}.${errorMeta.name}`;395 } else {396 moduleError = dispatchError.toHuman();397 }398 } else {399 this.logger.log(result, this.logger.level.ERROR);400 }401 }402403 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);404 unsub();405 reject({status, moduleError, result});406 }407 });408 } catch (e) {409 this.logger.log(e, this.logger.level.ERROR);410 reject(e);411 }412 });413 }414415 constructApiCall(apiCall: string, params: any[]) {416 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);417 let call = this.api as any;418 for(const part of apiCall.slice(4).split('.')) {419 call = call[part];420 }421 return call(...params);422 }423424 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true) {425 if(this.api === null) throw Error('API not initialized');426 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);427428 const startTime = (new Date()).getTime();429 let result: ITransactionResult;430 let events: IEvent[] = [];431 try {432 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), extrinsic) as ITransactionResult;433 events = this.eventHelper.extractEvents(result);434 }435 catch(e) {436 if(!(e as object).hasOwnProperty('status')) throw e;437 result = e as ITransactionResult;438 }439440 const endTime = (new Date()).getTime();441442 const log = {443 executedAt: endTime,444 executionTime: endTime - startTime,445 type: this.chainLogType.EXTRINSIC,446 status: result.status,447 call: extrinsic,448 signer: this.getSignerAddress(sender),449 params,450 } as IUniqueHelperLog;451452 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;453 if(events.length > 0) log.events = events;454455 this.chainLog.push(log);456457 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);458 return result;459 }460461 async callRpc(rpc: string, params?: any[]) {462 if(typeof params === 'undefined') params = [];463 if(this.api === null) throw Error('API not initialized');464 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);465466 const startTime = (new Date()).getTime();467 let result;468 let error = null;469 const log = {470 type: this.chainLogType.RPC,471 call: rpc,472 params,473 } as IUniqueHelperLog;474475 try {476 result = await this.constructApiCall(rpc, params);477 }478 catch(e) {479 error = e;480 }481482 const endTime = (new Date()).getTime();483484 log.executedAt = endTime;485 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';486 log.executionTime = endTime - startTime;487488 this.chainLog.push(log);489490 if(error !== null) throw error;491492 return result;493 }494495 getSignerAddress(signer: IKeyringPair | string): string {496 if(typeof signer === 'string') return signer;497 return signer.address;498 }499500 fetchAllPalletNames(): string[] {501 if(this.api === null) throw Error('API not initialized');502 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());503 }504505 fetchMissingPalletNames(requiredPallets: string[]): string[] {506 const palletNames = this.fetchAllPalletNames();507 return requiredPallets.filter(p => !palletNames.includes(p));508 }509}510511512class HelperGroup {513 helper: UniqueHelper;514515 constructor(uniqueHelper: UniqueHelper) {516 this.helper = uniqueHelper;517 }518}519520521class CollectionGroup extends HelperGroup {522 523524525526527528529530531 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {532 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();533 }534535 536537538539540 async getTotalCount(): Promise<number> {541 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();542 }543544 545546547548549550551552553 async getData(collectionId: number): Promise<{554 id: number;555 name: string;556 description: string;557 tokensCount: number;558 admins: ICrossAccountId[];559 normalizedOwner: TSubstrateAccount;560 raw: any561 } | null> {562 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);563 const humanCollection = collection.toHuman(), collectionData = {564 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],565 raw: humanCollection,566 } as any, jsonCollection = collection.toJSON();567 if (humanCollection === null) return null;568 collectionData.raw.limits = jsonCollection.limits;569 collectionData.raw.permissions = jsonCollection.permissions;570 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);571 for (const key of ['name', 'description']) {572 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);573 }574575 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))576 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)577 : 0;578 collectionData.admins = await this.getAdmins(collectionId);579580 return collectionData;581 }582583 584585586587588589590591 async getAdmins(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {592 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();593594 return normalize595 ? admins.map((address: any) => {596 return address.Substrate597 ? {Substrate: this.helper.address.normalizeSubstrate(address.Substrate)}598 : address;599 })600 : admins;601 }602603 604605606607608609610 async getAllowList(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {611 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();612 return normalize613 ? allowListed.map((address: any) => {614 return address.Substrate615 ? {Substrate: this.helper.address.normalizeSubstrate(address.Substrate)}616 : address;617 })618 : allowListed;619 }620621 622623624625626627628 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {629 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();630 }631632 633634635636637638639640 async burn(signer: TSigner, collectionId: number): Promise<boolean> {641 const result = await this.helper.executeExtrinsic(642 signer,643 'api.tx.unique.destroyCollection', [collectionId],644 true,645 );646647 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');648 }649650 651652653654655656657658659 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {660 const result = await this.helper.executeExtrinsic(661 signer,662 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],663 true,664 );665666 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');667 }668669 670671672673674675676677 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {678 const result = await this.helper.executeExtrinsic(679 signer,680 'api.tx.unique.confirmSponsorship', [collectionId],681 true,682 );683684 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');685 }686687 688689690691692693694695 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {696 const result = await this.helper.executeExtrinsic(697 signer,698 'api.tx.unique.removeCollectionSponsor', [collectionId],699 true,700 );701702 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');703 }704705 706707708709710711712713714715716717718719720721722 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {723 const result = await this.helper.executeExtrinsic(724 signer,725 'api.tx.unique.setCollectionLimits', [collectionId, limits],726 true,727 );728729 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');730 }731732 733734735736737738739740741 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {742 const result = await this.helper.executeExtrinsic(743 signer,744 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],745 true,746 );747748 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');749 }750751 752753754755756757758759760 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {761 const result = await this.helper.executeExtrinsic(762 signer,763 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],764 true,765 );766767 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');768 }769770 771772773774775776777778779 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {780 const result = await this.helper.executeExtrinsic(781 signer,782 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],783 true,784 );785786 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');787 }788789 790791792793794795796797 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {798 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();799 }800801 802803804805806807808 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {809 const result = await this.helper.executeExtrinsic(810 signer,811 'api.tx.unique.addToAllowList', [collectionId, addressObj],812 true,813 );814815 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');816 }817818 819820821822823824825826 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {827 const result = await this.helper.executeExtrinsic(828 signer,829 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],830 true,831 );832833 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');834 }835836 837838839840841842843844845 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {846 const result = await this.helper.executeExtrinsic(847 signer,848 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],849 true,850 );851852 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');853 }854855 856857858859860861862863864 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {865 return await this.setPermissions(signer, collectionId, {nesting: permissions});866 }867868 869870871872873874875876 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {877 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});878 }879880 881882883884885886887888889 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {890 const result = await this.helper.executeExtrinsic(891 signer,892 'api.tx.unique.setCollectionProperties', [collectionId, properties],893 true,894 );895896 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');897 }898899 900901902903904905906907908 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {909 const result = await this.helper.executeExtrinsic(910 signer,911 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],912 true,913 );914915 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');916 }917918 919920921922923924925926927928929 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {930 const result = await this.helper.executeExtrinsic(931 signer,932 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],933 true, 934 );935936 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);937 }938939 940941942943944945946947948949950951952 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {953 const result = await this.helper.executeExtrinsic(954 signer,955 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],956 true, 957 );958 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);959 }960961 962963964965966967968969970971972 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<{973 success: boolean,974 token: number | null975 }> {976 const burnResult = await this.helper.executeExtrinsic(977 signer,978 'api.tx.unique.burnItem', [collectionId, tokenId, amount],979 true, 980 );981 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);982 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');983 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};984 }985986 987988989990991992993994995996997 async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, amount=1n): Promise<boolean> {998 const burnResult = await this.helper.executeExtrinsic(999 signer,1000 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1001 true, 1002 );1003 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1004 return burnedTokens.success && burnedTokens.tokens.length > 0;1005 }10061007 1008100910101011101210131014101510161017 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1018 const approveResult = await this.helper.executeExtrinsic(1019 signer,1020 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1021 true, 1022 );10231024 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1025 }10261027 1028102910301031103210331034103510361037 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1038 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1039 }10401041 1042104310441045104610471048 async getLastTokenId(collectionId: number): Promise<number> {1049 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1050 }10511052 10531054105510561057105810591060 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {1061 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1062 }1063}10641065class NFTnRFT extends CollectionGroup {1066 10671068106910701071107210731074 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1075 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1076 }10771078 1079108010811082108310841085108610871088 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1089 properties: IProperty[];1090 owner: ICrossAccountId;1091 normalizedOwner: ICrossAccountId;1092 }| null> {1093 let tokenData;1094 if(typeof blockHashAt === 'undefined') {1095 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1096 }1097 else {1098 if(propertyKeys.length == 0) {1099 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1100 if(!collection) return null;1101 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1102 }1103 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1104 }1105 tokenData = tokenData.toHuman();1106 if (tokenData === null || tokenData.owner === null) return null;1107 const owner = {} as any;1108 for (const key of Object.keys(tokenData.owner)) {1109 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];1110 }1111 tokenData.normalizedOwner = crossAccountIdFromLower(owner);1112 return tokenData;1113 }11141115 11161117111811191120112111221123112411251126 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1127 const result = await this.helper.executeExtrinsic(1128 signer,1129 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1130 true,1131 );11321133 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1134 }11351136 1137113811391140114111421143114411451146 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1147 const result = await this.helper.executeExtrinsic(1148 signer,1149 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1150 true,1151 );11521153 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1154 }11551156 115711581159116011611162116311641165 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1166 const result = await this.helper.executeExtrinsic(1167 signer,1168 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1169 true,1170 );11711172 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1173 }11741175 117611771178117911801181118211831184 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueCollectionBase> {1185 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1186 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1187 for (const key of ['name', 'description', 'tokenPrefix']) {1188 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);1189 }1190 const creationResult = await this.helper.executeExtrinsic(1191 signer,1192 'api.tx.unique.createCollectionEx', [collectionOptions],1193 true, 1194 );1195 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1196 }11971198 getCollectionObject(_collectionId: number): any {1199 return null;1200 }12011202 getTokenObject(_collectionId: number, _tokenId: number): any {1203 return null;1204 }1205}120612071208class NFTGroup extends NFTnRFT {1209 121012111212121312141215 getCollectionObject(collectionId: number): UniqueNFTCollection {1216 return new UniqueNFTCollection(collectionId, this.helper);1217 }12181219 1220122112221223122412251226 getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1227 return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1228 }12291230 12311232123312341235123612371238 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1239 let owner;1240 if (typeof blockHashAt === 'undefined') {1241 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1242 } else {1243 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1244 }1245 return crossAccountIdFromLower(owner.toJSON());1246 }12471248 1249125012511252125312541255 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1256 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1257 }12581259 1260126112621263126412651266126712681269 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1270 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1271 }12721273 127412751276127712781279128012811282128312841285 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1286 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1287 }12881289 12901291129212931294129512961297 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1298 let owner;1299 if (typeof blockHashAt === 'undefined') {1300 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1301 } else {1302 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1303 }13041305 if (owner === null) return null;13061307 owner = owner.toHuman();13081309 return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1310 }13111312 13131314131513161317131813191320 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1321 let children;1322 if(typeof blockHashAt === 'undefined') {1323 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1324 } else {1325 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1326 }13271328 return children.toJSON().map((x: any) => {1329 return {collectionId: x.collection, tokenId: x.token};1330 });1331 }13321333 13341335133613371338133913401341 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1342 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1343 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1344 if(!result) {1345 throw Error('Unable to nest token!');1346 }1347 return result;1348 }13491350 135113521353135413551356135713581359 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1360 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1361 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1362 if(!result) {1363 throw Error('Unable to unnest token!');1364 }1365 return result;1366 }13671368 136913701371137213731374137513761377137813791380 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueNFTCollection> {1381 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1382 }13831384 138513861387138813891390 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFTToken> {1391 const creationResult = await this.helper.executeExtrinsic(1392 signer,1393 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1394 nft: {1395 properties: data.properties,1396 },1397 }],1398 true,1399 );1400 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1401 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1402 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1403 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1404 }14051406 140714081409141014111412141314141415141614171418141914201421 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1422 const creationResult = await this.helper.executeExtrinsic(1423 signer,1424 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1425 true,1426 );1427 const collection = this.getCollectionObject(collectionId);1428 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1429 }14301431 143214331434143514361437143814391440144114421443144414451446144714481449 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1450 const rawTokens = [];1451 for (const token of tokens) {1452 const raw = {NFT: {properties: token.properties}};1453 rawTokens.push(raw);1454 }1455 const creationResult = await this.helper.executeExtrinsic(1456 signer,1457 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1458 true,1459 );1460 const collection = this.getCollectionObject(collectionId);1461 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1462 }14631464 1465146614671468146914701471147214731474 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1475 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1476 }1477}147814791480class RFTGroup extends NFTnRFT {1481 148214831484148514861487 getCollectionObject(collectionId: number): UniqueRFTCollection {1488 return new UniqueRFTCollection(collectionId, this.helper);1489 }14901491 1492149314941495149614971498 getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1499 return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1500 }15011502 1503150415051506150715081509 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1510 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1511 }15121513 15141515151615171518151915201521 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1522 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1523 }15241525 1526152715281529153015311532153315341535 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1536 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1537 }15381539 15401541154215431544154515461547154815491550 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1551 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1552 }15531554 155515561557155815591560156115621563156415651566 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueRFTCollection> {1567 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1568 }15691570 1571157215731574157515761577 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFTToken> {1578 const creationResult = await this.helper.executeExtrinsic(1579 signer,1580 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1581 refungible: {1582 pieces: data.pieces,1583 properties: data.properties,1584 },1585 }],1586 true,1587 );1588 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1589 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1590 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1591 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1592 }15931594 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1595 throw Error('Not implemented');1596 const creationResult = await this.helper.executeExtrinsic(1597 signer,1598 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1599 true, 1600 );1601 const collection = this.getCollectionObject(collectionId);1602 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1603 }16041605 160616071608160916101611161216131614 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1615 const rawTokens = [];1616 for (const token of tokens) {1617 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1618 rawTokens.push(raw);1619 }1620 const creationResult = await this.helper.executeExtrinsic(1621 signer,1622 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1623 true,1624 );1625 const collection = this.getCollectionObject(collectionId);1626 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1627 }16281629 163016311632163316341635163616371638 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<{ success: boolean; token: number | null; }> {1639 return await super.burnToken(signer, collectionId, tokenId, amount);1640 }16411642 16431644164516461647164816491650165116521653 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1654 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1655 }16561657 1658165916601661166216631664 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1665 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1666 }16671668 166916701671167216731674167516761677 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1678 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1679 const repartitionResult = await this.helper.executeExtrinsic(1680 signer,1681 'api.tx.unique.repartition', [collectionId, tokenId, amount],1682 true,1683 );1684 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1685 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1686 }1687}168816891690class FTGroup extends CollectionGroup {1691 169216931694169516961697 getCollectionObject(collectionId: number): UniqueFTCollection {1698 return new UniqueFTCollection(collectionId, this.helper);1699 }17001701 1702170317041705170617071708170917101711171217131714 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0): Promise<UniqueFTCollection> {1715 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1716 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1717 collectionOptions.mode = {fungible: decimalPoints};1718 for (const key of ['name', 'description', 'tokenPrefix']) {1719 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);1720 }1721 const creationResult = await this.helper.executeExtrinsic(1722 signer,1723 'api.tx.unique.createCollectionEx', [collectionOptions],1724 true,1725 );1726 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1727 }17281729 173017311732173317341735173617371738 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1739 const creationResult = await this.helper.executeExtrinsic(1740 signer,1741 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1742 fungible: {1743 value: amount,1744 },1745 }],1746 true, 1747 );1748 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1749 }17501751 17521753175417551756175717581759 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1760 const rawTokens = [];1761 for (const token of tokens) {1762 const raw = {Fungible: {Value: token.value}};1763 rawTokens.push(raw);1764 }1765 const creationResult = await this.helper.executeExtrinsic(1766 signer,1767 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1768 true,1769 );1770 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1771 }17721773 177417751776177717781779 async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1780 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1781 }17821783 1784178517861787178817891790 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1791 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1792 }17931794 179517961797179817991800180118021803 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1804 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1805 }18061807 1808180918101811181218131814181518161817 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1818 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1819 }18201821 18221823182418251826182718281829 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1830 return (await super.burnToken(signer, collectionId, 0, amount)).success;1831 }18321833 183418351836183718381839184018411842 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1843 return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, amount);1844 }18451846 18471848184918501851 async getTotalPieces(collectionId: number): Promise<bigint> {1852 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1853 }18541855 1856185718581859186018611862186318641865 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1866 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1867 }18681869 1870187118721873187418751876 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1877 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1878 }1879}188018811882class ChainGroup extends HelperGroup {1883 18841885188618871888 getChainProperties(): IChainProperties {1889 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1890 return {1891 ss58Format: properties.ss58Format.toJSON(),1892 tokenDecimals: properties.tokenDecimals.toJSON(),1893 tokenSymbol: properties.tokenSymbol.toJSON(),1894 };1895 }18961897 18981899190019011902 async getLatestBlockNumber(): Promise<number> {1903 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1904 }19051906 190719081909191019111912 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1913 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1914 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1915 return blockHash;1916 }19171918 1919 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {1920 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);1921 if (!blockHash) return null;1922 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;1923 }19241925 192619271928192919301931 async getNonce(address: TSubstrateAccount): Promise<number> {1932 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1933 }1934}193519361937class BalanceGroup extends HelperGroup {1938 19391940194119421943 getOneTokenNominal(): bigint {1944 const chainProperties = this.helper.chain.getChainProperties();1945 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1946 }19471948 194919501951195219531954 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {1955 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();1956 }19571958 19591960196119621963 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {1964 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;1965 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};1966 }19671968 196919701971197219731974 async getEthereum(address: TEthereumAccount): Promise<bigint> {1975 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();1976 }19771978 19791980198119821983198419851986 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {1987 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);19881989 let transfer = {from: null, to: null, amount: 0n} as any;1990 result.result.events.forEach(({event: {data, method, section}}) => {1991 if ((section === 'balances') && (method === 'Transfer')) {1992 transfer = {1993 from: this.helper.address.normalizeSubstrate(data[0]),1994 to: this.helper.address.normalizeSubstrate(data[1]),1995 amount: BigInt(data[2]),1996 };1997 }1998 });1999 let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;2000 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;2001 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2002 return isSuccess;2003 }2004}200520062007class AddressGroup extends HelperGroup {2008 2009201020112012201320142015 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2016 return this.helper.util.normalizeSubstrateAddress(address, ss58Format);2017 }20182019 202020212022202320242025 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {2026 const info = this.helper.chain.getChainProperties();2027 return encodeAddress(decodeAddress(address), info.ss58Format);2028 }20292030 2031203220332034203520362037 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {2038 if(!toChainFormat) return evmToAddress(ethAddress);2039 const info = this.helper.chain.getChainProperties();2040 return evmToAddress(ethAddress, info.ss58Format);2041 }20422043 204420452046204720482049 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2050 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));2051 }2052}20532054class StakingGroup extends HelperGroup {2055 2056205720582059206020612062 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2063 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2064 const stakeResult = await this.helper.executeExtrinsic(2065 signer, 'api.tx.appPromotion.stake',2066 [amountToStake], true,2067 );2068 2069 return true;2070 }20712072 2073207420752076207720782079 async unstake(signer: TSigner, label?: string): Promise<number> {2080 if(typeof label === 'undefined') label = `${signer.address}`;2081 const unstakeResult = await this.helper.executeExtrinsic(2082 signer, 'api.tx.appPromotion.unstake',2083 [], true,2084 );2085 2086 return 1;2087 }20882089 20902091209220932094 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2095 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2096 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2097 }20982099 21002101210221032104 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2105 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2106 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2107 return { 2108 block: block.toBigInt(),2109 amount: amount.toBigInt(),2110 };2111 });2112 }21132114 21152116211721182119 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2120 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2121 }21222123 21242125212621272128 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2129 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2130 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2131 return {2132 block: block.toBigInt(),2133 amount: amount.toBigInt(),2134 };2135 });2136 return result;2137 }2138}21392140export class UniqueHelper extends ChainHelperBase {2141 chain: ChainGroup;2142 balance: BalanceGroup;2143 address: AddressGroup;2144 collection: CollectionGroup;2145 nft: NFTGroup;2146 rft: RFTGroup;2147 ft: FTGroup;2148 staking: StakingGroup;21492150 constructor(logger?: ILogger) {2151 super(logger);2152 this.chain = new ChainGroup(this);2153 this.balance = new BalanceGroup(this);2154 this.address = new AddressGroup(this);2155 this.collection = new CollectionGroup(this);2156 this.nft = new NFTGroup(this);2157 this.rft = new RFTGroup(this);2158 this.ft = new FTGroup(this);2159 this.staking = new StakingGroup(this);2160 }2161}216221632164class UniqueCollectionBase {2165 helper: UniqueHelper;2166 collectionId: number;21672168 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2169 this.collectionId = collectionId;2170 this.helper = uniqueHelper;2171 }21722173 async getData() {2174 return await this.helper.collection.getData(this.collectionId);2175 }21762177 async getLastTokenId() {2178 return await this.helper.collection.getLastTokenId(this.collectionId);2179 }21802181 async isTokenExists(tokenId: number) {2182 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2183 }21842185 async getAdmins() {2186 return await this.helper.collection.getAdmins(this.collectionId);2187 }21882189 async getAllowList() {2190 return await this.helper.collection.getAllowList(this.collectionId);2191 }21922193 async getEffectiveLimits() {2194 return await this.helper.collection.getEffectiveLimits(this.collectionId);2195 }21962197 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2198 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2199 }22002201 async confirmSponsorship(signer: TSigner) {2202 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2203 }22042205 async removeSponsor(signer: TSigner) {2206 return await this.helper.collection.removeSponsor(signer, this.collectionId);2207 }22082209 async setLimits(signer: TSigner, limits: ICollectionLimits) {2210 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2211 }22122213 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2214 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2215 }22162217 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2218 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2219 }22202221 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2222 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2223 }22242225 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2226 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2227 }22282229 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2230 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2231 }22322233 async setProperties(signer: TSigner, properties: IProperty[]) {2234 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2235 }22362237 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2238 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2239 }22402241 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2242 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2243 }22442245 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2246 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2247 }22482249 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2250 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2251 }22522253 async disableNesting(signer: TSigner) {2254 return await this.helper.collection.disableNesting(signer, this.collectionId);2255 }22562257 async burn(signer: TSigner) {2258 return await this.helper.collection.burn(signer, this.collectionId);2259 }2260}226122622263class UniqueNFTCollection extends UniqueCollectionBase {2264 getTokenObject(tokenId: number) {2265 return new UniqueNFTToken(tokenId, this);2266 }22672268 async getTokensByAddress(addressObj: ICrossAccountId) {2269 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2270 }22712272 async getToken(tokenId: number, blockHashAt?: string) {2273 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2274 }22752276 async getTokenOwner(tokenId: number, blockHashAt?: string) {2277 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2278 }22792280 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2281 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2282 }22832284 async getTokenChildren(tokenId: number, blockHashAt?: string) {2285 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2286 }22872288 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2289 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2290 }22912292 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2293 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2294 }22952296 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2297 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2298 }22992300 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2301 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2302 }23032304 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2305 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2306 }23072308 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2309 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2310 }23112312 async burnToken(signer: TSigner, tokenId: number) {2313 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2314 }23152316 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2317 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2318 }23192320 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2321 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2322 }23232324 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2325 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2326 }23272328 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2329 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2330 }23312332 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2333 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2334 }2335}233623372338class UniqueRFTCollection extends UniqueCollectionBase {2339 getTokenObject(tokenId: number) {2340 return new UniqueRFTToken(tokenId, this);2341 }23422343 async getTokensByAddress(addressObj: ICrossAccountId) {2344 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2345 }23462347 async getTop10TokenOwners(tokenId: number) {2348 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2349 }23502351 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2352 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2353 }23542355 async getTokenTotalPieces(tokenId: number) {2356 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2357 }23582359 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2360 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2361 }23622363 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2364 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2365 }23662367 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2368 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2369 }23702371 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2372 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2373 }23742375 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2376 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2377 }23782379 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2380 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2381 }23822383 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2384 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2385 }23862387 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2388 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2389 }23902391 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2392 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2393 }23942395 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2396 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2397 }23982399 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2400 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2401 }2402}240324042405class UniqueFTCollection extends UniqueCollectionBase {2406 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2407 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2408 }24092410 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2411 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2412 }24132414 async getBalance(addressObj: ICrossAccountId) {2415 return await this.helper.ft.getBalance(this.collectionId, addressObj);2416 }24172418 async getTop10Owners() {2419 return await this.helper.ft.getTop10Owners(this.collectionId);2420 }24212422 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2423 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2424 }24252426 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2427 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2428 }24292430 async burnTokens(signer: TSigner, amount=1n) {2431 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2432 }24332434 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2435 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2436 }24372438 async getTotalPieces() {2439 return await this.helper.ft.getTotalPieces(this.collectionId);2440 }24412442 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2443 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2444 }24452446 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2447 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2448 }2449}245024512452class UniqueTokenBase implements IToken {2453 collection: UniqueNFTCollection | UniqueRFTCollection;2454 collectionId: number;2455 tokenId: number;24562457 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2458 this.collection = collection;2459 this.collectionId = collection.collectionId;2460 this.tokenId = tokenId;2461 }24622463 async getNextSponsored(addressObj: ICrossAccountId) {2464 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2465 }24662467 async setProperties(signer: TSigner, properties: IProperty[]) {2468 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2469 }24702471 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2472 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2473 }2474}247524762477class UniqueNFTToken extends UniqueTokenBase {2478 collection: UniqueNFTCollection;24792480 constructor(tokenId: number, collection: UniqueNFTCollection) {2481 super(tokenId, collection);2482 this.collection = collection;2483 }24842485 async getData(blockHashAt?: string) {2486 return await this.collection.getToken(this.tokenId, blockHashAt);2487 }24882489 async getOwner(blockHashAt?: string) {2490 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2491 }24922493 async getTopmostOwner(blockHashAt?: string) {2494 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2495 }24962497 async getChildren(blockHashAt?: string) {2498 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2499 }25002501 async nest(signer: TSigner, toTokenObj: IToken) {2502 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2503 }25042505 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2506 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2507 }25082509 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2510 return await this.collection.transferToken(signer, this.tokenId, addressObj);2511 }25122513 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2514 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2515 }25162517 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2518 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2519 }25202521 async isApproved(toAddressObj: ICrossAccountId) {2522 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2523 }25242525 async burn(signer: TSigner) {2526 return await this.collection.burnToken(signer, this.tokenId);2527 }2528}25292530class UniqueRFTToken extends UniqueTokenBase {2531 collection: UniqueRFTCollection;25322533 constructor(tokenId: number, collection: UniqueRFTCollection) {2534 super(tokenId, collection);2535 this.collection = collection;2536 }25372538 async getTop10Owners() {2539 return await this.collection.getTop10TokenOwners(this.tokenId);2540 }25412542 async getBalance(addressObj: ICrossAccountId) {2543 return await this.collection.getTokenBalance(this.tokenId, addressObj);2544 }25452546 async getTotalPieces() {2547 return await this.collection.getTokenTotalPieces(this.tokenId);2548 }25492550 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2551 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2552 }25532554 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2555 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2556 }25572558 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2559 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2560 }25612562 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2563 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2564 }25652566 async repartition(signer: TSigner, amount: bigint) {2567 return await this.collection.repartitionToken(signer, this.tokenId, amount);2568 }25692570 async burn(signer: TSigner, amount=1n) {2571 return await this.collection.burnToken(signer, this.tokenId, amount);2572 }2573}