12345678import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IChainEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, ISubstrateBalance, 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) {95 if (creationResult.status !== this.transactionStatus.SUCCESS) {96 throw Error('Unable to create collection!');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 was found!');108 }109110 return collectionId;111 }112113 static extractTokensFromCreationResult(creationResult: ITransactionResult) {114 if (creationResult.status !== this.transactionStatus.SUCCESS) {115 throw Error('Unable to create tokens!');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) {134 if (burnResult.status !== this.transactionStatus.SUCCESS) {135 throw Error('Unable to burn tokens!');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) {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 was found!`);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 321 return new Promise(async (resolve, reject) => {322 try {323 const unsub = await sign((result: any) => {324 const status = this.getTransactionStatus(result);325326 if (status === this.transactionStatus.SUCCESS) {327 this.logger.log(`${label} successful`);328 unsub();329 resolve({result, status});330 } else if (status === this.transactionStatus.FAIL) {331 let moduleError = null;332333 if (result.hasOwnProperty('dispatchError')) {334 const dispatchError = result['dispatchError'];335336 if (dispatchError && dispatchError.isModule) {337 const modErr = dispatchError.asModule;338 const errorMeta = dispatchError.registry.findMetaError(modErr);339340 moduleError = `${errorMeta.section}.${errorMeta.name}`;341 }342 else {343 this.logger.log(result, this.logger.level.ERROR);344 }345 }346347 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);348 unsub();349 reject({status, moduleError, result});350 }351 });352 } catch (e) {353 this.logger.log(e, this.logger.level.ERROR);354 reject(e);355 }356 });357 }358359 constructApiCall(apiCall: string, params: any[]) {360 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);361 let call = this.api as any;362 for(const part of apiCall.slice(4).split('.')) {363 call = call[part];364 }365 return call(...params);366 }367368 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=false) {369 if(this.api === null) throw Error('API not initialized');370 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);371372 const startTime = (new Date()).getTime();373 let result: ITransactionResult;374 let events = [];375 try {376 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), extrinsic) as ITransactionResult;377 events = result.result.events.map((x: any) => x.toHuman());378 }379 catch(e) {380 if(!(e as object).hasOwnProperty('status')) throw e;381 result = e as ITransactionResult;382 }383384 const endTime = (new Date()).getTime();385386 const log = {387 executedAt: endTime,388 executionTime: endTime - startTime,389 type: this.chainLogType.EXTRINSIC,390 status: result.status,391 call: extrinsic,392 signer: this.getSignerAddress(sender),393 params,394 } as IUniqueHelperLog;395396 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;397 if(events.length > 0) log.events = events;398399 this.chainLog.push(log);400401 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);402 return result;403 }404405 async callRpc(rpc: string, params?: any[]) {406 if(typeof params === 'undefined') params = [];407 if(this.api === null) throw Error('API not initialized');408 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);409410 const startTime = (new Date()).getTime();411 let result;412 let error = null;413 const log = {414 type: this.chainLogType.RPC,415 call: rpc,416 params,417 } as IUniqueHelperLog;418419 try {420 result = await this.constructApiCall(rpc, params);421 }422 catch(e) {423 error = e;424 }425426 const endTime = (new Date()).getTime();427428 log.executedAt = endTime;429 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';430 log.executionTime = endTime - startTime;431432 this.chainLog.push(log);433434 if(error !== null) throw error;435436 return result;437 }438439 getSignerAddress(signer: IKeyringPair | string): string {440 if(typeof signer === 'string') return signer;441 return signer.address;442 }443}444445446class HelperGroup {447 helper: UniqueHelper;448449 constructor(uniqueHelper: UniqueHelper) {450 this.helper = uniqueHelper;451 }452}453454455class CollectionGroup extends HelperGroup {456 457458459460461462463464465 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {466 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();467 }468469 470471472473474 async getTotalCount(): Promise<number> {475 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();476 }477478 479480481482483484485 async getData(collectionId: number): Promise<{486 id: number;487 name: string;488 description: string;489 tokensCount: number;490 admins: ICrossAccountId[];491 normalizedOwner: TSubstrateAccount;492 raw: any493 } | null> {494 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);495 const humanCollection = collection.toHuman(), collectionData = {496 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],497 raw: humanCollection,498 } as any, jsonCollection = collection.toJSON();499 if (humanCollection === null) return null;500 collectionData.raw.limits = jsonCollection.limits;501 collectionData.raw.permissions = jsonCollection.permissions;502 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);503 for (const key of ['name', 'description']) {504 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);505 }506507 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode)) ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId) : 0;508 collectionData.admins = await this.getAdmins(collectionId);509510 return collectionData;511 }512513 514515516517518519520 async getAdmins(collectionId: number): Promise<ICrossAccountId[]> {521 const normalized = [];522 for(const admin of (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman()) {523 if(admin.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(admin.Substrate)});524 else normalized.push(admin);525 }526 return normalized;527 }528529 530531532533534535 async getAllowList(collectionId: number): Promise<ICrossAccountId[]> {536 const normalized = [];537 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();538 for (const address of allowListed) {539 if (address.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(address.Substrate)});540 else normalized.push(address);541 }542 return normalized;543 }544545 546547548549550551552 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {553 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();554 }555556 557558559560561562563564 async burn(signer: TSigner, collectionId: number): Promise<boolean> {565 const result = await this.helper.executeExtrinsic(566 signer,567 'api.tx.unique.destroyCollection', [collectionId],568 true,569 );570571 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');572 }573574 575576577578579580581582583 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {584 const result = await this.helper.executeExtrinsic(585 signer,586 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],587 true,588 );589590 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');591 }592593 594595596597598599600601 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {602 const result = await this.helper.executeExtrinsic(603 signer,604 'api.tx.unique.confirmSponsorship', [collectionId],605 true,606 );607608 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');609 }610611 612613614615616617618619620621622623624625626627628 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {629 const result = await this.helper.executeExtrinsic(630 signer,631 'api.tx.unique.setCollectionLimits', [collectionId, limits],632 true,633 );634635 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');636 }637638 639640641642643644645646647 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {648 const result = await this.helper.executeExtrinsic(649 signer,650 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],651 true,652 );653654 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');655 }656657 658659660661662663664665666 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {667 const result = await this.helper.executeExtrinsic(668 signer,669 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],670 true,671 );672673 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');674 }675676 677678679680681682683684685 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {686 const result = await this.helper.executeExtrinsic(687 signer,688 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],689 true,690 );691692 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');693 }694695 696697698699700701702 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {703 const result = await this.helper.executeExtrinsic(704 signer,705 'api.tx.unique.addToAllowList', [collectionId, addressObj],706 true,707 );708709 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');710 }711712 713714715716717718719720 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {721 const result = await this.helper.executeExtrinsic(722 signer,723 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],724 true,725 );726727 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');728 }729730 731732733734735736737738739 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {740 const result = await this.helper.executeExtrinsic(741 signer,742 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],743 true,744 );745746 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');747 }748749 750751752753754755756757758 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {759 return await this.setPermissions(signer, collectionId, {nesting: permissions});760 }761762 763764765766767768769770 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {771 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});772 }773774 775776777778779780781782783 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {784 const result = await this.helper.executeExtrinsic(785 signer,786 'api.tx.unique.setCollectionProperties', [collectionId, properties],787 true,788 );789790 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');791 }792793 794795796797798799800801802 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {803 const result = await this.helper.executeExtrinsic(804 signer,805 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],806 true,807 );808809 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');810 }811812 813814815816817818819820821822823 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {824 const result = await this.helper.executeExtrinsic(825 signer,826 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],827 true, 828 );829830 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);831 }832833 834835836837838839840841842843844845846 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {847 const result = await this.helper.executeExtrinsic(848 signer,849 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],850 true, 851 );852 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);853 }854855 856857858859860861862863864865866 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<{867 success: boolean,868 token: number | null869 }> {870 const burnResult = await this.helper.executeExtrinsic(871 signer,872 'api.tx.unique.burnItem', [collectionId, tokenId, amount],873 true, 874 );875 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);876 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');877 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};878 }879880 881882883884885886887888889890891 async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, amount=1n): Promise<boolean> {892 const burnResult = await this.helper.executeExtrinsic(893 signer,894 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],895 true, 896 );897 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);898 return burnedTokens.success && burnedTokens.tokens.length > 0;899 }900901 902903904905906907908909910911 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {912 const approveResult = await this.helper.executeExtrinsic(913 signer, 914 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],915 true, 916 );917918 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');919 }920921 922923924925926927928929930931 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {932 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();933 }934935 936937938939940941942 async getLastTokenId(collectionId: number): Promise<number> {943 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();944 }945946 947948949950951952953954 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {955 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();956 }957}958959class NFTnRFT extends CollectionGroup {960 961962963964965966967968 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {969 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();970 }971972 973974975976977978979980981982 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{983 properties: IProperty[];984 owner: ICrossAccountId;985 normalizedOwner: ICrossAccountId;986 }| null> {987 let tokenData;988 if(typeof blockHashAt === 'undefined') {989 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);990 }991 else {992 if(propertyKeys.length == 0) {993 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();994 if(!collection) return null;995 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);996 }997 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);998 }999 tokenData = tokenData.toHuman();1000 if (tokenData === null || tokenData.owner === null) return null;1001 const owner = {} as any;1002 for (const key of Object.keys(tokenData.owner)) {1003 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];1004 }1005 tokenData.normalizedOwner = crossAccountIdFromLower(owner);1006 return tokenData;1007 }10081009 10101011101210131014101510161017101810191020 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1021 const result = await this.helper.executeExtrinsic(1022 signer,1023 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1024 true,1025 );10261027 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1028 }10291030 1031103210331034103510361037103810391040 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1041 const result = await this.helper.executeExtrinsic(1042 signer,1043 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1044 true,1045 );10461047 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1048 }10491050 105110521053105410551056105710581059 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1060 const result = await this.helper.executeExtrinsic(1061 signer,1062 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1063 true,1064 );10651066 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1067 }10681069 107010711072107310741075107610771078 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueCollectionBase> {1079 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1080 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1081 for (const key of ['name', 'description', 'tokenPrefix']) {1082 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);1083 }1084 const creationResult = await this.helper.executeExtrinsic(1085 signer,1086 'api.tx.unique.createCollectionEx', [collectionOptions],1087 true, 1088 );1089 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1090 }10911092 getCollectionObject(_collectionId: number): any {1093 return null;1094 }10951096 getTokenObject(_collectionId: number, _tokenId: number): any {1097 return null;1098 }1099}110011011102class NFTGroup extends NFTnRFT {1103 110411051106110711081109 getCollectionObject(collectionId: number): UniqueNFTCollection {1110 return new UniqueNFTCollection(collectionId, this.helper);1111 }11121113 1114111511161117111811191120 getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1121 return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1122 }11231124 11251126112711281129113011311132 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1133 let owner;1134 if (typeof blockHashAt === 'undefined') {1135 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1136 } else {1137 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1138 }1139 return crossAccountIdFromLower(owner.toJSON());1140 }11411142 1143114411451146114711481149 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1150 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1151 }11521153 1154115511561157115811591160116111621163 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1164 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1165 }11661167 116811691170117111721173117411751176117711781179 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1180 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1181 }11821183 11841185118611871188118911901191 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1192 let owner;1193 if (typeof blockHashAt === 'undefined') {1194 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1195 } else {1196 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1197 }11981199 if (owner === null) return null;12001201 owner = owner.toHuman();12021203 return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1204 }12051206 12071208120912101211121212131214 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1215 let children;1216 if(typeof blockHashAt === 'undefined') {1217 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1218 } else {1219 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1220 }12211222 return children.toJSON().map((x: any) => {1223 return {collectionId: x.collection, tokenId: x.token};1224 });1225 }12261227 12281229123012311232123312341235 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1236 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1237 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1238 if(!result) {1239 throw Error('Unable to nest token!');1240 }1241 return result;1242 }12431244 124512461247124812491250125112521253 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1254 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1255 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1256 if(!result) {1257 throw Error('Unable to unnest token!');1258 }1259 return result;1260 }12611262 126312641265126612671268126912701271127212731274 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueNFTCollection> {1275 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1276 }12771278 127912801281128212831284 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFTToken> {1285 const creationResult = await this.helper.executeExtrinsic(1286 signer,1287 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1288 nft: {1289 properties: data.properties,1290 },1291 }],1292 true,1293 );1294 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1295 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1296 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1297 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1298 }12991300 130113021303130413051306130713081309131013111312131313141315 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1316 const creationResult = await this.helper.executeExtrinsic(1317 signer,1318 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1319 true,1320 );1321 const collection = this.getCollectionObject(collectionId);1322 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1323 }13241325 132613271328132913301331133213331334133513361337133813391340134113421343 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1344 const rawTokens = [];1345 for (const token of tokens) {1346 const raw = {NFT: {properties: token.properties}};1347 rawTokens.push(raw);1348 }1349 const creationResult = await this.helper.executeExtrinsic(1350 signer,1351 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1352 true,1353 );1354 const collection = this.getCollectionObject(collectionId);1355 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1356 }13571358 13591360136113621363136413651366 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number): Promise<{ success: boolean; token: number | null; }> {1367 return await super.burnToken(signer, collectionId, tokenId, 1n);1368 }13691370 1371137213731374137513761377137813791380 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1381 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1382 }1383}138413851386class RFTGroup extends NFTnRFT {1387 138813891390139113921393 getCollectionObject(collectionId: number): UniqueRFTCollection {1394 return new UniqueRFTCollection(collectionId, this.helper);1395 }13961397 1398139914001401140214031404 getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1405 return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1406 }14071408 1409141014111412141314141415 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1416 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1417 }14181419 14201421142214231424142514261427 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1428 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1429 }14301431 1432143314341435143614371438143914401441 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1442 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1443 }14441445 14461447144814491450145114521453145414551456 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1457 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1458 }14591460 146114621463146414651466146714681469147014711472 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueRFTCollection> {1473 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1474 }14751476 1477147814791480148114821483 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFTToken> {1484 const creationResult = await this.helper.executeExtrinsic(1485 signer,1486 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1487 refungible: {1488 pieces: data.pieces,1489 properties: data.properties,1490 },1491 }],1492 true,1493 );1494 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1495 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1496 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1497 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1498 }14991500 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1501 throw Error('Not implemented');1502 const creationResult = await this.helper.executeExtrinsic(1503 signer,1504 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1505 true, 1506 );1507 const collection = this.getCollectionObject(collectionId);1508 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1509 }15101511 151215131514151515161517151815191520 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1521 const rawTokens = [];1522 for (const token of tokens) {1523 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1524 rawTokens.push(raw);1525 }1526 const creationResult = await this.helper.executeExtrinsic(1527 signer,1528 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1529 true,1530 );1531 const collection = this.getCollectionObject(collectionId);1532 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1533 }15341535 153615371538153915401541154215431544 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<{ success: boolean; token: number | null; }> {1545 return await super.burnToken(signer, collectionId, tokenId, amount);1546 }15471548 15491550155115521553155415551556155715581559 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1560 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1561 }15621563 1564156515661567156815691570 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1571 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1572 }15731574 157515761577157815791580158115821583 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1584 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1585 const repartitionResult = await this.helper.executeExtrinsic(1586 signer,1587 'api.tx.unique.repartition', [collectionId, tokenId, amount],1588 true,1589 );1590 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1591 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1592 }1593}159415951596class FTGroup extends CollectionGroup {1597 159815991600160116021603 getCollectionObject(collectionId: number): UniqueFTCollection {1604 return new UniqueFTCollection(collectionId, this.helper);1605 }16061607 1608160916101611161216131614161516161617161816191620 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0): Promise<UniqueFTCollection> {1621 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1622 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1623 collectionOptions.mode = {fungible: decimalPoints};1624 for (const key of ['name', 'description', 'tokenPrefix']) {1625 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);1626 }1627 const creationResult = await this.helper.executeExtrinsic(1628 signer,1629 'api.tx.unique.createCollectionEx', [collectionOptions],1630 true,1631 );1632 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1633 }16341635 163616371638163916401641164216431644 async mintTokens(signer: TSigner, collectionId: number, owner: ICrossAccountId | string, amount: bigint): Promise<boolean> {1645 const creationResult = await this.helper.executeExtrinsic(1646 signer,1647 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1648 fungible: {1649 value: amount,1650 },1651 }],1652 true, 1653 );1654 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1655 }16561657 16581659166016611662166316641665 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {value: bigint}[]): Promise<boolean> {1666 const rawTokens = [];1667 for (const token of tokens) {1668 const raw = {Fungible: {Value: token.value}};1669 rawTokens.push(raw);1670 }1671 const creationResult = await this.helper.executeExtrinsic(1672 signer,1673 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1674 true,1675 );1676 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1677 }16781679 168016811682168316841685 async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1686 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1687 }16881689 1690169116921693169416951696 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1697 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1698 }16991700 170117021703170417051706170717081709 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1710 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1711 }17121713 1714171517161717171817191720172117221723 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1724 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1725 }17261727 17281729173017311732173317341735 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1736 return (await super.burnToken(signer, collectionId, 0, amount)).success;1737 }17381739 174017411742174317441745174617471748 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1749 return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, amount);1750 }17511752 17531754175517561757 async getTotalPieces(collectionId: number): Promise<bigint> {1758 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1759 }17601761 1762176317641765176617671768176917701771 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1772 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1773 }17741775 1776177717781779178017811782 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1783 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1784 }1785}178617871788class ChainGroup extends HelperGroup {1789 17901791179217931794 getChainProperties(): IChainProperties {1795 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1796 return {1797 ss58Format: properties.ss58Format.toJSON(),1798 tokenDecimals: properties.tokenDecimals.toJSON(),1799 tokenSymbol: properties.tokenSymbol.toJSON(),1800 };1801 }18021803 18041805180618071808 async getLatestBlockNumber(): Promise<number> {1809 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1810 }18111812 181318141815181618171818 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1819 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1820 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1821 return blockHash;1822 }18231824 1825 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {1826 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);1827 if (!blockHash) return null;1828 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;1829 }18301831 183218331834183518361837 async getNonce(address: TSubstrateAccount): Promise<number> {1838 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1839 }1840}184118421843class BalanceGroup extends HelperGroup {1844 18451846184718481849 getOneTokenNominal(): bigint {1850 const chainProperties = this.helper.chain.getChainProperties();1851 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1852 }18531854 185518561857185818591860 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {1861 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();1862 }18631864 18651866186718681869 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {1870 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;1871 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};1872 }18731874 187518761877187818791880 async getEthereum(address: TEthereumAccount): Promise<bigint> {1881 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();1882 }18831884 18851886188718881889189018911892 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {1893 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);18941895 let transfer = {from: null, to: null, amount: 0n} as any;1896 result.result.events.forEach(({event: {data, method, section}}) => {1897 if ((section === 'balances') && (method === 'Transfer')) {1898 transfer = {1899 from: this.helper.address.normalizeSubstrate(data[0]),1900 to: this.helper.address.normalizeSubstrate(data[1]),1901 amount: BigInt(data[2]),1902 };1903 }1904 });1905 let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;1906 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;1907 isSuccess = isSuccess && BigInt(amount) === transfer.amount;1908 return isSuccess;1909 }1910}191119121913class AddressGroup extends HelperGroup {1914 1915191619171918191919201921 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {1922 return this.helper.util.normalizeSubstrateAddress(address, ss58Format);1923 }19241925 192619271928192919301931 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {1932 const info = this.helper.chain.getChainProperties();1933 return encodeAddress(decodeAddress(address), info.ss58Format);1934 }19351936 1937193819391940194119421943 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {1944 if(!toChainFormat) return evmToAddress(ethAddress);1945 const info = this.helper.chain.getChainProperties();1946 return evmToAddress(ethAddress, info.ss58Format);1947 }19481949 195019511952195319541955 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {1956 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));1957 }1958}19591960class StakingGroup extends HelperGroup {1961 1962196319641965196619671968 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {1969 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;1970 const stakeResult = await this.helper.executeExtrinsic(1971 signer, 'api.tx.appPromotion.stake',1972 [amountToStake], true,1973 );1974 1975 return true;1976 }19771978 1979198019811982198319841985 async unstake(signer: TSigner, label?: string): Promise<boolean> {1986 if(typeof label === 'undefined') label = `${signer.address}`;1987 const unstakeResult = await this.helper.executeExtrinsic(1988 signer, 'api.tx.appPromotion.unstake', 1989 [], true,1990 );1991 1992 return true;1993 }19941995 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {1996 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();1997 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();1998 }19992000 async getTotalStakingLocked(address: ICrossAccountId): Promise<bigint> {2001 return (await this.helper.callRpc('api.rpc.appPromotion.totalStakingLocked', [address])).toBigInt();2002 }20032004 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<bigint[][]> {2005 return (await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);2006 }20072008 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2009 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2010 }2011 2012 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<bigint[][]> {2013 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);2014 }2015}20162017export class UniqueHelper extends ChainHelperBase {2018 chain: ChainGroup;2019 balance: BalanceGroup;2020 address: AddressGroup;2021 collection: CollectionGroup;2022 nft: NFTGroup;2023 rft: RFTGroup;2024 ft: FTGroup;2025 staking: StakingGroup;20262027 constructor(logger?: ILogger) {2028 super(logger);2029 this.chain = new ChainGroup(this);2030 this.balance = new BalanceGroup(this);2031 this.address = new AddressGroup(this);2032 this.collection = new CollectionGroup(this);2033 this.nft = new NFTGroup(this);2034 this.rft = new RFTGroup(this);2035 this.ft = new FTGroup(this);2036 this.staking = new StakingGroup(this);2037 } 2038}203920402041class UniqueCollectionBase {2042 helper: UniqueHelper;2043 collectionId: number;20442045 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2046 this.collectionId = collectionId;2047 this.helper = uniqueHelper;2048 }20492050 async getData() {2051 return await this.helper.collection.getData(this.collectionId);2052 }20532054 async getLastTokenId() {2055 return await this.helper.collection.getLastTokenId(this.collectionId);2056 }20572058 async isTokenExists(tokenId: number) {2059 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2060 }20612062 async getAdmins() {2063 return await this.helper.collection.getAdmins(this.collectionId);2064 }20652066 async getAllowList() {2067 return await this.helper.collection.getAllowList(this.collectionId);2068 }20692070 async getEffectiveLimits() {2071 return await this.helper.collection.getEffectiveLimits(this.collectionId);2072 }20732074 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2075 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2076 }20772078 async confirmSponsorship(signer: TSigner) {2079 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2080 }20812082 async setLimits(signer: TSigner, limits: ICollectionLimits) {2083 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2084 }20852086 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2087 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2088 }20892090 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2091 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2092 }20932094 async enableAllowList(signer: TSigner, value = true) {2095 return await this.setPermissions(signer, value ? {access: 'AllowList', mintMode: true} : {access: 'Normal'});2096 }20972098 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2099 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2100 }21012102 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2103 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2104 }21052106 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2107 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2108 }21092110 async setProperties(signer: TSigner, properties: IProperty[]) {2111 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2112 }21132114 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2115 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2116 }21172118 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2119 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2120 }21212122 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2123 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2124 }21252126 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2127 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2128 }21292130 async disableNesting(signer: TSigner) {2131 return await this.helper.collection.disableNesting(signer, this.collectionId);2132 }21332134 async burn(signer: TSigner) {2135 return await this.helper.collection.burn(signer, this.collectionId);2136 }2137}213821392140class UniqueNFTCollection extends UniqueCollectionBase {2141 getTokenObject(tokenId: number) {2142 return new UniqueNFTToken(tokenId, this);2143 }21442145 async getTokensByAddress(addressObj: ICrossAccountId) {2146 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2147 }21482149 async getToken(tokenId: number, blockHashAt?: string) {2150 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2151 }21522153 async getTokenOwner(tokenId: number, blockHashAt?: string) {2154 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2155 }21562157 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2158 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2159 }21602161 async getTokenChildren(tokenId: number, blockHashAt?: string) {2162 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2163 }21642165 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2166 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2167 }21682169 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2170 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2171 }21722173 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2174 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2175 }21762177 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2178 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2179 }21802181 async mintToken(signer: TSigner, owner: ICrossAccountId, properties?: IProperty[]) {2182 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2183 }21842185 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2186 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2187 }21882189 async burnToken(signer: TSigner, tokenId: number) {2190 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2191 }21922193 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2194 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2195 }21962197 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2198 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2199 }22002201 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2202 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2203 }22042205 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2206 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2207 }22082209 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2210 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2211 }2212}221322142215class UniqueRFTCollection extends UniqueCollectionBase {2216 getTokenObject(tokenId: number) {2217 return new UniqueRFTToken(tokenId, this);2218 }22192220 async getTokensByAddress(addressObj: ICrossAccountId) {2221 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2222 }22232224 async getTop10TokenOwners(tokenId: number) {2225 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2226 }22272228 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2229 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2230 }22312232 async getTokenTotalPieces(tokenId: number) {2233 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2234 }22352236 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2237 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2238 }22392240 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2241 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2242 }22432244 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2245 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2246 }22472248 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2249 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2250 }22512252 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2253 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2254 }22552256 async mintToken(signer: TSigner, owner: ICrossAccountId, pieces=100n, properties?: IProperty[]) {2257 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2258 }22592260 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]) {2261 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2262 }22632264 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2265 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2266 }22672268 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2269 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2270 }22712272 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2273 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2274 }22752276 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2277 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2278 }2279}228022812282class UniqueFTCollection extends UniqueCollectionBase {2283 async mint(signer: TSigner, owner: ICrossAccountId, amount: bigint) {2284 return await this.helper.ft.mintTokens(signer, this.collectionId, owner, amount);2285 }22862287 async mintWithOneOwner(signer: TSigner, owner: ICrossAccountId, tokens: {value: bigint}[]) {2288 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, owner, tokens);2289 }22902291 async getBalance(addressObj: ICrossAccountId) {2292 return await this.helper.ft.getBalance(this.collectionId, addressObj);2293 }22942295 async getTop10Owners() {2296 return await this.helper.ft.getTop10Owners(this.collectionId);2297 }22982299 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2300 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2301 }23022303 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2304 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2305 }23062307 async burnTokens(signer: TSigner, amount=1n) {2308 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2309 }23102311 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2312 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2313 }23142315 async getTotalPieces() {2316 return await this.helper.ft.getTotalPieces(this.collectionId);2317 }23182319 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2320 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2321 }23222323 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2324 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2325 }2326}232723282329class UniqueTokenBase implements IToken {2330 collection: UniqueNFTCollection | UniqueRFTCollection;2331 collectionId: number;2332 tokenId: number;23332334 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2335 this.collection = collection;2336 this.collectionId = collection.collectionId;2337 this.tokenId = tokenId;2338 }23392340 async getNextSponsored(addressObj: ICrossAccountId) {2341 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2342 }23432344 async setProperties(signer: TSigner, properties: IProperty[]) {2345 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2346 }23472348 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2349 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2350 }2351}235223532354class UniqueNFTToken extends UniqueTokenBase {2355 collection: UniqueNFTCollection;23562357 constructor(tokenId: number, collection: UniqueNFTCollection) {2358 super(tokenId, collection);2359 this.collection = collection;2360 }23612362 async getData(blockHashAt?: string) {2363 return await this.collection.getToken(this.tokenId, blockHashAt);2364 }23652366 async getOwner(blockHashAt?: string) {2367 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2368 }23692370 async getTopmostOwner(blockHashAt?: string) {2371 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2372 }23732374 async getChildren(blockHashAt?: string) {2375 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2376 }23772378 async nest(signer: TSigner, toTokenObj: IToken) {2379 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2380 }23812382 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2383 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2384 }23852386 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2387 return await this.collection.transferToken(signer, this.tokenId, addressObj);2388 }23892390 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2391 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2392 }23932394 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2395 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2396 }23972398 async isApproved(toAddressObj: ICrossAccountId) {2399 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2400 }24012402 async burn(signer: TSigner) {2403 return await this.collection.burnToken(signer, this.tokenId);2404 }2405}24062407class UniqueRFTToken extends UniqueTokenBase {2408 collection: UniqueRFTCollection;24092410 constructor(tokenId: number, collection: UniqueRFTCollection) {2411 super(tokenId, collection);2412 this.collection = collection;2413 }24142415 async getTop10Owners() {2416 return await this.collection.getTop10TokenOwners(this.tokenId);2417 }24182419 async getBalance(addressObj: ICrossAccountId) {2420 return await this.collection.getTokenBalance(this.tokenId, addressObj);2421 }24222423 async getTotalPieces() {2424 return await this.collection.getTokenTotalPieces(this.tokenId);2425 }24262427 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2428 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2429 }24302431 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2432 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2433 }24342435 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2436 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2437 }24382439 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2440 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2441 }24422443 async repartition(signer: TSigner, amount: bigint) {2444 return await this.collection.repartitionToken(signer, this.tokenId, amount);2445 }24462447 async burn(signer: TSigner, amount=1n) {2448 return await this.collection.burnToken(signer, this.tokenId, amount);2449 }2450}