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 params,392 } as IUniqueHelperLog;393394 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;395 if(events.length > 0) log.events = events;396397 this.chainLog.push(log);398399 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(failureMessage);400 return result;401 }402403 async callRpc(rpc: string, params?: any[]) {404 if(typeof params === 'undefined') params = [];405 if(this.api === null) throw Error('API not initialized');406 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);407408 const startTime = (new Date()).getTime();409 let result;410 let error = null;411 const log = {412 type: this.chainLogType.RPC,413 call: rpc,414 params,415 } as IUniqueHelperLog;416417 try {418 result = await this.constructApiCall(rpc, params);419 }420 catch(e) {421 error = e;422 }423424 const endTime = (new Date()).getTime();425426 log.executedAt = endTime;427 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';428 log.executionTime = endTime - startTime;429430 this.chainLog.push(log);431432 if(error !== null) throw error;433434 return result;435 }436437 getSignerAddress(signer: IKeyringPair | string): string {438 if(typeof signer === 'string') return signer;439 return signer.address;440 }441}442443444class HelperGroup {445 helper: UniqueHelper;446447 constructor(uniqueHelper: UniqueHelper) {448 this.helper = uniqueHelper;449 }450}451452453class CollectionGroup extends HelperGroup {454 455456457458459460461462463 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {464 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();465 }466467 468469470471472 async getTotalCount(): Promise<number> {473 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();474 }475476 477478479480481482483 async getData(collectionId: number): Promise<{484 id: number;485 name: string;486 description: string;487 tokensCount: number;488 admins: ICrossAccountId[];489 normalizedOwner: TSubstrateAccount;490 raw: any491 } | null> {492 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);493 const humanCollection = collection.toHuman(), collectionData = {494 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],495 raw: humanCollection,496 } as any, jsonCollection = collection.toJSON();497 if (humanCollection === null) return null;498 collectionData.raw.limits = jsonCollection.limits;499 collectionData.raw.permissions = jsonCollection.permissions;500 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);501 for (const key of ['name', 'description']) {502 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);503 }504505 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode)) ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId) : 0;506 collectionData.admins = await this.getAdmins(collectionId);507508 return collectionData;509 }510511 512513514515516517518 async getAdmins(collectionId: number): Promise<ICrossAccountId[]> {519 const normalized = [];520 for(const admin of (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman()) {521 if(admin.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(admin.Substrate)});522 else normalized.push(admin);523 }524 return normalized;525 }526527 528529530531532533534 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {535 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();536 }537538 539540541542543544545546547 async burn(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {548 if(typeof label === 'undefined') label = `collection #${collectionId}`;549 const result = await this.helper.executeExtrinsic(550 signer,551 'api.tx.unique.destroyCollection', [collectionId],552 true, `Unable to burn collection for ${label}`,553 );554555 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed', label);556 }557558 559560561562563564565566567568 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount, label?: string): Promise<boolean> {569 if(typeof label === 'undefined') label = `collection #${collectionId}`;570 const result = await this.helper.executeExtrinsic(571 signer,572 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],573 true, `Unable to set collection sponsor for ${label}`,574 );575576 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet', label);577 }578579 580581582583584585586587588 async confirmSponsorship(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {589 if(typeof label === 'undefined') label = `collection #${collectionId}`;590 const result = await this.helper.executeExtrinsic(591 signer,592 'api.tx.unique.confirmSponsorship', [collectionId],593 true, `Unable to confirm collection sponsorship for ${label}`,594 );595596 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed', label);597 }598599 600601602603604605606607608609610611612613614615616617 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits, label?: string): Promise<boolean> {618 if(typeof label === 'undefined') label = `collection #${collectionId}`;619 const result = await this.helper.executeExtrinsic(620 signer,621 'api.tx.unique.setCollectionLimits', [collectionId, limits],622 true, `Unable to set collection limits for ${label}`,623 );624625 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet', label);626 }627628 629630631632633634635636637638 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount, label?: string): Promise<boolean> {639 if(typeof label === 'undefined') label = `collection #${collectionId}`;640 const result = await this.helper.executeExtrinsic(641 signer,642 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],643 true, `Unable to change collection owner for ${label}`,644 );645646 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged', label);647 }648649 650651652653654655656657658659 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {660 if(typeof label === 'undefined') label = `collection #${collectionId}`;661 const result = await this.helper.executeExtrinsic(662 signer,663 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],664 true, `Unable to add collection admin for ${label}`,665 );666667 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded', label);668 }669670 671672673674675676677678679680 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {681 if(typeof label === 'undefined') label = `collection #${collectionId}`;682 const result = await this.helper.executeExtrinsic(683 signer,684 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],685 true, `Unable to remove collection admin for ${label}`,686 );687688 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved', label);689 }690691 692693694695696697698699700701 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions, label?: string): Promise<boolean> {702 if(typeof label === 'undefined') label = `collection #${collectionId}`;703 const result = await this.helper.executeExtrinsic(704 signer,705 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],706 true, `Unable to set collection permissions for ${label}`,707 );708709 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet', label);710 }711712 713714715716717718719720721722 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions, label?: string): Promise<boolean> {723 return await this.setPermissions(signer, collectionId, {nesting: permissions}, label);724 }725726 727728729730731732733734735 async disableNesting(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {736 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}}, label);737 }738739 740741742743744745746747748749 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[], label?: string): Promise<boolean> {750 if(typeof label === 'undefined') label = `collection #${collectionId}`;751 const result = await this.helper.executeExtrinsic(752 signer,753 'api.tx.unique.setCollectionProperties', [collectionId, properties],754 true, `Unable to set collection properties for ${label}`,755 );756757 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet', label);758 }759760 761762763764765766767768769770 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[], label?: string): Promise<boolean> {771 if(typeof label === 'undefined') label = `collection #${collectionId}`;772 const result = await this.helper.executeExtrinsic(773 signer,774 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],775 true, `Unable to delete collection properties for ${label}`,776 );777778 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted', label);779 }780781 782783784785786787788789790791792 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {793 const result = await this.helper.executeExtrinsic(794 signer,795 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],796 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,797 );798799 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);800 }801802 803804805806807808809810811812813814815 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {816 const result = await this.helper.executeExtrinsic(817 signer,818 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],819 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,820 );821 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);822 }823824 825826827828829830831832833834835836 async burnToken(signer: TSigner, collectionId: number, tokenId: number, label?: string, amount=1n): Promise<{837 success: boolean,838 token: number | null839 }> {840 if(typeof label === 'undefined') label = `collection #${collectionId}`;841 const burnResult = await this.helper.executeExtrinsic(842 signer,843 'api.tx.unique.burnItem', [collectionId, tokenId, amount],844 true, `Unable to burn token for ${label}`,845 );846 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);847 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');848 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};849 }850851 852853854855856857858859860861862863 async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, label?: string, amount=1n): Promise<boolean> {864 if(typeof label === 'undefined') label = `collection #${collectionId}`;865 const burnResult = await this.helper.executeExtrinsic(866 signer,867 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],868 true, `Unable to burn token from for ${label}`,869 );870 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);871 return burnedTokens.success && burnedTokens.tokens.length > 0;872 }873874 875876877878879880881882883884885 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=1n) {886 if(typeof label === 'undefined') label = `collection #${collectionId}`;887 const approveResult = await this.helper.executeExtrinsic(888 signer, 889 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],890 true, `Unable to approve token for ${label}`,891 );892893 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved', label);894 }895896 897898899900901902903904905 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {906 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();907 }908909 910911912913914915 async getLastTokenId(collectionId: number): Promise<number> {916 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();917 }918919 920921922923924925926 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {927 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();928 }929}930931class NFTnRFT extends CollectionGroup {932 933934935936937938939940 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {941 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();942 }943944 945946947948949950951952953 async getToken(collectionId: number, tokenId: number, blockHashAt?: string, propertyKeys?: string[]): Promise<{954 properties: IProperty[];955 owner: ICrossAccountId;956 normalizedOwner: ICrossAccountId;957 }| null> {958 let tokenData;959 if(typeof blockHashAt === 'undefined') {960 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);961 }962 else {963 if(typeof propertyKeys === 'undefined') {964 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();965 if(!collection) return null;966 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);967 }968 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);969 }970 tokenData = tokenData.toHuman();971 if (tokenData === null || tokenData.owner === null) return null;972 const owner = {} as any;973 for (const key of Object.keys(tokenData.owner)) {974 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];975 }976 tokenData.normalizedOwner = crossAccountIdFromLower(owner);977 return tokenData;978 }979980 981982983984985986987988989990991 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[], label?: string): Promise<boolean> {992 if(typeof label === 'undefined') label = `collection #${collectionId}`;993 const result = await this.helper.executeExtrinsic(994 signer,995 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],996 true, `Unable to set token property permissions for ${label}`,997 );998999 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet', label);1000 }10011002 1003100410051006100710081009101010111012 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[], label?: string): Promise<boolean> {1013 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;1014 const result = await this.helper.executeExtrinsic(1015 signer,1016 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1017 true, `Unable to set token properties for ${label}`,1018 );10191020 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet', label);1021 }10221023 1024102510261027102810291030103110321033 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[], label?: string): Promise<boolean> {1034 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;1035 const result = await this.helper.executeExtrinsic(1036 signer,1037 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1038 true, `Unable to delete token properties for ${label}`,1039 );10401041 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted', label);1042 }10431044 104510461047104810491050105110521053 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT', errorLabel = 'Unable to mint collection'): Promise<UniqueCollectionBase> {1054 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1055 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1056 for (const key of ['name', 'description', 'tokenPrefix']) {1057 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);1058 }1059 const creationResult = await this.helper.executeExtrinsic(1060 signer,1061 'api.tx.unique.createCollectionEx', [collectionOptions],1062 true, errorLabel,1063 );1064 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1065 }10661067 getCollectionObject(collectionId: number): any {1068 return null;1069 }10701071 getTokenObject(collectionId: number, tokenId: number): any {1072 return null;1073 }1074}107510761077class NFTGroup extends NFTnRFT {1078 107910801081108210831084 getCollectionObject(collectionId: number): UniqueNFTCollection {1085 return new UniqueNFTCollection(collectionId, this.helper);1086 }10871088 1089109010911092109310941095 getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1096 return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1097 }10981099 11001101110211031104110511061107 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1108 let owner;1109 if (typeof blockHashAt === 'undefined') {1110 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1111 } else {1112 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1113 }1114 return crossAccountIdFromLower(owner.toJSON());1115 }11161117 1118111911201121112211231124 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1125 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1126 }11271128 1129113011311132113311341135113611371138 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1139 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1140 }11411142 114311441145114611471148114911501151115211531154 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1155 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1156 }11571158 11591160116111621163116411651166 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1167 let owner;1168 if (typeof blockHashAt === 'undefined') {1169 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1170 } else {1171 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1172 }11731174 if (owner === null) return null;11751176 owner = owner.toHuman();11771178 return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1179 }11801181 11821183118411851186118711881189 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1190 let children;1191 if(typeof blockHashAt === 'undefined') {1192 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1193 } else {1194 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1195 }11961197 return children.toJSON().map((x: any) => {1198 return {collectionId: x.collection, tokenId: x.token};1199 });1200 }12011202 120312041205120612071208120912101211 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, label='nest token'): Promise<boolean> {1212 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1213 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1214 if(!result) {1215 throw Error(`Unable to nest token for ${label}`);1216 }1217 return result;1218 }12191220 1221122212231224122512261227122812291230 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId, label='unnest token'): Promise<boolean> {1231 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1232 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1233 if(!result) {1234 throw Error(`Unable to unnest token for ${label}`);1235 }1236 return result;1237 }12381239 1240124112421243124412451246124712481249125012511252 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueNFTCollection> {1253 return await super.mintCollection(signer, collectionOptions, 'NFT', `Unable to mint NFT collection for ${label}`) as UniqueNFTCollection;1254 }12551256 1257125812591260126112621263 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }, label?: string): Promise<UniqueNFTToken> {1264 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1265 const creationResult = await this.helper.executeExtrinsic(1266 signer,1267 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1268 nft: {1269 properties: data.properties,1270 },1271 }],1272 true, `Unable to mint NFT token for ${label}`,1273 );1274 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1275 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1276 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1277 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1278 }12791280 1281128212831284128512861287128812891290129112921293129412951296 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1297 if(typeof label === 'undefined') label = `collection #${collectionId}`;1298 const creationResult = await this.helper.executeExtrinsic(1299 signer,1300 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1301 true, `Unable to mint NFT tokens for ${label}`,1302 );1303 const collection = this.getCollectionObject(collectionId);1304 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1305 }13061307 1308130913101311131213131314131513161317131813191320132113221323132413251326 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1327 if(typeof label === 'undefined') label = `collection #${collectionId}`;1328 const rawTokens = [];1329 for (const token of tokens) {1330 const raw = {NFT: {properties: token.properties}};1331 rawTokens.push(raw);1332 }1333 const creationResult = await this.helper.executeExtrinsic(1334 signer,1335 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1336 true, `Unable to mint NFT tokens for ${label}`,1337 );1338 const collection = this.getCollectionObject(collectionId);1339 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1340 }13411342 134313441345134613471348134913501351 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string): Promise<{ success: boolean; token: number | null; }> {1352 return await super.burnToken(signer, collectionId, tokenId, label, 1n);1353 }13541355 13561357135813591360136113621363136413651366 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {1367 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, 1n);1368 }1369}137013711372class RFTGroup extends NFTnRFT {1373 137413751376137713781379 getCollectionObject(collectionId: number): UniqueRFTCollection {1380 return new UniqueRFTCollection(collectionId, this.helper);1381 }13821383 1384138513861387138813891390 getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1391 return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1392 }13931394 1395139613971398139914001401 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1402 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1403 }14041405 14061407140814091410141114121413 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1414 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1415 }14161417 1418141914201421142214231424142514261427 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=100n): Promise<boolean> {1428 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1429 }14301431 14321433143414351436143714381439144014411442 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n): Promise<boolean> {1443 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1444 }14451446 1447144814491450145114521453145414551456145714581459 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueRFTCollection> {1460 return await super.mintCollection(signer, collectionOptions, 'RFT', `Unable to mint RFT collection for ${label}`) as UniqueRFTCollection;1461 }14621463 14641465146614671468146914701471 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }, label?: string): Promise<UniqueRFTToken> {1472 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1473 const creationResult = await this.helper.executeExtrinsic(1474 signer,1475 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1476 refungible: {1477 pieces: data.pieces,1478 properties: data.properties,1479 },1480 }],1481 true, `Unable to mint RFT token for ${label}`,1482 );1483 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1484 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1485 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1486 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1487 }14881489 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1490 throw Error('Not implemented');1491 if(typeof label === 'undefined') label = `collection #${collectionId}`;1492 const creationResult = await this.helper.executeExtrinsic(1493 signer,1494 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1495 true, `Unable to mint RFT tokens for ${label}`,1496 );1497 const collection = this.getCollectionObject(collectionId);1498 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1499 }15001501 1502150315041505150615071508150915101511 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1512 if(typeof label === 'undefined') label = `collection #${collectionId}`;1513 const rawTokens = [];1514 for (const token of tokens) {1515 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1516 rawTokens.push(raw);1517 }1518 const creationResult = await this.helper.executeExtrinsic(1519 signer,1520 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1521 true, `Unable to mint RFT tokens for ${label}`,1522 );1523 const collection = this.getCollectionObject(collectionId);1524 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1525 }15261527 1528152915301531153215331534153515361537 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string, amount=100n): Promise<{ success: boolean; token: number | null; }> {1538 return await super.burnToken(signer, collectionId, tokenId, label, amount);1539 }15401541 154215431544154515461547154815491550155115521553 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=100n) {1554 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, amount);1555 }15561557 1558155915601561156215631564 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1565 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1566 }15671568 1569157015711572157315741575157615771578 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint, label?: string): Promise<boolean> {1579 if(typeof label === 'undefined') label = `collection #${collectionId}`;1580 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1581 const repartitionResult = await this.helper.executeExtrinsic(1582 signer,1583 'api.tx.unique.repartition', [collectionId, tokenId, amount],1584 true, `Unable to repartition RFT token for ${label}`,1585 );1586 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated', label);1587 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed', label);1588 }1589}159015911592class FTGroup extends CollectionGroup {1593 159415951596159715981599 getCollectionObject(collectionId: number): UniqueFTCollection {1600 return new UniqueFTCollection(collectionId, this.helper);1601 }16021603 16041605160616071608160916101611161216131614161516161617 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0, errorLabel = 'Unable to mint collection'): Promise<UniqueFTCollection> {1618 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1619 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1620 collectionOptions.mode = {fungible: decimalPoints};1621 for (const key of ['name', 'description', 'tokenPrefix']) {1622 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);1623 }1624 const creationResult = await this.helper.executeExtrinsic(1625 signer,1626 'api.tx.unique.createCollectionEx', [collectionOptions],1627 true, errorLabel,1628 );1629 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1630 }16311632 1633163416351636163716381639164016411642 async mintTokens(signer: TSigner, collectionId: number, owner: ICrossAccountId | string, amount: bigint, label?: string): Promise<boolean> {1643 if(typeof label === 'undefined') label = `collection #${collectionId}`;1644 const creationResult = await this.helper.executeExtrinsic(1645 signer,1646 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1647 fungible: {1648 value: amount,1649 },1650 }],1651 true, `Unable to mint fungible tokens for ${label}`,1652 );1653 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1654 }16551656 165716581659166016611662166316641665 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string): Promise<boolean> {1666 if(typeof label === 'undefined') label = `collection #${collectionId}`;1667 const rawTokens = [];1668 for (const token of tokens) {1669 const raw = {Fungible: {Value: token.value}};1670 rawTokens.push(raw);1671 }1672 const creationResult = await this.helper.executeExtrinsic(1673 signer,1674 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1675 true, `Unable to mint RFT tokens for ${label}`,1676 );1677 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1678 }16791680 168116821683168416851686 async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1687 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1688 }16891690 1691169216931694169516961697 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1698 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1699 }17001701 170217031704170517061707170817091710 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount: bigint) {1711 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1712 }17131714 1715171617171718171917201721172217231724 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {1725 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1726 }17271728 172917301731173217331734173517361737 async burnTokens(signer: IKeyringPair, collectionId: number, amount=100n, label?: string): Promise<boolean> {1738 return (await super.burnToken(signer, collectionId, 0, label, amount)).success;1739 }17401741 1742174317441745174617471748174917501751 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=100n, label?: string): Promise<boolean> {1752 return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, label, amount);1753 }17541755 17561757175817591760 async getTotalPieces(collectionId: number): Promise<bigint> {1761 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1762 }17631764 17651766176717681769177017711772177317741775 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {1776 return super.approveToken(signer, collectionId, 0, toAddressObj, label, amount);1777 }17781779 1780178117821783178417851786 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1787 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1788 }1789}179017911792class ChainGroup extends HelperGroup {1793 17941795179617971798 getChainProperties(): IChainProperties {1799 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1800 return {1801 ss58Format: properties.ss58Format.toJSON(),1802 tokenDecimals: properties.tokenDecimals.toJSON(),1803 tokenSymbol: properties.tokenSymbol.toJSON(),1804 };1805 }18061807 18081809181018111812 async getLatestBlockNumber(): Promise<number> {1813 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1814 }18151816 181718181819182018211822 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1823 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1824 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1825 return blockHash;1826 }18271828 182918301831183218331834 async getNonce(address: TSubstrateAccount): Promise<number> {1835 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1836 }1837}183818391840class BalanceGroup extends HelperGroup {1841 18421843184418451846 getOneTokenNominal(): bigint {1847 const chainProperties = this.helper.chain.getChainProperties();1848 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1849 }18501851 185218531854185518561857 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {1858 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();1859 }18601861 186218631864186518661867 async getEthereum(address: TEthereumAccount): Promise<bigint> {1868 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();1869 }18701871 18721873187418751876187718781879 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {1880 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}`);18811882 let transfer = {from: null, to: null, amount: 0n} as any;1883 result.result.events.forEach(({event: {data, method, section}}) => {1884 if ((section === 'balances') && (method === 'Transfer')) {1885 transfer = {1886 from: this.helper.address.normalizeSubstrate(data[0]),1887 to: this.helper.address.normalizeSubstrate(data[1]),1888 amount: BigInt(data[2]),1889 };1890 }1891 });1892 let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;1893 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;1894 isSuccess = isSuccess && BigInt(amount) === transfer.amount;1895 return isSuccess;1896 }1897}189818991900class AddressGroup extends HelperGroup {1901 1902190319041905190619071908 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {1909 return this.helper.util.normalizeSubstrateAddress(address, ss58Format);1910 }19111912 191319141915191619171918 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {1919 const info = this.helper.chain.getChainProperties();1920 return encodeAddress(decodeAddress(address), info.ss58Format);1921 }19221923 1924192519261927192819291930 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {1931 if(!toChainFormat) return evmToAddress(ethAddress);1932 const info = this.helper.chain.getChainProperties();1933 return evmToAddress(ethAddress, info.ss58Format);1934 }19351936 193719381939194019411942 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {1943 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));1944 }1945}194619471948export class UniqueHelper extends ChainHelperBase {1949 chain: ChainGroup;1950 balance: BalanceGroup;1951 address: AddressGroup;1952 collection: CollectionGroup;1953 nft: NFTGroup;1954 rft: RFTGroup;1955 ft: FTGroup;19561957 constructor(logger?: ILogger) {1958 super(logger);1959 this.chain = new ChainGroup(this);1960 this.balance = new BalanceGroup(this);1961 this.address = new AddressGroup(this);1962 this.collection = new CollectionGroup(this);1963 this.nft = new NFTGroup(this);1964 this.rft = new RFTGroup(this);1965 this.ft = new FTGroup(this);1966 } 1967}196819691970class UniqueCollectionBase {1971 helper: UniqueHelper;1972 collectionId: number;19731974 constructor(collectionId: number, uniqueHelper: UniqueHelper) {1975 this.collectionId = collectionId;1976 this.helper = uniqueHelper;1977 }19781979 async getData() {1980 return await this.helper.collection.getData(this.collectionId);1981 }19821983 async getLastTokenId() {1984 return await this.helper.collection.getLastTokenId(this.collectionId);1985 }19861987 async isTokenExists(tokenId: number) {1988 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);1989 }19901991 async getAdmins() {1992 return await this.helper.collection.getAdmins(this.collectionId);1993 }19941995 async getEffectiveLimits() {1996 return await this.helper.collection.getEffectiveLimits(this.collectionId);1997 }19981999 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount, label?: string) {2000 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress, label);2001 }20022003 async confirmSponsorship(signer: TSigner, label?: string) {2004 return await this.helper.collection.confirmSponsorship(signer, this.collectionId, label);2005 }20062007 async setLimits(signer: TSigner, limits: ICollectionLimits, label?: string) {2008 return await this.helper.collection.setLimits(signer, this.collectionId, limits, label);2009 }20102011 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount, label?: string) {2012 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress, label);2013 }20142015 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {2016 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj, label);2017 }20182019 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {2020 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj, label);2021 }20222023 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {2024 return await this.helper.collection.setProperties(signer, this.collectionId, properties, label);2025 }20262027 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {2028 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys, label);2029 }20302031 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2032 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2033 }20342035 async setPermissions(signer: TSigner, permissions: ICollectionPermissions, label?: string) {2036 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions, label);2037 }20382039 async enableNesting(signer: TSigner, permissions: INestingPermissions, label?: string) {2040 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions, label);2041 }20422043 async disableNesting(signer: TSigner, label?: string) {2044 return await this.helper.collection.disableNesting(signer, this.collectionId, label);2045 }20462047 async burn(signer: TSigner, label?: string) {2048 return await this.helper.collection.burn(signer, this.collectionId, label);2049 }2050}205120522053class UniqueNFTCollection extends UniqueCollectionBase {2054 getTokenObject(tokenId: number) {2055 return new UniqueNFTToken(tokenId, this);2056 }20572058 async getTokensByAddress(addressObj: ICrossAccountId) {2059 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2060 }20612062 async getToken(tokenId: number, blockHashAt?: string) {2063 return await this.helper.nft.getToken(this.collectionId, tokenId, blockHashAt);2064 }20652066 async getTokenOwner(tokenId: number, blockHashAt?: string) {2067 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2068 }20692070 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2071 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2072 }20732074 async getTokenChildren(tokenId: number, blockHashAt?: string) {2075 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2076 }20772078 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2079 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2080 }20812082 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2083 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2084 }20852086 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {2087 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label);2088 }20892090 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2091 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2092 }20932094 async mintToken(signer: TSigner, owner: ICrossAccountId, properties?: IProperty[], label?: string) {2095 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties}, label);2096 }20972098 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string) {2099 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens, label);2100 }21012102 async burnToken(signer: TSigner, tokenId: number, label?: string) {2103 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId, label);2104 }21052106 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {2107 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);2108 }21092110 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {2111 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);2112 }21132114 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {2115 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);2116 }21172118 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken, label?: string) {2119 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj, label);2120 }21212122 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {2123 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj, label);2124 }2125}212621272128class UniqueRFTCollection extends UniqueCollectionBase {2129 getTokenObject(tokenId: number) {2130 return new UniqueRFTToken(tokenId, this);2131 }21322133 async getTokensByAddress(addressObj: ICrossAccountId) {2134 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2135 }21362137 async getTop10TokenOwners(tokenId: number) {2138 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2139 }21402141 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2142 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2143 }21442145 async getTokenTotalPieces(tokenId: number) {2146 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2147 }21482149 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=100n) {2150 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2151 }21522153 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {2154 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2155 }21562157 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2158 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label, amount);2159 }21602161 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2162 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2163 }21642165 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint, label?: string) {2166 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount, label);2167 }21682169 async mintToken(signer: TSigner, owner: ICrossAccountId, pieces=100n, properties?: IProperty[], label?: string) {2170 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties}, label);2171 }21722173 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string) {2174 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens, label);2175 }21762177 async burnToken(signer: TSigner, tokenId: number, amount=100n, label?: string) {2178 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, label, amount);2179 }21802181 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {2182 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);2183 }21842185 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {2186 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);2187 }21882189 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {2190 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);2191 }2192}219321942195class UniqueFTCollection extends UniqueCollectionBase {2196 async mint(signer: TSigner, owner: ICrossAccountId, amount: bigint, label?: string) {2197 return await this.helper.ft.mintTokens(signer, this.collectionId, owner, amount, label);2198 }21992200 async mintWithOneOwner(signer: TSigner, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string) {2201 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, owner, tokens, label);2202 }22032204 async getBalance(addressObj: ICrossAccountId) {2205 return await this.helper.ft.getBalance(this.collectionId, addressObj);2206 }22072208 async getTop10Owners() {2209 return await this.helper.ft.getTop10Owners(this.collectionId);2210 }22112212 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount: bigint) {2213 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2214 }22152216 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {2217 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2218 }22192220 async burnTokens(signer: TSigner, amount: bigint, label?: string) {2221 return await this.helper.ft.burnTokens(signer, this.collectionId, amount, label);2222 }22232224 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount: bigint, label?: string) {2225 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount, label);2226 }22272228 async getTotalPieces() {2229 return await this.helper.ft.getTotalPieces(this.collectionId);2230 }22312232 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2233 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount, label);2234 }22352236 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2237 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2238 }2239}224022412242class UniqueTokenBase implements IToken {2243 collection: UniqueNFTCollection | UniqueRFTCollection;2244 collectionId: number;2245 tokenId: number;22462247 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2248 this.collection = collection;2249 this.collectionId = collection.collectionId;2250 this.tokenId = tokenId;2251 }22522253 async getNextSponsored(addressObj: ICrossAccountId) {2254 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2255 }22562257 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {2258 return await this.collection.setTokenProperties(signer, this.tokenId, properties, label);2259 }22602261 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {2262 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys, label);2263 }2264}226522662267class UniqueNFTToken extends UniqueTokenBase {2268 collection: UniqueNFTCollection;22692270 constructor(tokenId: number, collection: UniqueNFTCollection) {2271 super(tokenId, collection);2272 this.collection = collection;2273 }22742275 async getData(blockHashAt?: string) {2276 return await this.collection.getToken(this.tokenId, blockHashAt);2277 }22782279 async getOwner(blockHashAt?: string) {2280 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2281 }22822283 async getTopmostOwner(blockHashAt?: string) {2284 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2285 }22862287 async getChildren(blockHashAt?: string) {2288 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2289 }22902291 async nest(signer: TSigner, toTokenObj: IToken, label?: string) {2292 return await this.collection.nestToken(signer, this.tokenId, toTokenObj, label);2293 }22942295 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {2296 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj, label);2297 }22982299 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2300 return await this.collection.transferToken(signer, this.tokenId, addressObj);2301 }23022303 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2304 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2305 }23062307 async approve(signer: TSigner, toAddressObj: ICrossAccountId, label?: string) {2308 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, label);2309 }23102311 async isApproved(toAddressObj: ICrossAccountId) {2312 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2313 }23142315 async burn(signer: TSigner, label?: string) {2316 return await this.collection.burnToken(signer, this.tokenId, label);2317 }2318}23192320class UniqueRFTToken extends UniqueTokenBase {2321 collection: UniqueRFTCollection;23222323 constructor(tokenId: number, collection: UniqueRFTCollection) {2324 super(tokenId, collection);2325 this.collection = collection;2326 }23272328 async getTop10Owners() {2329 return await this.collection.getTop10TokenOwners(this.tokenId);2330 }23312332 async getBalance(addressObj: ICrossAccountId) {2333 return await this.collection.getTokenBalance(this.tokenId, addressObj);2334 }23352336 async getTotalPieces() {2337 return await this.collection.getTokenTotalPieces(this.tokenId);2338 }23392340 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=100n) {2341 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2342 }23432344 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {2345 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2346 }23472348 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2349 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount, label);2350 }23512352 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2353 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2354 }23552356 async repartition(signer: TSigner, amount: bigint, label?: string) {2357 return await this.collection.repartitionToken(signer, this.tokenId, amount, label);2358 }23592360 async burn(signer: TSigner, amount=100n, label?: string) {2361 return await this.collection.burnToken(signer, this.tokenId, amount, label);2362 }2363}