12345678import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents} from '@polkadot/api/types';10import {IKeyringPair} from '@polkadot/types/types';11import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';12import { ICrossAccountIdLower, ICrossAccountId, TUniqueNetworks, IApiListeners, TApiAllowedListeners, TSigner, TSubstrateAccount, ICollectionLimits, ICollectionPermissions, INestingPermissions, IProperty, ITokenPropertyPermission, ICollectionCreationOptions, IToken, IChainProperties, TEthereumAccount } from './types';131415const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {16 const address = {} as ICrossAccountId;17 if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;18 if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;19 return address;20};212223const nesting = {24 toChecksumAddress(address: string): string {25 if (typeof address === 'undefined') return '';2627 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);2829 address = address.toLowerCase().replace(/^0x/i,'');30 const addressHash = keccakAsHex(address).replace(/^0x/i,'');31 const checksumAddress = ['0x'];3233 for (let i = 0; i < address.length; i++) {34 35 if (parseInt(addressHash[i], 16) > 7) {36 checksumAddress.push(address[i].toUpperCase());37 } else {38 checksumAddress.push(address[i]);39 }40 }41 return checksumAddress.join('');42 },43 tokenIdToAddress(collectionId: number, tokenId: number) {44 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);45 },46};474849interface IChainEvent {50 data: any;51 method: string;52 section: string;53}5455interface ITransactionResult {56 status: 'Fail' | 'Success';57 result: {58 events: {59 event: IChainEvent60 }[];61 },62 moduleError?: string;63}6465interface ILogger {66 log: (msg: any, level?: string) => void;67 level: {68 ERROR: 'ERROR';69 WARNING: 'WARNING';70 INFO: 'INFO';71 [key: string]: string;72 }73}7475interface IUniqueHelperLog {76 executedAt: number;77 executionTime: number;78 type: 'extrinsic' | 'rpc';79 status: 'Fail' | 'Success';80 call: string;81 params: any[];82 moduleError?: string;83 events?: any;84}8586class UniqueUtil {87 static transactionStatus = {88 NOT_READY: 'NotReady',89 FAIL: 'Fail',90 SUCCESS: 'Success',91 };9293 static chainLogType = {94 EXTRINSIC: 'extrinsic',95 RPC: 'rpc',96 };9798 static getNestingTokenAddress(collectionId: number, tokenId: number) {99 return nesting.tokenIdToAddress(collectionId, tokenId);100 }101102 static getDefaultLogger(): ILogger {103 return {104 log(msg: any, level = 'INFO') {105 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));106 },107 level: {108 ERROR: 'ERROR',109 WARNING: 'WARNING',110 INFO: 'INFO',111 },112 };113 }114115 static vec2str(arr: string[] | number[]) {116 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');117 }118119 static str2vec(string: string) {120 if (typeof string !== 'string') return string;121 return Array.from(string).map(x => x.charCodeAt(0));122 }123124 static fromSeed(seed: string, ss58Format = 42) {125 const keyring = new Keyring({type: 'sr25519', ss58Format});126 return keyring.addFromUri(seed);127 }128129 static normalizeSubstrateAddress(address: string, ss58Format = 42) {130 return encodeAddress(decodeAddress(address), ss58Format);131 }132133 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult, label = 'new collection') {134 if (creationResult.status !== this.transactionStatus.SUCCESS) {135 throw Error(`Unable to create collection for ${label}`);136 }137138 let collectionId = null;139 creationResult.result.events.forEach(({event: {data, method, section}}) => {140 if ((section === 'common') && (method === 'CollectionCreated')) {141 collectionId = parseInt(data[0].toString(), 10);142 }143 });144145 if (collectionId === null) {146 throw Error(`No CollectionCreated event for ${label}`);147 }148149 return collectionId;150 }151152 static extractTokensFromCreationResult(creationResult: ITransactionResult, label = 'new tokens') {153 if (creationResult.status !== this.transactionStatus.SUCCESS) {154 throw Error(`Unable to create tokens for ${label}`);155 }156 let success = false;157 const tokens = [] as any;158 creationResult.result.events.forEach(({event: {data, method, section}}) => {159 if (method === 'ExtrinsicSuccess') {160 success = true;161 } else if ((section === 'common') && (method === 'ItemCreated')) {162 tokens.push({163 collectionId: parseInt(data[0].toString(), 10),164 tokenId: parseInt(data[1].toString(), 10),165 owner: data[2].toJSON(),166 });167 }168 });169 return {success, tokens};170 }171172 static extractTokensFromBurnResult(burnResult: ITransactionResult, label = 'burned tokens') {173 if (burnResult.status !== this.transactionStatus.SUCCESS) {174 throw Error(`Unable to burn tokens for ${label}`);175 }176 let success = false;177 const tokens = [] as any;178 burnResult.result.events.forEach(({event: {data, method, section}}) => {179 if (method === 'ExtrinsicSuccess') {180 success = true;181 } else if ((section === 'common') && (method === 'ItemDestroyed')) {182 tokens.push({183 collectionId: parseInt(data[0].toString(), 10),184 tokenId: parseInt(data[1].toString(), 10),185 owner: data[2].toJSON(),186 });187 }188 });189 return {success, tokens};190 }191192 static findCollectionInEvents(events: {event: IChainEvent}[], collectionId: number, expectedSection: string, expectedMethod: string, label?: string) {193 let eventId = null;194 events.forEach(({event: {data, method, section}}) => {195 if ((section === expectedSection) && (method === expectedMethod)) {196 eventId = parseInt(data[0].toString(), 10);197 }198 });199200 if (eventId === null) {201 throw Error(`No ${expectedMethod} event for ${label}`);202 }203 return eventId === collectionId;204 }205206 static isTokenTransferSuccess(events: {event: IChainEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {207 const normalizeAddress = (address: string | ICrossAccountId) => {208 if(typeof address === 'string') return address;209 const obj = {} as any;210 Object.keys(address).forEach(k => {211 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];212 });213 if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};214 if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};215 return address;216 };217 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;218 events.forEach(({event: {data, method, section}}) => {219 if ((section === 'common') && (method === 'Transfer')) {220 const hData = (data as any).toJSON();221 transfer = {222 collectionId: hData[0],223 tokenId: hData[1],224 from: normalizeAddress(hData[2]),225 to: normalizeAddress(hData[3]),226 amount: BigInt(hData[4]),227 };228 }229 });230 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;231 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);232 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);233 isSuccess = isSuccess && amount === transfer.amount;234 return isSuccess;235 }236}237238239class ChainHelperBase {240 transactionStatus = UniqueUtil.transactionStatus;241 chainLogType = UniqueUtil.chainLogType;242 util: typeof UniqueUtil;243 logger: ILogger;244 api: ApiPromise | null;245 forcedNetwork: TUniqueNetworks | null;246 network: TUniqueNetworks | null;247 chainLog: IUniqueHelperLog[];248249 constructor(logger?: ILogger) {250 this.util = UniqueUtil;251 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();252 this.logger = logger;253 this.api = null;254 this.forcedNetwork = null;255 this.network = null;256 this.chainLog = [];257 }258259 clearChainLog(): void {260 this.chainLog = [];261 }262263 forceNetwork(value: TUniqueNetworks): void {264 this.forcedNetwork = value;265 }266267 async connect(wsEndpoint: string, listeners?: IApiListeners) {268 if (this.api !== null) throw Error('Already connected');269 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);270 this.api = api;271 this.network = network;272 }273274 async disconnect() {275 if (this.api === null) return;276 await this.api.disconnect();277 this.api = null;278 this.network = null;279 }280281 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {282 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;283 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;284 return 'opal';285 }286287 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {288 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});289 await api.isReady;290291 const network = await this.detectNetwork(api);292293 await api.disconnect();294295 return network;296 }297298 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{ 299 api: ApiPromise; 300 network: TUniqueNetworks; 301 }> {302 if(typeof network === 'undefined' || network === null) network = 'opal';303 const supportedRPC = {304 opal: {305 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,306 },307 quartz: {308 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,309 },310 unique: {311 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,312 },313 };314 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);315 const rpc = supportedRPC[network];316317 318 319320 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});321322 await api.isReadyOrError;323324 if (typeof listeners === 'undefined') listeners = {};325 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {326 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;327 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);328 }329330 return {api, network};331 }332333 getTransactionStatus(data: {events: {event: IChainEvent}[], status: any}) {334 const {events, status} = data;335 if (status.isReady) {336 return this.transactionStatus.NOT_READY;337 }338 if (status.isBroadcast) {339 return this.transactionStatus.NOT_READY;340 }341 if (status.isInBlock || status.isFinalized) {342 const errors = events.filter(e => e.event.data.method === 'ExtrinsicFailed');343 if (errors.length > 0) {344 return this.transactionStatus.FAIL;345 }346 if (events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {347 return this.transactionStatus.SUCCESS;348 }349 }350351 return this.transactionStatus.FAIL;352 }353354 signTransaction(sender: TSigner, transaction: any, label = 'transaction', options: any = null) {355 const sign = (callback: any) => {356 if(options !== null) return transaction.signAndSend(sender, options, callback);357 return transaction.signAndSend(sender, callback);358 };359 return new Promise(async (resolve, reject) => {360 try {361 const unsub = await sign((result: any) => {362 const status = this.getTransactionStatus(result);363364 if (status === this.transactionStatus.SUCCESS) {365 this.logger.log(`${label} successful`);366 unsub();367 resolve({result, status});368 } else if (status === this.transactionStatus.FAIL) {369 let moduleError = null;370371 if (result.hasOwnProperty('dispatchError')) {372 const dispatchError = result['dispatchError'];373374 if (dispatchError && dispatchError.isModule) {375 const modErr = dispatchError.asModule;376 const errorMeta = dispatchError.registry.findMetaError(modErr);377378 moduleError = `${errorMeta.section}.${errorMeta.name}`;379 }380 else {381 this.logger.log(result, this.logger.level.ERROR);382 }383 }384385 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);386 unsub();387 reject({status, moduleError, result});388 }389 });390 } catch (e) {391 this.logger.log(e, this.logger.level.ERROR);392 reject(e);393 }394 });395 }396397 constructApiCall(apiCall: string, params: any[]) {398 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);399 let call = this.api as any;400 for(const part of apiCall.slice(4).split('.')) {401 call = call[part];402 }403 return call(...params);404 }405406 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=false, failureMessage='expected success') {407 if(this.api === null) throw Error('API not initialized');408 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);409410 const startTime = (new Date()).getTime();411 let result: ITransactionResult;412 let events = [];413 try {414 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), extrinsic) as ITransactionResult;415 events = result.result.events.map((x: any) => x.toHuman());416 }417 catch(e) {418 if(!(e as object).hasOwnProperty('status')) throw e;419 result = e as ITransactionResult;420 }421422 const endTime = (new Date()).getTime();423424 const log = {425 executedAt: endTime,426 executionTime: endTime - startTime,427 type: this.chainLogType.EXTRINSIC,428 status: result.status,429 call: extrinsic,430 params,431 } as IUniqueHelperLog;432433 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;434 if(events.length > 0) log.events = events;435436 this.chainLog.push(log);437438 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(failureMessage);439 return result;440 }441442 async callRpc(rpc: string, params?: any[]) {443 if(typeof params === 'undefined') params = [];444 if(this.api === null) throw Error('API not initialized');445 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);446447 const startTime = (new Date()).getTime();448 let result;449 let error = null;450 const log = {451 type: this.chainLogType.RPC,452 call: rpc,453 params,454 } as IUniqueHelperLog;455456 try {457 result = await this.constructApiCall(rpc, params);458 }459 catch(e) {460 error = e;461 }462463 const endTime = (new Date()).getTime();464465 log.executedAt = endTime;466 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';467 log.executionTime = endTime - startTime;468469 this.chainLog.push(log);470471 if(error !== null) throw error;472473 return result;474 }475476 getSignerAddress(signer: IKeyringPair | string): string {477 if(typeof signer === 'string') return signer;478 return signer.address;479 }480}481482483class HelperGroup {484 helper: UniqueHelper;485486 constructor(uniqueHelper: UniqueHelper) {487 this.helper = uniqueHelper;488 }489}490491492class CollectionGroup extends HelperGroup {493 494495496497498499500501502 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {503 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();504 }505506 507508509510511 async getTotalCount(): Promise<number> {512 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();513 }514515 516517518519520521522 async getData(collectionId: number): Promise<{523 id: number;524 name: string;525 description: string;526 tokensCount: number;527 admins: ICrossAccountId[];528 normalizedOwner: TSubstrateAccount;529 raw: any530 } | null> {531 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);532 const humanCollection = collection.toHuman(), collectionData = {533 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],534 raw: humanCollection,535 } as any, jsonCollection = collection.toJSON();536 if (humanCollection === null) return null;537 collectionData.raw.limits = jsonCollection.limits;538 collectionData.raw.permissions = jsonCollection.permissions;539 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);540 for (const key of ['name', 'description']) {541 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);542 }543544 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode)) ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId) : 0;545 collectionData.admins = await this.getAdmins(collectionId);546547 return collectionData;548 }549550 551552553554555556557 async getAdmins(collectionId: number): Promise<ICrossAccountId[]> {558 const normalized = [];559 for(const admin of (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman()) {560 if(admin.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(admin.Substrate)});561 else normalized.push(admin);562 }563 return normalized;564 }565566 567568569570571572573 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {574 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();575 }576577 578579580581582583584585586 async burn(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {587 if(typeof label === 'undefined') label = `collection #${collectionId}`;588 const result = await this.helper.executeExtrinsic(589 signer,590 'api.tx.unique.destroyCollection', [collectionId],591 true, `Unable to burn collection for ${label}`,592 );593594 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed', label);595 }596597 598599600601602603604605606607 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount, label?: string): Promise<boolean> {608 if(typeof label === 'undefined') label = `collection #${collectionId}`;609 const result = await this.helper.executeExtrinsic(610 signer,611 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],612 true, `Unable to set collection sponsor for ${label}`,613 );614615 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet', label);616 }617618 619620621622623624625626627 async confirmSponsorship(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {628 if(typeof label === 'undefined') label = `collection #${collectionId}`;629 const result = await this.helper.executeExtrinsic(630 signer,631 'api.tx.unique.confirmSponsorship', [collectionId],632 true, `Unable to confirm collection sponsorship for ${label}`,633 );634635 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed', label);636 }637638 639640641642643644645646647648649650651652653654655656 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits, label?: string): Promise<boolean> {657 if(typeof label === 'undefined') label = `collection #${collectionId}`;658 const result = await this.helper.executeExtrinsic(659 signer,660 'api.tx.unique.setCollectionLimits', [collectionId, limits],661 true, `Unable to set collection limits for ${label}`,662 );663664 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet', label);665 }666667 668669670671672673674675676677 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount, label?: string): Promise<boolean> {678 if(typeof label === 'undefined') label = `collection #${collectionId}`;679 const result = await this.helper.executeExtrinsic(680 signer,681 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],682 true, `Unable to change collection owner for ${label}`,683 );684685 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged', label);686 }687688 689690691692693694695696697698 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {699 if(typeof label === 'undefined') label = `collection #${collectionId}`;700 const result = await this.helper.executeExtrinsic(701 signer,702 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],703 true, `Unable to add collection admin for ${label}`,704 );705706 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded', label);707 }708709 710711712713714715716717718719 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {720 if(typeof label === 'undefined') label = `collection #${collectionId}`;721 const result = await this.helper.executeExtrinsic(722 signer,723 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],724 true, `Unable to remove collection admin for ${label}`,725 );726727 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved', label);728 }729730 731732733734735736737738739740 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions, label?: string): Promise<boolean> {741 if(typeof label === 'undefined') label = `collection #${collectionId}`;742 const result = await this.helper.executeExtrinsic(743 signer,744 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],745 true, `Unable to set collection permissions for ${label}`,746 );747748 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet', label);749 }750751 752753754755756757758759760761 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions, label?: string): Promise<boolean> {762 return await this.setPermissions(signer, collectionId, {nesting: permissions}, label);763 }764765 766767768769770771772773774 async disableNesting(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {775 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}}, label);776 }777778 779780781782783784785786787788 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[], label?: string): Promise<boolean> {789 if(typeof label === 'undefined') label = `collection #${collectionId}`;790 const result = await this.helper.executeExtrinsic(791 signer,792 'api.tx.unique.setCollectionProperties', [collectionId, properties],793 true, `Unable to set collection properties for ${label}`,794 );795796 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet', label);797 }798799 800801802803804805806807808809 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[], label?: string): Promise<boolean> {810 if(typeof label === 'undefined') label = `collection #${collectionId}`;811 const result = await this.helper.executeExtrinsic(812 signer,813 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],814 true, `Unable to delete collection properties for ${label}`,815 );816817 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted', label);818 }819820 821822823824825826827828829830831 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {832 const result = await this.helper.executeExtrinsic(833 signer,834 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],835 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,836 );837838 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);839 }840841 842843844845846847848849850851852853854 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {855 const result = await this.helper.executeExtrinsic(856 signer,857 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],858 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,859 );860 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);861 }862863 864865866867868869870871872873874875 async burnToken(signer: TSigner, collectionId: number, tokenId: number, label?: string, amount=1n): Promise<{876 success: boolean,877 token: number | null878 }> {879 if(typeof label === 'undefined') label = `collection #${collectionId}`;880 const burnResult = await this.helper.executeExtrinsic(881 signer,882 'api.tx.unique.burnItem', [collectionId, tokenId, amount],883 true, `Unable to burn token for ${label}`,884 );885 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);886 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');887 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};888 }889890 891892893894895896897898899900901902 async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, label?: string, amount=1n): Promise<boolean> {903 if(typeof label === 'undefined') label = `collection #${collectionId}`;904 const burnResult = await this.helper.executeExtrinsic(905 signer,906 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],907 true, `Unable to burn token from for ${label}`,908 );909 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);910 return burnedTokens.success && burnedTokens.tokens.length > 0;911 }912913 914915916917918919920921922923924 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=1n) {925 if(typeof label === 'undefined') label = `collection #${collectionId}`;926 const approveResult = await this.helper.executeExtrinsic(927 signer, 928 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],929 true, `Unable to approve token for ${label}`,930 );931932 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved', label);933 }934935 936937938939940941942943944 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {945 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();946 }947948 949950951952953954 async getLastTokenId(collectionId: number): Promise<number> {955 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();956 }957958 959960961962963964965 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {966 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();967 }968}969970class NFTnRFT extends CollectionGroup {971 972973974975976977978979 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {980 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();981 }982983 984985986987988989990991992 async getToken(collectionId: number, tokenId: number, blockHashAt?: string, propertyKeys?: string[]): Promise<{993 properties: IProperty[];994 owner: ICrossAccountId;995 normalizedOwner: ICrossAccountId;996 }| null> {997 let tokenData;998 if(typeof blockHashAt === 'undefined') {999 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1000 }1001 else {1002 if(typeof propertyKeys === 'undefined') {1003 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1004 if(!collection) return null;1005 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1006 }1007 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1008 }1009 tokenData = tokenData.toHuman();1010 if (tokenData === null || tokenData.owner === null) return null;1011 const owner = {} as any;1012 for (const key of Object.keys(tokenData.owner)) {1013 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];1014 }1015 tokenData.normalizedOwner = crossAccountIdFromLower(owner);1016 return tokenData;1017 }10181019 10201021102210231024102510261027102810291030 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[], label?: string): Promise<boolean> {1031 if(typeof label === 'undefined') label = `collection #${collectionId}`;1032 const result = await this.helper.executeExtrinsic(1033 signer,1034 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1035 true, `Unable to set token property permissions for ${label}`,1036 );10371038 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet', label);1039 }10401041 1042104310441045104610471048104910501051 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[], label?: string): Promise<boolean> {1052 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;1053 const result = await this.helper.executeExtrinsic(1054 signer,1055 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1056 true, `Unable to set token properties for ${label}`,1057 );10581059 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet', label);1060 }10611062 1063106410651066106710681069107010711072 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[], label?: string): Promise<boolean> {1073 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;1074 const result = await this.helper.executeExtrinsic(1075 signer,1076 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1077 true, `Unable to delete token properties for ${label}`,1078 );10791080 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted', label);1081 }10821083 108410851086108710881089109010911092 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT', errorLabel = 'Unable to mint collection'): Promise<UniqueCollectionBase> {1093 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1094 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1095 for (const key of ['name', 'description', 'tokenPrefix']) {1096 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);1097 }1098 const creationResult = await this.helper.executeExtrinsic(1099 signer,1100 'api.tx.unique.createCollectionEx', [collectionOptions],1101 true, errorLabel,1102 );1103 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1104 }11051106 getCollectionObject(collectionId: number): any {1107 return null;1108 }11091110 getTokenObject(collectionId: number, tokenId: number): any {1111 return null;1112 }1113}111411151116class NFTGroup extends NFTnRFT {1117 111811191120112111221123 getCollectionObject(collectionId: number): UniqueNFTCollection {1124 return new UniqueNFTCollection(collectionId, this.helper);1125 }11261127 1128112911301131113211331134 getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1135 return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1136 }11371138 11391140114111421143114411451146 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1147 let owner;1148 if (typeof blockHashAt === 'undefined') {1149 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1150 } else {1151 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1152 }1153 return crossAccountIdFromLower(owner.toJSON());1154 }11551156 1157115811591160116111621163 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1164 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1165 }11661167 1168116911701171117211731174117511761177 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1178 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1179 }11801181 118211831184118511861187118811891190119111921193 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1194 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1195 }11961197 11981199120012011202120312041205 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1206 let owner;1207 if (typeof blockHashAt === 'undefined') {1208 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1209 } else {1210 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1211 }12121213 if (owner === null) return null;12141215 owner = owner.toHuman();12161217 return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1218 }12191220 12211222122312241225122612271228 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1229 let children;1230 if(typeof blockHashAt === 'undefined') {1231 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1232 } else {1233 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1234 }12351236 return children.toJSON().map((x: any) => {1237 return {collectionId: x.collection, tokenId: x.token};1238 });1239 }12401241 124212431244124512461247124812491250 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, label='nest token'): Promise<boolean> {1251 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1252 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1253 if(!result) {1254 throw Error(`Unable to nest token for ${label}`);1255 }1256 return result;1257 }12581259 1260126112621263126412651266126712681269 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId, label='unnest token'): Promise<boolean> {1270 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1271 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1272 if(!result) {1273 throw Error(`Unable to unnest token for ${label}`);1274 }1275 return result;1276 }12771278 1279128012811282128312841285128612871288128912901291 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueNFTCollection> {1292 return await super.mintCollection(signer, collectionOptions, 'NFT', `Unable to mint NFT collection for ${label}`) as UniqueNFTCollection;1293 }12941295 1296129712981299130013011302 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }, label?: string): Promise<UniqueNFTToken> {1303 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1304 const creationResult = await this.helper.executeExtrinsic(1305 signer,1306 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1307 nft: {1308 properties: data.properties,1309 },1310 }],1311 true, `Unable to mint NFT token for ${label}`,1312 );1313 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1314 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1315 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1316 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1317 }13181319 1320132113221323132413251326132713281329133013311332133313341335 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1336 if(typeof label === 'undefined') label = `collection #${collectionId}`;1337 const creationResult = await this.helper.executeExtrinsic(1338 signer,1339 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1340 true, `Unable to mint NFT tokens for ${label}`,1341 );1342 const collection = this.getCollectionObject(collectionId);1343 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1344 }13451346 1347134813491350135113521353135413551356135713581359136013611362136313641365 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1366 if(typeof label === 'undefined') label = `collection #${collectionId}`;1367 const rawTokens = [];1368 for (const token of tokens) {1369 const raw = {NFT: {properties: token.properties}};1370 rawTokens.push(raw);1371 }1372 const creationResult = await this.helper.executeExtrinsic(1373 signer,1374 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1375 true, `Unable to mint NFT tokens for ${label}`,1376 );1377 const collection = this.getCollectionObject(collectionId);1378 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1379 }13801381 138213831384138513861387138813891390 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string): Promise<{ success: boolean; token: number | null; }> {1391 return await super.burnToken(signer, collectionId, tokenId, label, 1n);1392 }13931394 13951396139713981399140014011402140314041405 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {1406 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, 1n);1407 }1408}140914101411class RFTGroup extends NFTnRFT {1412 141314141415141614171418 getCollectionObject(collectionId: number): UniqueRFTCollection {1419 return new UniqueRFTCollection(collectionId, this.helper);1420 }14211422 1423142414251426142714281429 getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1430 return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1431 }14321433 1434143514361437143814391440 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1441 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1442 }14431444 14451446144714481449145014511452 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1453 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1454 }14551456 1457145814591460146114621463146414651466 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=100n): Promise<boolean> {1467 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1468 }14691470 14711472147314741475147614771478147914801481 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n): Promise<boolean> {1482 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1483 }14841485 1486148714881489149014911492149314941495149614971498 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueRFTCollection> {1499 return await super.mintCollection(signer, collectionOptions, 'RFT', `Unable to mint RFT collection for ${label}`) as UniqueRFTCollection;1500 }15011502 15031504150515061507150815091510 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }, label?: string): Promise<UniqueRFTToken> {1511 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1512 const creationResult = await this.helper.executeExtrinsic(1513 signer,1514 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1515 refungible: {1516 pieces: data.pieces,1517 properties: data.properties,1518 },1519 }],1520 true, `Unable to mint RFT token for ${label}`,1521 );1522 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1523 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1524 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1525 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1526 }15271528 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1529 throw Error('Not implemented');1530 if(typeof label === 'undefined') label = `collection #${collectionId}`;1531 const creationResult = await this.helper.executeExtrinsic(1532 signer,1533 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1534 true, `Unable to mint RFT tokens for ${label}`,1535 );1536 const collection = this.getCollectionObject(collectionId);1537 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1538 }15391540 1541154215431544154515461547154815491550 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1551 if(typeof label === 'undefined') label = `collection #${collectionId}`;1552 const rawTokens = [];1553 for (const token of tokens) {1554 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1555 rawTokens.push(raw);1556 }1557 const creationResult = await this.helper.executeExtrinsic(1558 signer,1559 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1560 true, `Unable to mint RFT tokens for ${label}`,1561 );1562 const collection = this.getCollectionObject(collectionId);1563 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1564 }15651566 1567156815691570157115721573157415751576 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string, amount=100n): Promise<{ success: boolean; token: number | null; }> {1577 return await super.burnToken(signer, collectionId, tokenId, label, amount);1578 }15791580 158115821583158415851586158715881589159015911592 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=100n) {1593 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, amount);1594 }15951596 1597159815991600160116021603 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1604 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1605 }16061607 1608160916101611161216131614161516161617 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint, label?: string): Promise<boolean> {1618 if(typeof label === 'undefined') label = `collection #${collectionId}`;1619 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1620 const repartitionResult = await this.helper.executeExtrinsic(1621 signer,1622 'api.tx.unique.repartition', [collectionId, tokenId, amount],1623 true, `Unable to repartition RFT token for ${label}`,1624 );1625 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated', label);1626 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed', label);1627 }1628}162916301631class FTGroup extends CollectionGroup {1632 163316341635163616371638 getCollectionObject(collectionId: number): UniqueFTCollection {1639 return new UniqueFTCollection(collectionId, this.helper);1640 }16411642 16431644164516461647164816491650165116521653165416551656 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0, errorLabel = 'Unable to mint collection'): Promise<UniqueFTCollection> {1657 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1658 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1659 collectionOptions.mode = {fungible: decimalPoints};1660 for (const key of ['name', 'description', 'tokenPrefix']) {1661 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);1662 }1663 const creationResult = await this.helper.executeExtrinsic(1664 signer,1665 'api.tx.unique.createCollectionEx', [collectionOptions],1666 true, errorLabel,1667 );1668 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1669 }16701671 1672167316741675167616771678167916801681 async mintTokens(signer: TSigner, collectionId: number, owner: ICrossAccountId | string, amount: bigint, label?: string): Promise<boolean> {1682 if(typeof label === 'undefined') label = `collection #${collectionId}`;1683 const creationResult = await this.helper.executeExtrinsic(1684 signer,1685 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1686 fungible: {1687 value: amount,1688 },1689 }],1690 true, `Unable to mint fungible tokens for ${label}`,1691 );1692 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1693 }16941695 169616971698169917001701170217031704 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string): Promise<boolean> {1705 if(typeof label === 'undefined') label = `collection #${collectionId}`;1706 const rawTokens = [];1707 for (const token of tokens) {1708 const raw = {Fungible: {Value: token.value}};1709 rawTokens.push(raw);1710 }1711 const creationResult = await this.helper.executeExtrinsic(1712 signer,1713 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1714 true, `Unable to mint RFT tokens for ${label}`,1715 );1716 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1717 }17181719 172017211722172317241725 async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1726 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1727 }17281729 1730173117321733173417351736 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1737 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1738 }17391740 174117421743174417451746174717481749 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount: bigint) {1750 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1751 }17521753 1754175517561757175817591760176117621763 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {1764 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1765 }17661767 176817691770177117721773177417751776 async burnTokens(signer: IKeyringPair, collectionId: number, amount=100n, label?: string): Promise<boolean> {1777 return (await super.burnToken(signer, collectionId, 0, label, amount)).success;1778 }17791780 1781178217831784178517861787178817891790 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=100n, label?: string): Promise<boolean> {1791 return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, label, amount);1792 }17931794 17951796179717981799 async getTotalPieces(collectionId: number): Promise<bigint> {1800 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1801 }18021803 18041805180618071808180918101811181218131814 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {1815 return super.approveToken(signer, collectionId, 0, toAddressObj, label, amount);1816 }18171818 1819182018211822182318241825 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1826 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1827 }1828}182918301831class ChainGroup extends HelperGroup {1832 18331834183518361837 getChainProperties(): IChainProperties {1838 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1839 return {1840 ss58Format: properties.ss58Format.toJSON(),1841 tokenDecimals: properties.tokenDecimals.toJSON(),1842 tokenSymbol: properties.tokenSymbol.toJSON(),1843 };1844 }18451846 18471848184918501851 async getLatestBlockNumber(): Promise<number> {1852 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1853 }18541855 185618571858185918601861 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1862 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1863 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1864 return blockHash;1865 }18661867 186818691870187118721873 async getNonce(address: TSubstrateAccount): Promise<number> {1874 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1875 }1876}187718781879class BalanceGroup extends HelperGroup {1880 18811882188318841885 getOneTokenNominal(): bigint {1886 const chainProperties = this.helper.chain.getChainProperties();1887 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1888 }18891890 189118921893189418951896 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {1897 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();1898 }18991900 190119021903190419051906 async getEthereum(address: TEthereumAccount): Promise<bigint> {1907 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();1908 }19091910 19111912191319141915191619171918 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {1919 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}`);19201921 let transfer = {from: null, to: null, amount: 0n} as any;1922 result.result.events.forEach(({event: {data, method, section}}) => {1923 if ((section === 'balances') && (method === 'Transfer')) {1924 transfer = {1925 from: this.helper.address.normalizeSubstrate(data[0]),1926 to: this.helper.address.normalizeSubstrate(data[1]),1927 amount: BigInt(data[2]),1928 };1929 }1930 });1931 let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;1932 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;1933 isSuccess = isSuccess && BigInt(amount) === transfer.amount;1934 return isSuccess;1935 }1936}193719381939class AddressGroup extends HelperGroup {1940 1941194219431944194519461947 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {1948 return this.helper.util.normalizeSubstrateAddress(address, ss58Format);1949 }19501951 195219531954195519561957 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {1958 const info = this.helper.chain.getChainProperties();1959 return encodeAddress(decodeAddress(address), info.ss58Format);1960 }19611962 1963196419651966196719681969 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {1970 if(!toChainFormat) return evmToAddress(ethAddress);1971 const info = this.helper.chain.getChainProperties();1972 return evmToAddress(ethAddress, info.ss58Format);1973 }19741975 197619771978197919801981 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {1982 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));1983 }1984}198519861987export class UniqueHelper extends ChainHelperBase {1988 chain: ChainGroup;1989 balance: BalanceGroup;1990 address: AddressGroup;1991 collection: CollectionGroup;1992 nft: NFTGroup;1993 rft: RFTGroup;1994 ft: FTGroup;19951996 constructor(logger?: ILogger) {1997 super(logger);1998 this.chain = new ChainGroup(this);1999 this.balance = new BalanceGroup(this);2000 this.address = new AddressGroup(this);2001 this.collection = new CollectionGroup(this);2002 this.nft = new NFTGroup(this);2003 this.rft = new RFTGroup(this);2004 this.ft = new FTGroup(this);2005 } 2006}200720082009class UniqueCollectionBase {2010 helper: UniqueHelper;2011 collectionId: number;20122013 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2014 this.collectionId = collectionId;2015 this.helper = uniqueHelper;2016 }20172018 async getData() {2019 return await this.helper.collection.getData(this.collectionId);2020 }20212022 async getLastTokenId() {2023 return await this.helper.collection.getLastTokenId(this.collectionId);2024 }20252026 async isTokenExists(tokenId: number) {2027 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2028 }20292030 async getAdmins() {2031 return await this.helper.collection.getAdmins(this.collectionId);2032 }20332034 async getEffectiveLimits() {2035 return await this.helper.collection.getEffectiveLimits(this.collectionId);2036 }20372038 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount, label?: string) {2039 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress, label);2040 }20412042 async confirmSponsorship(signer: TSigner, label?: string) {2043 return await this.helper.collection.confirmSponsorship(signer, this.collectionId, label);2044 }20452046 async setLimits(signer: TSigner, limits: ICollectionLimits, label?: string) {2047 return await this.helper.collection.setLimits(signer, this.collectionId, limits, label);2048 }20492050 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount, label?: string) {2051 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress, label);2052 }20532054 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {2055 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj, label);2056 }20572058 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {2059 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj, label);2060 }20612062 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {2063 return await this.helper.collection.setProperties(signer, this.collectionId, properties, label);2064 }20652066 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {2067 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys, label);2068 }20692070 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2071 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2072 }20732074 async setPermissions(signer: TSigner, permissions: ICollectionPermissions, label?: string) {2075 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions, label);2076 }20772078 async enableNesting(signer: TSigner, permissions: INestingPermissions, label?: string) {2079 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions, label);2080 }20812082 async disableNesting(signer: TSigner, label?: string) {2083 return await this.helper.collection.disableNesting(signer, this.collectionId, label);2084 }20852086 async burn(signer: TSigner, label?: string) {2087 return await this.helper.collection.burn(signer, this.collectionId, label);2088 }2089}209020912092class UniqueNFTCollection extends UniqueCollectionBase {2093 getTokenObject(tokenId: number) {2094 return new UniqueNFTToken(tokenId, this);2095 }20962097 async getTokensByAddress(addressObj: ICrossAccountId) {2098 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2099 }21002101 async getToken(tokenId: number, blockHashAt?: string) {2102 return await this.helper.nft.getToken(this.collectionId, tokenId, blockHashAt);2103 }21042105 async getTokenOwner(tokenId: number, blockHashAt?: string) {2106 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2107 }21082109 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2110 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2111 }21122113 async getTokenChildren(tokenId: number, blockHashAt?: string) {2114 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2115 }21162117 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2118 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2119 }21202121 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2122 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2123 }21242125 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {2126 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label);2127 }21282129 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2130 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2131 }21322133 async mintToken(signer: TSigner, owner: ICrossAccountId, properties?: IProperty[], label?: string) {2134 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties}, label);2135 }21362137 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string) {2138 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens, label);2139 }21402141 async burnToken(signer: TSigner, tokenId: number, label?: string) {2142 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId, label);2143 }21442145 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {2146 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);2147 }21482149 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {2150 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);2151 }21522153 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {2154 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);2155 }21562157 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken, label?: string) {2158 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj, label);2159 }21602161 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {2162 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj, label);2163 }2164}216521662167class UniqueRFTCollection extends UniqueCollectionBase {2168 getTokenObject(tokenId: number) {2169 return new UniqueRFTToken(tokenId, this);2170 }21712172 async getTokensByAddress(addressObj: ICrossAccountId) {2173 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2174 }21752176 async getTop10TokenOwners(tokenId: number) {2177 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2178 }21792180 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2181 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2182 }21832184 async getTokenTotalPieces(tokenId: number) {2185 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2186 }21872188 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=100n) {2189 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2190 }21912192 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {2193 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2194 }21952196 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2197 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label, amount);2198 }21992200 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2201 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2202 }22032204 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint, label?: string) {2205 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount, label);2206 }22072208 async mintToken(signer: TSigner, owner: ICrossAccountId, pieces=100n, properties?: IProperty[], label?: string) {2209 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties}, label);2210 }22112212 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string) {2213 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens, label);2214 }22152216 async burnToken(signer: TSigner, tokenId: number, amount=100n, label?: string) {2217 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, label, amount);2218 }22192220 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {2221 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);2222 }22232224 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {2225 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);2226 }22272228 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {2229 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);2230 }2231}223222332234class UniqueFTCollection extends UniqueCollectionBase {2235 async mint(signer: TSigner, owner: ICrossAccountId, amount: bigint, label?: string) {2236 return await this.helper.ft.mintTokens(signer, this.collectionId, owner, amount, label);2237 }22382239 async mintWithOneOwner(signer: TSigner, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string) {2240 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, owner, tokens, label);2241 }22422243 async getBalance(addressObj: ICrossAccountId) {2244 return await this.helper.ft.getBalance(this.collectionId, addressObj);2245 }22462247 async getTop10Owners() {2248 return await this.helper.ft.getTop10Owners(this.collectionId);2249 }22502251 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount: bigint) {2252 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2253 }22542255 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {2256 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2257 }22582259 async burnTokens(signer: TSigner, amount: bigint, label?: string) {2260 return await this.helper.ft.burnTokens(signer, this.collectionId, amount, label);2261 }22622263 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount: bigint, label?: string) {2264 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount, label);2265 }22662267 async getTotalPieces() {2268 return await this.helper.ft.getTotalPieces(this.collectionId);2269 }22702271 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2272 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount, label);2273 }22742275 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2276 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2277 }2278}227922802281class UniqueTokenBase implements IToken {2282 collection: UniqueNFTCollection | UniqueRFTCollection;2283 collectionId: number;2284 tokenId: number;22852286 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2287 this.collection = collection;2288 this.collectionId = collection.collectionId;2289 this.tokenId = tokenId;2290 }22912292 async getNextSponsored(addressObj: ICrossAccountId) {2293 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2294 }22952296 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {2297 return await this.collection.setTokenProperties(signer, this.tokenId, properties, label);2298 }22992300 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {2301 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys, label);2302 }2303}230423052306class UniqueNFTToken extends UniqueTokenBase {2307 collection: UniqueNFTCollection;23082309 constructor(tokenId: number, collection: UniqueNFTCollection) {2310 super(tokenId, collection);2311 this.collection = collection;2312 }23132314 async getData(blockHashAt?: string) {2315 return await this.collection.getToken(this.tokenId, blockHashAt);2316 }23172318 async getOwner(blockHashAt?: string) {2319 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2320 }23212322 async getTopmostOwner(blockHashAt?: string) {2323 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2324 }23252326 async getChildren(blockHashAt?: string) {2327 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2328 }23292330 async nest(signer: TSigner, toTokenObj: IToken, label?: string) {2331 return await this.collection.nestToken(signer, this.tokenId, toTokenObj, label);2332 }23332334 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {2335 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj, label);2336 }23372338 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2339 return await this.collection.transferToken(signer, this.tokenId, addressObj);2340 }23412342 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2343 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2344 }23452346 async approve(signer: TSigner, toAddressObj: ICrossAccountId, label?: string) {2347 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, label);2348 }23492350 async isApproved(toAddressObj: ICrossAccountId) {2351 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2352 }23532354 async burn(signer: TSigner, label?: string) {2355 return await this.collection.burnToken(signer, this.tokenId, label);2356 }2357}23582359class UniqueRFTToken extends UniqueTokenBase {2360 collection: UniqueRFTCollection;23612362 constructor(tokenId: number, collection: UniqueRFTCollection) {2363 super(tokenId, collection);2364 this.collection = collection;2365 }23662367 async getTop10Owners() {2368 return await this.collection.getTop10TokenOwners(this.tokenId);2369 }23702371 async getBalance(addressObj: ICrossAccountId) {2372 return await this.collection.getTokenBalance(this.tokenId, addressObj);2373 }23742375 async getTotalPieces() {2376 return await this.collection.getTokenTotalPieces(this.tokenId);2377 }23782379 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=100n) {2380 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2381 }23822383 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {2384 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2385 }23862387 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2388 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount, label);2389 }23902391 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2392 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2393 }23942395 async repartition(signer: TSigner, amount: bigint, label?: string) {2396 return await this.collection.repartitionToken(signer, this.tokenId, amount, label);2397 }23982399 async burn(signer: TSigner, amount=100n, label?: string) {2400 return await this.collection.burnToken(signer, this.tokenId, amount, label);2401 }2402}