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, IChainEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314const 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};202122const nesting = {23 toChecksumAddress(address: string): string {24 if (typeof address === 'undefined') return '';2526 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);2728 address = address.toLowerCase().replace(/^0x/i,'');29 const addressHash = keccakAsHex(address).replace(/^0x/i,'');30 const checksumAddress = ['0x'];3132 for (let i = 0; i < address.length; i++) {33 34 if (parseInt(addressHash[i], 16) > 7) {35 checksumAddress.push(address[i].toUpperCase());36 } else {37 checksumAddress.push(address[i]);38 }39 }40 return checksumAddress.join('');41 },42 tokenIdToAddress(collectionId: number, tokenId: number) {43 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);44 },45};4647class UniqueUtil {48 static transactionStatus = {49 NOT_READY: 'NotReady',50 FAIL: 'Fail',51 SUCCESS: 'Success',52 };5354 static chainLogType = {55 EXTRINSIC: 'extrinsic',56 RPC: 'rpc',57 };5859 static getNestingTokenAddress(collectionId: number, tokenId: number) {60 return nesting.tokenIdToAddress(collectionId, tokenId);61 }6263 static getDefaultLogger(): ILogger {64 return {65 log(msg: any, level = 'INFO') {66 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));67 },68 level: {69 ERROR: 'ERROR',70 WARNING: 'WARNING',71 INFO: 'INFO',72 },73 };74 }7576 static vec2str(arr: string[] | number[]) {77 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');78 }7980 static str2vec(string: string) {81 if (typeof string !== 'string') return string;82 return Array.from(string).map(x => x.charCodeAt(0));83 }8485 static fromSeed(seed: string, ss58Format = 42) {86 const keyring = new Keyring({type: 'sr25519', ss58Format});87 return keyring.addFromUri(seed);88 }8990 static normalizeSubstrateAddress(address: string, ss58Format = 42) {91 return encodeAddress(decodeAddress(address), ss58Format);92 }9394 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult, label = 'new collection') {95 if (creationResult.status !== this.transactionStatus.SUCCESS) {96 throw Error(`Unable to create collection for ${label}`);97 }9899 let collectionId = null;100 creationResult.result.events.forEach(({event: {data, method, section}}) => {101 if ((section === 'common') && (method === 'CollectionCreated')) {102 collectionId = parseInt(data[0].toString(), 10);103 }104 });105106 if (collectionId === null) {107 throw Error(`No CollectionCreated event for ${label}`);108 }109110 return collectionId;111 }112113 static extractTokensFromCreationResult(creationResult: ITransactionResult, label = 'new tokens') {114 if (creationResult.status !== this.transactionStatus.SUCCESS) {115 throw Error(`Unable to create tokens for ${label}`);116 }117 let success = false;118 const tokens = [] as any;119 creationResult.result.events.forEach(({event: {data, method, section}}) => {120 if (method === 'ExtrinsicSuccess') {121 success = true;122 } else if ((section === 'common') && (method === 'ItemCreated')) {123 tokens.push({124 collectionId: parseInt(data[0].toString(), 10),125 tokenId: parseInt(data[1].toString(), 10),126 owner: data[2].toJSON(),127 });128 }129 });130 return {success, tokens};131 }132133 static extractTokensFromBurnResult(burnResult: ITransactionResult, label = 'burned tokens') {134 if (burnResult.status !== this.transactionStatus.SUCCESS) {135 throw Error(`Unable to burn tokens for ${label}`);136 }137 let success = false;138 const tokens = [] as any;139 burnResult.result.events.forEach(({event: {data, method, section}}) => {140 if (method === 'ExtrinsicSuccess') {141 success = true;142 } else if ((section === 'common') && (method === 'ItemDestroyed')) {143 tokens.push({144 collectionId: parseInt(data[0].toString(), 10),145 tokenId: parseInt(data[1].toString(), 10),146 owner: data[2].toJSON(),147 });148 }149 });150 return {success, tokens};151 }152153 static findCollectionInEvents(events: {event: IChainEvent}[], collectionId: number, expectedSection: string, expectedMethod: string, label?: string) {154 let eventId = null;155 events.forEach(({event: {data, method, section}}) => {156 if ((section === expectedSection) && (method === expectedMethod)) {157 eventId = parseInt(data[0].toString(), 10);158 }159 });160161 if (eventId === null) {162 throw Error(`No ${expectedMethod} event for ${label}`);163 }164 return eventId === collectionId;165 }166167 static isTokenTransferSuccess(events: {event: IChainEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {168 const normalizeAddress = (address: string | ICrossAccountId) => {169 if(typeof address === 'string') return address;170 const obj = {} as any;171 Object.keys(address).forEach(k => {172 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];173 });174 if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};175 if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};176 return address;177 };178 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;179 events.forEach(({event: {data, method, section}}) => {180 if ((section === 'common') && (method === 'Transfer')) {181 const hData = (data as any).toJSON();182 transfer = {183 collectionId: hData[0],184 tokenId: hData[1],185 from: normalizeAddress(hData[2]),186 to: normalizeAddress(hData[3]),187 amount: BigInt(hData[4]),188 };189 }190 });191 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;192 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);193 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);194 isSuccess = isSuccess && amount === transfer.amount;195 return isSuccess;196 }197}198199200class ChainHelperBase {201 transactionStatus = UniqueUtil.transactionStatus;202 chainLogType = UniqueUtil.chainLogType;203 util: typeof UniqueUtil;204 logger: ILogger;205 api: ApiPromise | null;206 forcedNetwork: TUniqueNetworks | null;207 network: TUniqueNetworks | null;208 chainLog: IUniqueHelperLog[];209210 constructor(logger?: ILogger) {211 this.util = UniqueUtil;212 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();213 this.logger = logger;214 this.api = null;215 this.forcedNetwork = null;216 this.network = null;217 this.chainLog = [];218 }219220 clearChainLog(): void {221 this.chainLog = [];222 }223224 forceNetwork(value: TUniqueNetworks): void {225 this.forcedNetwork = value;226 }227228 async connect(wsEndpoint: string, listeners?: IApiListeners) {229 if (this.api !== null) throw Error('Already connected');230 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);231 this.api = api;232 this.network = network;233 }234235 async disconnect() {236 if (this.api === null) return;237 await this.api.disconnect();238 this.api = null;239 this.network = null;240 }241242 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {243 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;244 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;245 return 'opal';246 }247248 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {249 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});250 await api.isReady;251252 const network = await this.detectNetwork(api);253254 await api.disconnect();255256 return network;257 }258259 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{ 260 api: ApiPromise; 261 network: TUniqueNetworks; 262 }> {263 if(typeof network === 'undefined' || network === null) network = 'opal';264 const supportedRPC = {265 opal: {266 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,267 },268 quartz: {269 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,270 },271 unique: {272 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,273 },274 };275 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);276 const rpc = supportedRPC[network];277278 279 280281 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});282283 await api.isReadyOrError;284285 if (typeof listeners === 'undefined') listeners = {};286 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {287 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;288 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);289 }290291 return {api, network};292 }293294 getTransactionStatus(data: {events: {event: IChainEvent}[], status: any}) {295 const {events, status} = data;296 if (status.isReady) {297 return this.transactionStatus.NOT_READY;298 }299 if (status.isBroadcast) {300 return this.transactionStatus.NOT_READY;301 }302 if (status.isInBlock || status.isFinalized) {303 const errors = events.filter(e => e.event.data.method === 'ExtrinsicFailed');304 if (errors.length > 0) {305 return this.transactionStatus.FAIL;306 }307 if (events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {308 return this.transactionStatus.SUCCESS;309 }310 }311312 return this.transactionStatus.FAIL;313 }314315 signTransaction(sender: TSigner, transaction: any, label = 'transaction', options: any = null) {316 const sign = (callback: any) => {317 if(options !== null) return transaction.signAndSend(sender, options, callback);318 return transaction.signAndSend(sender, callback);319 };320 return new Promise(async (resolve, reject) => {321 try {322 const unsub = await sign((result: any) => {323 const status = this.getTransactionStatus(result);324325 if (status === this.transactionStatus.SUCCESS) {326 this.logger.log(`${label} successful`);327 unsub();328 resolve({result, status});329 } else if (status === this.transactionStatus.FAIL) {330 let moduleError = null;331332 if (result.hasOwnProperty('dispatchError')) {333 const dispatchError = result['dispatchError'];334335 if (dispatchError && dispatchError.isModule) {336 const modErr = dispatchError.asModule;337 const errorMeta = dispatchError.registry.findMetaError(modErr);338339 moduleError = `${errorMeta.section}.${errorMeta.name}`;340 }341 else {342 this.logger.log(result, this.logger.level.ERROR);343 }344 }345346 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);347 unsub();348 reject({status, moduleError, result});349 }350 });351 } catch (e) {352 this.logger.log(e, this.logger.level.ERROR);353 reject(e);354 }355 });356 }357358 constructApiCall(apiCall: string, params: any[]) {359 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);360 let call = this.api as any;361 for(const part of apiCall.slice(4).split('.')) {362 call = call[part];363 }364 return call(...params);365 }366367 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=false, failureMessage='expected success') {368 if(this.api === null) throw Error('API not initialized');369 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);370371 const startTime = (new Date()).getTime();372 let result: ITransactionResult;373 let events = [];374 try {375 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), extrinsic) as ITransactionResult;376 events = result.result.events.map((x: any) => x.toHuman());377 }378 catch(e) {379 if(!(e as object).hasOwnProperty('status')) throw e;380 result = e as ITransactionResult;381 }382383 const endTime = (new Date()).getTime();384385 const log = {386 executedAt: endTime,387 executionTime: endTime - startTime,388 type: this.chainLogType.EXTRINSIC,389 status: result.status,390 call: extrinsic,391 signer: this.getSignerAddress(sender),392 params,393 } as IUniqueHelperLog;394395 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;396 if(events.length > 0) log.events = events;397398 this.chainLog.push(log);399400 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(failureMessage);401 return result;402 }403404 async callRpc(rpc: string, params?: any[]) {405 if(typeof params === 'undefined') params = [];406 if(this.api === null) throw Error('API not initialized');407 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);408409 const startTime = (new Date()).getTime();410 let result;411 let error = null;412 const log = {413 type: this.chainLogType.RPC,414 call: rpc,415 params,416 } as IUniqueHelperLog;417418 try {419 result = await this.constructApiCall(rpc, params);420 }421 catch(e) {422 error = e;423 }424425 const endTime = (new Date()).getTime();426427 log.executedAt = endTime;428 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';429 log.executionTime = endTime - startTime;430431 this.chainLog.push(log);432433 if(error !== null) throw error;434435 return result;436 }437438 getSignerAddress(signer: IKeyringPair | string): string {439 if(typeof signer === 'string') return signer;440 return signer.address;441 }442}443444445class HelperGroup {446 helper: UniqueHelper;447448 constructor(uniqueHelper: UniqueHelper) {449 this.helper = uniqueHelper;450 }451}452453454class CollectionGroup extends HelperGroup {455 456457458459460461462463464 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {465 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();466 }467468 469470471472473 async getTotalCount(): Promise<number> {474 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();475 }476477 478479480481482483484 async getData(collectionId: number): Promise<{485 id: number;486 name: string;487 description: string;488 tokensCount: number;489 admins: ICrossAccountId[];490 normalizedOwner: TSubstrateAccount;491 raw: any492 } | null> {493 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);494 const humanCollection = collection.toHuman(), collectionData = {495 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],496 raw: humanCollection,497 } as any, jsonCollection = collection.toJSON();498 if (humanCollection === null) return null;499 collectionData.raw.limits = jsonCollection.limits;500 collectionData.raw.permissions = jsonCollection.permissions;501 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);502 for (const key of ['name', 'description']) {503 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);504 }505506 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode)) ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId) : 0;507 collectionData.admins = await this.getAdmins(collectionId);508509 return collectionData;510 }511512 513514515516517518519 async getAdmins(collectionId: number): Promise<ICrossAccountId[]> {520 const normalized = [];521 for(const admin of (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman()) {522 if(admin.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(admin.Substrate)});523 else normalized.push(admin);524 }525 return normalized;526 }527528 529530531532533534 async getAllowList(collectionId: number): Promise<ICrossAccountId[]> {535 const normalized = [];536 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();537 for (const address of allowListed) {538 if (address.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(address.Substrate)});539 else normalized.push(address);540 }541 return normalized;542 }543544 545546547548549550551 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {552 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();553 }554555 556557558559560561562563564 async burn(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {565 if(typeof label === 'undefined') label = `collection #${collectionId}`;566 const result = await this.helper.executeExtrinsic(567 signer,568 'api.tx.unique.destroyCollection', [collectionId],569 true, `Unable to burn collection for ${label}`,570 );571572 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed', label);573 }574575 576577578579580581582583584585 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount, label?: string): Promise<boolean> {586 if(typeof label === 'undefined') label = `collection #${collectionId}`;587 const result = await this.helper.executeExtrinsic(588 signer,589 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],590 true, `Unable to set collection sponsor for ${label}`,591 );592593 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet', label);594 }595596 597598599600601602603604605 async confirmSponsorship(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {606 if(typeof label === 'undefined') label = `collection #${collectionId}`;607 const result = await this.helper.executeExtrinsic(608 signer,609 'api.tx.unique.confirmSponsorship', [collectionId],610 true, `Unable to confirm collection sponsorship for ${label}`,611 );612613 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed', label);614 }615616 617618619620621622623624625626627628629630631632633634 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits, label?: string): Promise<boolean> {635 if(typeof label === 'undefined') label = `collection #${collectionId}`;636 const result = await this.helper.executeExtrinsic(637 signer,638 'api.tx.unique.setCollectionLimits', [collectionId, limits],639 true, `Unable to set collection limits for ${label}`,640 );641642 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet', label);643 }644645 646647648649650651652653654655 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount, label?: string): Promise<boolean> {656 if(typeof label === 'undefined') label = `collection #${collectionId}`;657 const result = await this.helper.executeExtrinsic(658 signer,659 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],660 true, `Unable to change collection owner for ${label}`,661 );662663 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged', label);664 }665666 667668669670671672673674675676 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {677 if(typeof label === 'undefined') label = `collection #${collectionId}`;678 const result = await this.helper.executeExtrinsic(679 signer,680 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],681 true, `Unable to add collection admin for ${label}`,682 );683684 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded', label);685 }686687 688689690691692693694695 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId, label?: string): Promise<boolean> {696 if(typeof label === 'undefined') label = `collection #${collectionId}`;697 const result = await this.helper.executeExtrinsic(698 signer,699 'api.tx.unique.addToAllowList', [collectionId, addressObj],700 true, `Unable to add address to allow list for ${label}`,701 );702703 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');704 }705706 707708709710711712713714715716 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {717 if(typeof label === 'undefined') label = `collection #${collectionId}`;718 const result = await this.helper.executeExtrinsic(719 signer,720 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],721 true, `Unable to remove collection admin for ${label}`,722 );723724 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved', label);725 }726727 728729730731732733734735736737 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions, label?: string): Promise<boolean> {738 if(typeof label === 'undefined') label = `collection #${collectionId}`;739 const result = await this.helper.executeExtrinsic(740 signer,741 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],742 true, `Unable to set collection permissions for ${label}`,743 );744745 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet', label);746 }747748 749750751752753754755756757758 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions, label?: string): Promise<boolean> {759 return await this.setPermissions(signer, collectionId, {nesting: permissions}, label);760 }761762 763764765766767768769770771 async disableNesting(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {772 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}}, label);773 }774775 776777778779780781782783784785 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[], label?: string): Promise<boolean> {786 if(typeof label === 'undefined') label = `collection #${collectionId}`;787 const result = await this.helper.executeExtrinsic(788 signer,789 'api.tx.unique.setCollectionProperties', [collectionId, properties],790 true, `Unable to set collection properties for ${label}`,791 );792793 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet', label);794 }795796 797798799800801802803804805806 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[], label?: string): Promise<boolean> {807 if(typeof label === 'undefined') label = `collection #${collectionId}`;808 const result = await this.helper.executeExtrinsic(809 signer,810 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],811 true, `Unable to delete collection properties for ${label}`,812 );813814 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted', label);815 }816817 818819820821822823824825826827828 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {829 const result = await this.helper.executeExtrinsic(830 signer,831 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],832 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,833 );834835 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);836 }837838 839840841842843844845846847848849850851 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {852 const result = await this.helper.executeExtrinsic(853 signer,854 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],855 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,856 );857 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);858 }859860 861862863864865866867868869870871872 async burnToken(signer: TSigner, collectionId: number, tokenId: number, label?: string, amount=1n): Promise<{873 success: boolean,874 token: number | null875 }> {876 if(typeof label === 'undefined') label = `collection #${collectionId}`;877 const burnResult = await this.helper.executeExtrinsic(878 signer,879 'api.tx.unique.burnItem', [collectionId, tokenId, amount],880 true, `Unable to burn token for ${label}`,881 );882 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);883 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');884 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};885 }886887 888889890891892893894895896897898899 async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, label?: string, amount=1n): Promise<boolean> {900 if(typeof label === 'undefined') label = `collection #${collectionId}`;901 const burnResult = await this.helper.executeExtrinsic(902 signer,903 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],904 true, `Unable to burn token from for ${label}`,905 );906 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);907 return burnedTokens.success && burnedTokens.tokens.length > 0;908 }909910 911912913914915916917918919920921 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=1n) {922 if(typeof label === 'undefined') label = `collection #${collectionId}`;923 const approveResult = await this.helper.executeExtrinsic(924 signer, 925 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],926 true, `Unable to approve token for ${label}`,927 );928929 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved', label);930 }931932 933934935936937938939940941 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {942 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();943 }944945 946947948949950951 async getLastTokenId(collectionId: number): Promise<number> {952 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();953 }954955 956957958959960961962 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {963 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();964 }965}966967class NFTnRFT extends CollectionGroup {968 969970971972973974975976 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {977 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();978 }979980 981982983984985986987988989 async getToken(collectionId: number, tokenId: number, blockHashAt?: string, propertyKeys?: string[]): Promise<{990 properties: IProperty[];991 owner: ICrossAccountId;992 normalizedOwner: ICrossAccountId;993 }| null> {994 let tokenData;995 if(typeof blockHashAt === 'undefined') {996 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);997 }998 else {999 if(typeof propertyKeys === 'undefined') {1000 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1001 if(!collection) return null;1002 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1003 }1004 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1005 }1006 tokenData = tokenData.toHuman();1007 if (tokenData === null || tokenData.owner === null) return null;1008 const owner = {} as any;1009 for (const key of Object.keys(tokenData.owner)) {1010 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];1011 }1012 tokenData.normalizedOwner = crossAccountIdFromLower(owner);1013 return tokenData;1014 }10151016 10171018101910201021102210231024102510261027 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[], label?: string): Promise<boolean> {1028 if(typeof label === 'undefined') label = `collection #${collectionId}`;1029 const result = await this.helper.executeExtrinsic(1030 signer,1031 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1032 true, `Unable to set token property permissions for ${label}`,1033 );10341035 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet', label);1036 }10371038 1039104010411042104310441045104610471048 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[], label?: string): Promise<boolean> {1049 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;1050 const result = await this.helper.executeExtrinsic(1051 signer,1052 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1053 true, `Unable to set token properties for ${label}`,1054 );10551056 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet', label);1057 }10581059 1060106110621063106410651066106710681069 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[], label?: string): Promise<boolean> {1070 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;1071 const result = await this.helper.executeExtrinsic(1072 signer,1073 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1074 true, `Unable to delete token properties for ${label}`,1075 );10761077 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted', label);1078 }10791080 108110821083108410851086108710881089 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT', errorLabel = 'Unable to mint collection'): Promise<UniqueCollectionBase> {1090 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1091 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1092 for (const key of ['name', 'description', 'tokenPrefix']) {1093 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);1094 }1095 const creationResult = await this.helper.executeExtrinsic(1096 signer,1097 'api.tx.unique.createCollectionEx', [collectionOptions],1098 true, errorLabel,1099 );1100 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1101 }11021103 getCollectionObject(collectionId: number): any {1104 return null;1105 }11061107 getTokenObject(collectionId: number, tokenId: number): any {1108 return null;1109 }1110}111111121113class NFTGroup extends NFTnRFT {1114 111511161117111811191120 getCollectionObject(collectionId: number): UniqueNFTCollection {1121 return new UniqueNFTCollection(collectionId, this.helper);1122 }11231124 1125112611271128112911301131 getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1132 return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1133 }11341135 11361137113811391140114111421143 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1144 let owner;1145 if (typeof blockHashAt === 'undefined') {1146 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1147 } else {1148 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1149 }1150 return crossAccountIdFromLower(owner.toJSON());1151 }11521153 1154115511561157115811591160 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1161 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1162 }11631164 1165116611671168116911701171117211731174 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1175 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1176 }11771178 117911801181118211831184118511861187118811891190 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1191 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1192 }11931194 11951196119711981199120012011202 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1203 let owner;1204 if (typeof blockHashAt === 'undefined') {1205 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1206 } else {1207 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1208 }12091210 if (owner === null) return null;12111212 owner = owner.toHuman();12131214 return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1215 }12161217 12181219122012211222122312241225 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1226 let children;1227 if(typeof blockHashAt === 'undefined') {1228 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1229 } else {1230 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1231 }12321233 return children.toJSON().map((x: any) => {1234 return {collectionId: x.collection, tokenId: x.token};1235 });1236 }12371238 123912401241124212431244124512461247 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, label='nest token'): Promise<boolean> {1248 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1249 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1250 if(!result) {1251 throw Error(`Unable to nest token for ${label}`);1252 }1253 return result;1254 }12551256 1257125812591260126112621263126412651266 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId, label='unnest token'): Promise<boolean> {1267 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1268 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1269 if(!result) {1270 throw Error(`Unable to unnest token for ${label}`);1271 }1272 return result;1273 }12741275 1276127712781279128012811282128312841285128612871288 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueNFTCollection> {1289 return await super.mintCollection(signer, collectionOptions, 'NFT', `Unable to mint NFT collection for ${label}`) as UniqueNFTCollection;1290 }12911292 1293129412951296129712981299 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }, label?: string): Promise<UniqueNFTToken> {1300 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1301 const creationResult = await this.helper.executeExtrinsic(1302 signer,1303 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1304 nft: {1305 properties: data.properties,1306 },1307 }],1308 true, `Unable to mint NFT token for ${label}`,1309 );1310 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1311 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1312 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1313 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1314 }13151316 1317131813191320132113221323132413251326132713281329133013311332 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1333 if(typeof label === 'undefined') label = `collection #${collectionId}`;1334 const creationResult = await this.helper.executeExtrinsic(1335 signer,1336 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1337 true, `Unable to mint NFT tokens for ${label}`,1338 );1339 const collection = this.getCollectionObject(collectionId);1340 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1341 }13421343 1344134513461347134813491350135113521353135413551356135713581359136013611362 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1363 if(typeof label === 'undefined') label = `collection #${collectionId}`;1364 const rawTokens = [];1365 for (const token of tokens) {1366 const raw = {NFT: {properties: token.properties}};1367 rawTokens.push(raw);1368 }1369 const creationResult = await this.helper.executeExtrinsic(1370 signer,1371 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1372 true, `Unable to mint NFT tokens for ${label}`,1373 );1374 const collection = this.getCollectionObject(collectionId);1375 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1376 }13771378 137913801381138213831384138513861387 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string): Promise<{ success: boolean; token: number | null; }> {1388 return await super.burnToken(signer, collectionId, tokenId, label, 1n);1389 }13901391 13921393139413951396139713981399140014011402 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {1403 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, 1n);1404 }1405}140614071408class RFTGroup extends NFTnRFT {1409 141014111412141314141415 getCollectionObject(collectionId: number): UniqueRFTCollection {1416 return new UniqueRFTCollection(collectionId, this.helper);1417 }14181419 1420142114221423142414251426 getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1427 return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1428 }14291430 1431143214331434143514361437 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1438 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1439 }14401441 14421443144414451446144714481449 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1450 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1451 }14521453 1454145514561457145814591460146114621463 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=100n): Promise<boolean> {1464 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1465 }14661467 14681469147014711472147314741475147614771478 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n): Promise<boolean> {1479 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1480 }14811482 1483148414851486148714881489149014911492149314941495 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueRFTCollection> {1496 return await super.mintCollection(signer, collectionOptions, 'RFT', `Unable to mint RFT collection for ${label}`) as UniqueRFTCollection;1497 }14981499 15001501150215031504150515061507 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }, label?: string): Promise<UniqueRFTToken> {1508 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1509 const creationResult = await this.helper.executeExtrinsic(1510 signer,1511 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1512 refungible: {1513 pieces: data.pieces,1514 properties: data.properties,1515 },1516 }],1517 true, `Unable to mint RFT token for ${label}`,1518 );1519 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1520 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1521 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1522 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1523 }15241525 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1526 throw Error('Not implemented');1527 if(typeof label === 'undefined') label = `collection #${collectionId}`;1528 const creationResult = await this.helper.executeExtrinsic(1529 signer,1530 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1531 true, `Unable to mint RFT tokens for ${label}`,1532 );1533 const collection = this.getCollectionObject(collectionId);1534 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1535 }15361537 1538153915401541154215431544154515461547 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1548 if(typeof label === 'undefined') label = `collection #${collectionId}`;1549 const rawTokens = [];1550 for (const token of tokens) {1551 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1552 rawTokens.push(raw);1553 }1554 const creationResult = await this.helper.executeExtrinsic(1555 signer,1556 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1557 true, `Unable to mint RFT tokens for ${label}`,1558 );1559 const collection = this.getCollectionObject(collectionId);1560 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1561 }15621563 1564156515661567156815691570157115721573 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string, amount=100n): Promise<{ success: boolean; token: number | null; }> {1574 return await super.burnToken(signer, collectionId, tokenId, label, amount);1575 }15761577 157815791580158115821583158415851586158715881589 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=100n) {1590 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, amount);1591 }15921593 1594159515961597159815991600 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1601 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1602 }16031604 1605160616071608160916101611161216131614 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint, label?: string): Promise<boolean> {1615 if(typeof label === 'undefined') label = `collection #${collectionId}`;1616 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1617 const repartitionResult = await this.helper.executeExtrinsic(1618 signer,1619 'api.tx.unique.repartition', [collectionId, tokenId, amount],1620 true, `Unable to repartition RFT token for ${label}`,1621 );1622 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated', label);1623 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed', label);1624 }1625}162616271628class FTGroup extends CollectionGroup {1629 163016311632163316341635 getCollectionObject(collectionId: number): UniqueFTCollection {1636 return new UniqueFTCollection(collectionId, this.helper);1637 }16381639 16401641164216431644164516461647164816491650165116521653 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0, errorLabel = 'Unable to mint collection'): Promise<UniqueFTCollection> {1654 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1655 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1656 collectionOptions.mode = {fungible: decimalPoints};1657 for (const key of ['name', 'description', 'tokenPrefix']) {1658 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);1659 }1660 const creationResult = await this.helper.executeExtrinsic(1661 signer,1662 'api.tx.unique.createCollectionEx', [collectionOptions],1663 true, errorLabel,1664 );1665 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1666 }16671668 1669167016711672167316741675167616771678 async mintTokens(signer: TSigner, collectionId: number, owner: ICrossAccountId | string, amount: bigint, label?: string): Promise<boolean> {1679 if(typeof label === 'undefined') label = `collection #${collectionId}`;1680 const creationResult = await this.helper.executeExtrinsic(1681 signer,1682 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1683 fungible: {1684 value: amount,1685 },1686 }],1687 true, `Unable to mint fungible tokens for ${label}`,1688 );1689 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1690 }16911692 169316941695169616971698169917001701 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string): Promise<boolean> {1702 if(typeof label === 'undefined') label = `collection #${collectionId}`;1703 const rawTokens = [];1704 for (const token of tokens) {1705 const raw = {Fungible: {Value: token.value}};1706 rawTokens.push(raw);1707 }1708 const creationResult = await this.helper.executeExtrinsic(1709 signer,1710 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1711 true, `Unable to mint RFT tokens for ${label}`,1712 );1713 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1714 }17151716 171717181719172017211722 async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1723 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1724 }17251726 1727172817291730173117321733 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1734 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1735 }17361737 173817391740174117421743174417451746 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount: bigint) {1747 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1748 }17491750 1751175217531754175517561757175817591760 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {1761 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1762 }17631764 176517661767176817691770177117721773 async burnTokens(signer: IKeyringPair, collectionId: number, amount=100n, label?: string): Promise<boolean> {1774 return (await super.burnToken(signer, collectionId, 0, label, amount)).success;1775 }17761777 1778177917801781178217831784178517861787 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=100n, label?: string): Promise<boolean> {1788 return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, label, amount);1789 }17901791 17921793179417951796 async getTotalPieces(collectionId: number): Promise<bigint> {1797 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1798 }17991800 18011802180318041805180618071808180918101811 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {1812 return super.approveToken(signer, collectionId, 0, toAddressObj, label, amount);1813 }18141815 1816181718181819182018211822 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1823 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1824 }1825}182618271828class ChainGroup extends HelperGroup {1829 18301831183218331834 getChainProperties(): IChainProperties {1835 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1836 return {1837 ss58Format: properties.ss58Format.toJSON(),1838 tokenDecimals: properties.tokenDecimals.toJSON(),1839 tokenSymbol: properties.tokenSymbol.toJSON(),1840 };1841 }18421843 18441845184618471848 async getLatestBlockNumber(): Promise<number> {1849 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1850 }18511852 185318541855185618571858 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1859 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1860 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1861 return blockHash;1862 }18631864 186518661867186818691870 async getNonce(address: TSubstrateAccount): Promise<number> {1871 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1872 }1873}187418751876class BalanceGroup extends HelperGroup {1877 18781879188018811882 getOneTokenNominal(): bigint {1883 const chainProperties = this.helper.chain.getChainProperties();1884 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1885 }18861887 188818891890189118921893 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {1894 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();1895 }18961897 189818991900190119021903 async getEthereum(address: TEthereumAccount): Promise<bigint> {1904 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();1905 }19061907 19081909191019111912191319141915 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {1916 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true, `Unable to transfer balance from ${this.helper.getSignerAddress(signer)} to ${address}`);19171918 let transfer = {from: null, to: null, amount: 0n} as any;1919 result.result.events.forEach(({event: {data, method, section}}) => {1920 if ((section === 'balances') && (method === 'Transfer')) {1921 transfer = {1922 from: this.helper.address.normalizeSubstrate(data[0]),1923 to: this.helper.address.normalizeSubstrate(data[1]),1924 amount: BigInt(data[2]),1925 };1926 }1927 });1928 let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;1929 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;1930 isSuccess = isSuccess && BigInt(amount) === transfer.amount;1931 return isSuccess;1932 }1933}193419351936class AddressGroup extends HelperGroup {1937 1938193919401941194219431944 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {1945 return this.helper.util.normalizeSubstrateAddress(address, ss58Format);1946 }19471948 194919501951195219531954 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {1955 const info = this.helper.chain.getChainProperties();1956 return encodeAddress(decodeAddress(address), info.ss58Format);1957 }19581959 1960196119621963196419651966 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {1967 if(!toChainFormat) return evmToAddress(ethAddress);1968 const info = this.helper.chain.getChainProperties();1969 return evmToAddress(ethAddress, info.ss58Format);1970 }19711972 197319741975197619771978 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {1979 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));1980 }1981}198219831984export class UniqueHelper extends ChainHelperBase {1985 chain: ChainGroup;1986 balance: BalanceGroup;1987 address: AddressGroup;1988 collection: CollectionGroup;1989 nft: NFTGroup;1990 rft: RFTGroup;1991 ft: FTGroup;19921993 constructor(logger?: ILogger) {1994 super(logger);1995 this.chain = new ChainGroup(this);1996 this.balance = new BalanceGroup(this);1997 this.address = new AddressGroup(this);1998 this.collection = new CollectionGroup(this);1999 this.nft = new NFTGroup(this);2000 this.rft = new RFTGroup(this);2001 this.ft = new FTGroup(this);2002 } 2003}200420052006class UniqueCollectionBase {2007 helper: UniqueHelper;2008 collectionId: number;20092010 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2011 this.collectionId = collectionId;2012 this.helper = uniqueHelper;2013 }20142015 async getData() {2016 return await this.helper.collection.getData(this.collectionId);2017 }20182019 async getLastTokenId() {2020 return await this.helper.collection.getLastTokenId(this.collectionId);2021 }20222023 async isTokenExists(tokenId: number) {2024 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2025 }20262027 async getAdmins() {2028 return await this.helper.collection.getAdmins(this.collectionId);2029 }20302031 async getAllowList() {2032 return await this.helper.collection.getAllowList(this.collectionId);2033 }20342035 async getEffectiveLimits() {2036 return await this.helper.collection.getEffectiveLimits(this.collectionId);2037 }20382039 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount, label?: string) {2040 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress, label);2041 }20422043 async confirmSponsorship(signer: TSigner, label?: string) {2044 return await this.helper.collection.confirmSponsorship(signer, this.collectionId, label);2045 }20462047 async setLimits(signer: TSigner, limits: ICollectionLimits, label?: string) {2048 return await this.helper.collection.setLimits(signer, this.collectionId, limits, label);2049 }20502051 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount, label?: string) {2052 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress, label);2053 }20542055 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {2056 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj, label);2057 }20582059 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId, label?: string) {2060 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj, label);2061 }20622063 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {2064 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj, label);2065 }20662067 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {2068 return await this.helper.collection.setProperties(signer, this.collectionId, properties, label);2069 }20702071 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {2072 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys, label);2073 }20742075 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2076 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2077 }20782079 async setPermissions(signer: TSigner, permissions: ICollectionPermissions, label?: string) {2080 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions, label);2081 }20822083 async enableNesting(signer: TSigner, permissions: INestingPermissions, label?: string) {2084 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions, label);2085 }20862087 async disableNesting(signer: TSigner, label?: string) {2088 return await this.helper.collection.disableNesting(signer, this.collectionId, label);2089 }20902091 async burn(signer: TSigner, label?: string) {2092 return await this.helper.collection.burn(signer, this.collectionId, label);2093 }2094}209520962097class UniqueNFTCollection extends UniqueCollectionBase {2098 getTokenObject(tokenId: number) {2099 return new UniqueNFTToken(tokenId, this);2100 }21012102 async getTokensByAddress(addressObj: ICrossAccountId) {2103 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2104 }21052106 async getToken(tokenId: number, blockHashAt?: string) {2107 return await this.helper.nft.getToken(this.collectionId, tokenId, blockHashAt);2108 }21092110 async getTokenOwner(tokenId: number, blockHashAt?: string) {2111 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2112 }21132114 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2115 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2116 }21172118 async getTokenChildren(tokenId: number, blockHashAt?: string) {2119 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2120 }21212122 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2123 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2124 }21252126 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2127 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2128 }21292130 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {2131 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label);2132 }21332134 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2135 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2136 }21372138 async mintToken(signer: TSigner, owner: ICrossAccountId, properties?: IProperty[], label?: string) {2139 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties}, label);2140 }21412142 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string) {2143 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens, label);2144 }21452146 async burnToken(signer: TSigner, tokenId: number, label?: string) {2147 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId, label);2148 }21492150 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {2151 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);2152 }21532154 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {2155 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);2156 }21572158 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {2159 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);2160 }21612162 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken, label?: string) {2163 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj, label);2164 }21652166 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {2167 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj, label);2168 }2169}217021712172class UniqueRFTCollection extends UniqueCollectionBase {2173 getTokenObject(tokenId: number) {2174 return new UniqueRFTToken(tokenId, this);2175 }21762177 async getTokensByAddress(addressObj: ICrossAccountId) {2178 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2179 }21802181 async getTop10TokenOwners(tokenId: number) {2182 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2183 }21842185 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2186 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2187 }21882189 async getTokenTotalPieces(tokenId: number) {2190 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2191 }21922193 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=100n) {2194 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2195 }21962197 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {2198 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2199 }22002201 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2202 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label, amount);2203 }22042205 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2206 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2207 }22082209 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint, label?: string) {2210 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount, label);2211 }22122213 async mintToken(signer: TSigner, owner: ICrossAccountId, pieces=100n, properties?: IProperty[], label?: string) {2214 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties}, label);2215 }22162217 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string) {2218 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens, label);2219 }22202221 async burnToken(signer: TSigner, tokenId: number, amount=100n, label?: string) {2222 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, label, amount);2223 }22242225 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {2226 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);2227 }22282229 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {2230 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);2231 }22322233 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {2234 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);2235 }2236}223722382239class UniqueFTCollection extends UniqueCollectionBase {2240 async mint(signer: TSigner, owner: ICrossAccountId, amount: bigint, label?: string) {2241 return await this.helper.ft.mintTokens(signer, this.collectionId, owner, amount, label);2242 }22432244 async mintWithOneOwner(signer: TSigner, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string) {2245 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, owner, tokens, label);2246 }22472248 async getBalance(addressObj: ICrossAccountId) {2249 return await this.helper.ft.getBalance(this.collectionId, addressObj);2250 }22512252 async getTop10Owners() {2253 return await this.helper.ft.getTop10Owners(this.collectionId);2254 }22552256 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount: bigint) {2257 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2258 }22592260 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {2261 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2262 }22632264 async burnTokens(signer: TSigner, amount: bigint, label?: string) {2265 return await this.helper.ft.burnTokens(signer, this.collectionId, amount, label);2266 }22672268 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount: bigint, label?: string) {2269 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount, label);2270 }22712272 async getTotalPieces() {2273 return await this.helper.ft.getTotalPieces(this.collectionId);2274 }22752276 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2277 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount, label);2278 }22792280 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2281 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2282 }2283}228422852286class UniqueTokenBase implements IToken {2287 collection: UniqueNFTCollection | UniqueRFTCollection;2288 collectionId: number;2289 tokenId: number;22902291 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2292 this.collection = collection;2293 this.collectionId = collection.collectionId;2294 this.tokenId = tokenId;2295 }22962297 async getNextSponsored(addressObj: ICrossAccountId) {2298 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2299 }23002301 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {2302 return await this.collection.setTokenProperties(signer, this.tokenId, properties, label);2303 }23042305 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {2306 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys, label);2307 }2308}230923102311class UniqueNFTToken extends UniqueTokenBase {2312 collection: UniqueNFTCollection;23132314 constructor(tokenId: number, collection: UniqueNFTCollection) {2315 super(tokenId, collection);2316 this.collection = collection;2317 }23182319 async getData(blockHashAt?: string) {2320 return await this.collection.getToken(this.tokenId, blockHashAt);2321 }23222323 async getOwner(blockHashAt?: string) {2324 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2325 }23262327 async getTopmostOwner(blockHashAt?: string) {2328 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2329 }23302331 async getChildren(blockHashAt?: string) {2332 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2333 }23342335 async nest(signer: TSigner, toTokenObj: IToken, label?: string) {2336 return await this.collection.nestToken(signer, this.tokenId, toTokenObj, label);2337 }23382339 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {2340 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj, label);2341 }23422343 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2344 return await this.collection.transferToken(signer, this.tokenId, addressObj);2345 }23462347 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2348 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2349 }23502351 async approve(signer: TSigner, toAddressObj: ICrossAccountId, label?: string) {2352 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, label);2353 }23542355 async isApproved(toAddressObj: ICrossAccountId) {2356 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2357 }23582359 async burn(signer: TSigner, label?: string) {2360 return await this.collection.burnToken(signer, this.tokenId, label);2361 }2362}23632364class UniqueRFTToken extends UniqueTokenBase {2365 collection: UniqueRFTCollection;23662367 constructor(tokenId: number, collection: UniqueRFTCollection) {2368 super(tokenId, collection);2369 this.collection = collection;2370 }23712372 async getTop10Owners() {2373 return await this.collection.getTop10TokenOwners(this.tokenId);2374 }23752376 async getBalance(addressObj: ICrossAccountId) {2377 return await this.collection.getTokenBalance(this.tokenId, addressObj);2378 }23792380 async getTotalPieces() {2381 return await this.collection.getTokenTotalPieces(this.tokenId);2382 }23832384 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=100n) {2385 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2386 }23872388 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {2389 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2390 }23912392 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2393 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount, label);2394 }23952396 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2397 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2398 }23992400 async repartition(signer: TSigner, amount: bigint, label?: string) {2401 return await this.collection.repartitionToken(signer, this.tokenId, amount, label);2402 }24032404 async burn(signer: TSigner, amount=100n, label?: string) {2405 return await this.collection.burnToken(signer, this.tokenId, amount, label);2406 }2407}