12345678import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IChainEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {15 const address = {} as ICrossAccountId;16 if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;17 if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;18 return address;19};202122const nesting = {23 toChecksumAddress(address: string): string {24 if (typeof address === 'undefined') return '';2526 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);2728 address = address.toLowerCase().replace(/^0x/i,'');29 const addressHash = keccakAsHex(address).replace(/^0x/i,'');30 const checksumAddress = ['0x'];3132 for (let i = 0; i < address.length; i++) {33 34 if (parseInt(addressHash[i], 16) > 7) {35 checksumAddress.push(address[i].toUpperCase());36 } else {37 checksumAddress.push(address[i]);38 }39 }40 return checksumAddress.join('');41 },42 tokenIdToAddress(collectionId: number, tokenId: number) {43 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);44 },45};4647class UniqueUtil {48 static transactionStatus = {49 NOT_READY: 'NotReady',50 FAIL: 'Fail',51 SUCCESS: 'Success',52 };5354 static chainLogType = {55 EXTRINSIC: 'extrinsic',56 RPC: 'rpc',57 };5859 static getNestingTokenAddress(collectionId: number, tokenId: number) {60 return nesting.tokenIdToAddress(collectionId, tokenId);61 }6263 static getDefaultLogger(): ILogger {64 return {65 log(msg: any, level = 'INFO') {66 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));67 },68 level: {69 ERROR: 'ERROR',70 WARNING: 'WARNING',71 INFO: 'INFO',72 },73 };74 }7576 static vec2str(arr: string[] | number[]) {77 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');78 }7980 static str2vec(string: string) {81 if (typeof string !== 'string') return string;82 return Array.from(string).map(x => x.charCodeAt(0));83 }8485 static fromSeed(seed: string, ss58Format = 42) {86 const keyring = new Keyring({type: 'sr25519', ss58Format});87 return keyring.addFromUri(seed);88 }8990 static normalizeSubstrateAddress(address: string, ss58Format = 42) {91 return encodeAddress(decodeAddress(address), ss58Format);92 }9394 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult, label = 'new collection') {95 if (creationResult.status !== this.transactionStatus.SUCCESS) {96 throw Error(`Unable to create collection for ${label}`);97 }9899 let collectionId = null;100 creationResult.result.events.forEach(({event: {data, method, section}}) => {101 if ((section === 'common') && (method === 'CollectionCreated')) {102 collectionId = parseInt(data[0].toString(), 10);103 }104 });105106 if (collectionId === null) {107 throw Error(`No CollectionCreated event for ${label}`);108 }109110 return collectionId;111 }112113 static extractTokensFromCreationResult(creationResult: ITransactionResult, label = 'new tokens') {114 if (creationResult.status !== this.transactionStatus.SUCCESS) {115 throw Error(`Unable to create tokens for ${label}`);116 }117 let success = false;118 const tokens = [] as any;119 creationResult.result.events.forEach(({event: {data, method, section}}) => {120 if (method === 'ExtrinsicSuccess') {121 success = true;122 } else if ((section === 'common') && (method === 'ItemCreated')) {123 tokens.push({124 collectionId: parseInt(data[0].toString(), 10),125 tokenId: parseInt(data[1].toString(), 10),126 owner: data[2].toJSON(),127 });128 }129 });130 return {success, tokens};131 }132133 static extractTokensFromBurnResult(burnResult: ITransactionResult, label = 'burned tokens') {134 if (burnResult.status !== this.transactionStatus.SUCCESS) {135 throw Error(`Unable to burn tokens for ${label}`);136 }137 let success = false;138 const tokens = [] as any;139 burnResult.result.events.forEach(({event: {data, method, section}}) => {140 if (method === 'ExtrinsicSuccess') {141 success = true;142 } else if ((section === 'common') && (method === 'ItemDestroyed')) {143 tokens.push({144 collectionId: parseInt(data[0].toString(), 10),145 tokenId: parseInt(data[1].toString(), 10),146 owner: data[2].toJSON(),147 });148 }149 });150 return {success, tokens};151 }152153 static findCollectionInEvents(events: {event: IChainEvent}[], collectionId: number, expectedSection: string, expectedMethod: string, label?: string) {154 let eventId = null;155 events.forEach(({event: {data, method, section}}) => {156 if ((section === expectedSection) && (method === expectedMethod)) {157 eventId = parseInt(data[0].toString(), 10);158 }159 });160161 if (eventId === null) {162 throw Error(`No ${expectedMethod} event for ${label}`);163 }164 return eventId === collectionId;165 }166167 static isTokenTransferSuccess(events: {event: IChainEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {168 const normalizeAddress = (address: string | ICrossAccountId) => {169 if(typeof address === 'string') return address;170 const obj = {} as any;171 Object.keys(address).forEach(k => {172 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];173 });174 if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};175 if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};176 return address;177 };178 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;179 events.forEach(({event: {data, method, section}}) => {180 if ((section === 'common') && (method === 'Transfer')) {181 const hData = (data as any).toJSON();182 transfer = {183 collectionId: hData[0],184 tokenId: hData[1],185 from: normalizeAddress(hData[2]),186 to: normalizeAddress(hData[3]),187 amount: BigInt(hData[4]),188 };189 }190 });191 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;192 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);193 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);194 isSuccess = isSuccess && amount === transfer.amount;195 return isSuccess;196 }197}198199200class ChainHelperBase {201 transactionStatus = UniqueUtil.transactionStatus;202 chainLogType = UniqueUtil.chainLogType;203 util: typeof UniqueUtil;204 logger: ILogger;205 api: ApiPromise | null;206 forcedNetwork: TUniqueNetworks | null;207 network: TUniqueNetworks | null;208 chainLog: IUniqueHelperLog[];209210 constructor(logger?: ILogger) {211 this.util = UniqueUtil;212 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();213 this.logger = logger;214 this.api = null;215 this.forcedNetwork = null;216 this.network = null;217 this.chainLog = [];218 }219220 clearChainLog(): void {221 this.chainLog = [];222 }223224 forceNetwork(value: TUniqueNetworks): void {225 this.forcedNetwork = value;226 }227228 async connect(wsEndpoint: string, listeners?: IApiListeners) {229 if (this.api !== null) throw Error('Already connected');230 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);231 this.api = api;232 this.network = network;233 }234235 async disconnect() {236 if (this.api === null) return;237 await this.api.disconnect();238 this.api = null;239 this.network = null;240 }241242 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {243 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;244 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;245 return 'opal';246 }247248 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {249 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});250 await api.isReady;251252 const network = await this.detectNetwork(api);253254 await api.disconnect();255256 return network;257 }258259 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{ 260 api: ApiPromise; 261 network: TUniqueNetworks; 262 }> {263 if(typeof network === 'undefined' || network === null) network = 'opal';264 const supportedRPC = {265 opal: {266 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,267 },268 quartz: {269 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,270 },271 unique: {272 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,273 },274 };275 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);276 const rpc = supportedRPC[network];277278 279 280281 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});282283 await api.isReadyOrError;284285 if (typeof listeners === 'undefined') listeners = {};286 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {287 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;288 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);289 }290291 return {api, network};292 }293294 getTransactionStatus(data: {events: {event: IChainEvent}[], status: any}) {295 const {events, status} = data;296 if (status.isReady) {297 return this.transactionStatus.NOT_READY;298 }299 if (status.isBroadcast) {300 return this.transactionStatus.NOT_READY;301 }302 if (status.isInBlock || status.isFinalized) {303 const errors = events.filter(e => e.event.data.method === 'ExtrinsicFailed');304 if (errors.length > 0) {305 return this.transactionStatus.FAIL;306 }307 if (events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {308 return this.transactionStatus.SUCCESS;309 }310 }311312 return this.transactionStatus.FAIL;313 }314315 signTransaction(sender: TSigner, transaction: any, label = 'transaction', options: any = null) {316 const sign = (callback: any) => {317 if(options !== null) return transaction.signAndSend(sender, options, callback);318 return transaction.signAndSend(sender, callback);319 };320 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, failureMessage='expected success') {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(failureMessage);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 557558559560561562563564565 async burn(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {566 if(typeof label === 'undefined') label = `collection #${collectionId}`;567 const result = await this.helper.executeExtrinsic(568 signer,569 'api.tx.unique.destroyCollection', [collectionId],570 true, `Unable to burn collection for ${label}`,571 );572573 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed', label);574 }575576 577578579580581582583584585586 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount, 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.setCollectionSponsor', [collectionId, sponsorAddress],591 true, `Unable to set collection sponsor for ${label}`,592 );593594 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet', label);595 }596597 598599600601602603604605606 async confirmSponsorship(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {607 if(typeof label === 'undefined') label = `collection #${collectionId}`;608 const result = await this.helper.executeExtrinsic(609 signer,610 'api.tx.unique.confirmSponsorship', [collectionId],611 true, `Unable to confirm collection sponsorship for ${label}`,612 );613614 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed', label);615 }616617 618619620621622623624625626627628629630631632633634635 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits, label?: string): Promise<boolean> {636 if(typeof label === 'undefined') label = `collection #${collectionId}`;637 const result = await this.helper.executeExtrinsic(638 signer,639 'api.tx.unique.setCollectionLimits', [collectionId, limits],640 true, `Unable to set collection limits for ${label}`,641 );642643 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet', label);644 }645646 647648649650651652653654655656 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount, 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.changeCollectionOwner', [collectionId, ownerAddress],661 true, `Unable to change collection owner for ${label}`,662 );663664 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged', label);665 }666667 668669670671672673674675676677 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, 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.addCollectionAdmin', [collectionId, adminAddressObj],682 true, `Unable to add collection admin for ${label}`,683 );684685 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded', label);686 }687688 689690691692693694695696 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId, label?: string): Promise<boolean> {697 if(typeof label === 'undefined') label = `collection #${collectionId}`;698 const result = await this.helper.executeExtrinsic(699 signer,700 'api.tx.unique.addToAllowList', [collectionId, addressObj],701 true, `Unable to add address to allow list for ${label}`,702 );703704 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');705 }706707 708709710711712713714715716717 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {718 if(typeof label === 'undefined') label = `collection #${collectionId}`;719 const result = await this.helper.executeExtrinsic(720 signer,721 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],722 true, `Unable to remove collection admin for ${label}`,723 );724725 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved', label);726 }727728 729730731732733734735736737738 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions, label?: string): Promise<boolean> {739 if(typeof label === 'undefined') label = `collection #${collectionId}`;740 const result = await this.helper.executeExtrinsic(741 signer,742 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],743 true, `Unable to set collection permissions for ${label}`,744 );745746 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet', label);747 }748749 750751752753754755756757758759 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions, label?: string): Promise<boolean> {760 return await this.setPermissions(signer, collectionId, {nesting: permissions}, label);761 }762763 764765766767768769770771772 async disableNesting(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {773 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}}, label);774 }775776 777778779780781782783784785786 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[], label?: string): Promise<boolean> {787 if(typeof label === 'undefined') label = `collection #${collectionId}`;788 const result = await this.helper.executeExtrinsic(789 signer,790 'api.tx.unique.setCollectionProperties', [collectionId, properties],791 true, `Unable to set collection properties for ${label}`,792 );793794 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet', label);795 }796797 798799800801802803804805806807 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[], label?: string): Promise<boolean> {808 if(typeof label === 'undefined') label = `collection #${collectionId}`;809 const result = await this.helper.executeExtrinsic(810 signer,811 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],812 true, `Unable to delete collection properties for ${label}`,813 );814815 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted', label);816 }817818 819820821822823824825826827828829 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {830 const result = await this.helper.executeExtrinsic(831 signer,832 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],833 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,834 );835836 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);837 }838839 840841842843844845846847848849850851852 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {853 const result = await this.helper.executeExtrinsic(854 signer,855 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],856 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,857 );858 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);859 }860861 862863864865866867868869870871872873 async burnToken(signer: TSigner, collectionId: number, tokenId: number, label?: string, amount=1n): Promise<{874 success: boolean,875 token: number | null876 }> {877 if(typeof label === 'undefined') label = `collection #${collectionId}`;878 const burnResult = await this.helper.executeExtrinsic(879 signer,880 'api.tx.unique.burnItem', [collectionId, tokenId, amount],881 true, `Unable to burn token for ${label}`,882 );883 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);884 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');885 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};886 }887888 889890891892893894895896897898899900 async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, label?: string, amount=1n): Promise<boolean> {901 if(typeof label === 'undefined') label = `collection #${collectionId}`;902 const burnResult = await this.helper.executeExtrinsic(903 signer,904 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],905 true, `Unable to burn token from for ${label}`,906 );907 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);908 return burnedTokens.success && burnedTokens.tokens.length > 0;909 }910911 912913914915916917918919920921922 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=1n) {923 if(typeof label === 'undefined') label = `collection #${collectionId}`;924 const approveResult = await this.helper.executeExtrinsic(925 signer, 926 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],927 true, `Unable to approve token for ${label}`,928 );929930 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved', label);931 }932933 934935936937938939940941942 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {943 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();944 }945946 947948949950951952 async getLastTokenId(collectionId: number): Promise<number> {953 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();954 }955956 957958959960961962963 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {964 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();965 }966}967968class NFTnRFT extends CollectionGroup {969 970971972973974975976977 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {978 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();979 }980981 982983984985986987988989990 async getToken(collectionId: number, tokenId: number, blockHashAt?: string, propertyKeys?: string[]): Promise<{991 properties: IProperty[];992 owner: ICrossAccountId;993 normalizedOwner: ICrossAccountId;994 }| null> {995 let tokenData;996 if(typeof blockHashAt === 'undefined') {997 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);998 }999 else {1000 if(typeof propertyKeys === 'undefined') {1001 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1002 if(!collection) return null;1003 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1004 }1005 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1006 }1007 tokenData = tokenData.toHuman();1008 if (tokenData === null || tokenData.owner === null) return null;1009 const owner = {} as any;1010 for (const key of Object.keys(tokenData.owner)) {1011 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];1012 }1013 tokenData.normalizedOwner = crossAccountIdFromLower(owner);1014 return tokenData;1015 }10161017 10181019102010211022102310241025102610271028 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[], label?: string): Promise<boolean> {1029 if(typeof label === 'undefined') label = `collection #${collectionId}`;1030 const result = await this.helper.executeExtrinsic(1031 signer,1032 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1033 true, `Unable to set token property permissions for ${label}`,1034 );10351036 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet', label);1037 }10381039 1040104110421043104410451046104710481049 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[], label?: string): Promise<boolean> {1050 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;1051 const result = await this.helper.executeExtrinsic(1052 signer,1053 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1054 true, `Unable to set token properties for ${label}`,1055 );10561057 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet', label);1058 }10591060 1061106210631064106510661067106810691070 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[], label?: string): Promise<boolean> {1071 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;1072 const result = await this.helper.executeExtrinsic(1073 signer,1074 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1075 true, `Unable to delete token properties for ${label}`,1076 );10771078 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted', label);1079 }10801081 108210831084108510861087108810891090 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT', errorLabel = 'Unable to mint collection'): Promise<UniqueCollectionBase> {1091 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1092 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1093 for (const key of ['name', 'description', 'tokenPrefix']) {1094 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);1095 }1096 const creationResult = await this.helper.executeExtrinsic(1097 signer,1098 'api.tx.unique.createCollectionEx', [collectionOptions],1099 true, errorLabel,1100 );1101 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1102 }11031104 getCollectionObject(_collectionId: number): any {1105 return null;1106 }11071108 getTokenObject(_collectionId: number, _tokenId: number): any {1109 return null;1110 }1111}111211131114class NFTGroup extends NFTnRFT {1115 111611171118111911201121 getCollectionObject(collectionId: number): UniqueNFTCollection {1122 return new UniqueNFTCollection(collectionId, this.helper);1123 }11241125 1126112711281129113011311132 getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1133 return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1134 }11351136 11371138113911401141114211431144 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1145 let owner;1146 if (typeof blockHashAt === 'undefined') {1147 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1148 } else {1149 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1150 }1151 return crossAccountIdFromLower(owner.toJSON());1152 }11531154 1155115611571158115911601161 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1162 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1163 }11641165 1166116711681169117011711172117311741175 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1176 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1177 }11781179 118011811182118311841185118611871188118911901191 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1192 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1193 }11941195 11961197119811991200120112021203 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1204 let owner;1205 if (typeof blockHashAt === 'undefined') {1206 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1207 } else {1208 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1209 }12101211 if (owner === null) return null;12121213 owner = owner.toHuman();12141215 return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1216 }12171218 12191220122112221223122412251226 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1227 let children;1228 if(typeof blockHashAt === 'undefined') {1229 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1230 } else {1231 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1232 }12331234 return children.toJSON().map((x: any) => {1235 return {collectionId: x.collection, tokenId: x.token};1236 });1237 }12381239 124012411242124312441245124612471248 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, label='nest token'): Promise<boolean> {1249 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1250 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1251 if(!result) {1252 throw Error(`Unable to nest token for ${label}`);1253 }1254 return result;1255 }12561257 1258125912601261126212631264126512661267 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId, label='unnest token'): Promise<boolean> {1268 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1269 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1270 if(!result) {1271 throw Error(`Unable to unnest token for ${label}`);1272 }1273 return result;1274 }12751276 1277127812791280128112821283128412851286128712881289 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueNFTCollection> {1290 return await super.mintCollection(signer, collectionOptions, 'NFT', `Unable to mint NFT collection for ${label}`) as UniqueNFTCollection;1291 }12921293 1294129512961297129812991300 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }, label?: string): Promise<UniqueNFTToken> {1301 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1302 const creationResult = await this.helper.executeExtrinsic(1303 signer,1304 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1305 nft: {1306 properties: data.properties,1307 },1308 }],1309 true, `Unable to mint NFT token for ${label}`,1310 );1311 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1312 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1313 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1314 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1315 }13161317 1318131913201321132213231324132513261327132813291330133113321333 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1334 if(typeof label === 'undefined') label = `collection #${collectionId}`;1335 const creationResult = await this.helper.executeExtrinsic(1336 signer,1337 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1338 true, `Unable to mint NFT tokens for ${label}`,1339 );1340 const collection = this.getCollectionObject(collectionId);1341 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1342 }13431344 1345134613471348134913501351135213531354135513561357135813591360136113621363 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1364 if(typeof label === 'undefined') label = `collection #${collectionId}`;1365 const rawTokens = [];1366 for (const token of tokens) {1367 const raw = {NFT: {properties: token.properties}};1368 rawTokens.push(raw);1369 }1370 const creationResult = await this.helper.executeExtrinsic(1371 signer,1372 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1373 true, `Unable to mint NFT tokens for ${label}`,1374 );1375 const collection = this.getCollectionObject(collectionId);1376 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1377 }13781379 138013811382138313841385138613871388 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string): Promise<{ success: boolean; token: number | null; }> {1389 return await super.burnToken(signer, collectionId, tokenId, label, 1n);1390 }13911392 13931394139513961397139813991400140114021403 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {1404 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, 1n);1405 }1406}140714081409class RFTGroup extends NFTnRFT {1410 141114121413141414151416 getCollectionObject(collectionId: number): UniqueRFTCollection {1417 return new UniqueRFTCollection(collectionId, this.helper);1418 }14191420 1421142214231424142514261427 getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1428 return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1429 }14301431 1432143314341435143614371438 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1439 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1440 }14411442 14431444144514461447144814491450 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1451 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1452 }14531454 1455145614571458145914601461146214631464 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=100n): Promise<boolean> {1465 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1466 }14671468 14691470147114721473147414751476147714781479 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n): Promise<boolean> {1480 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1481 }14821483 1484148514861487148814891490149114921493149414951496 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueRFTCollection> {1497 return await super.mintCollection(signer, collectionOptions, 'RFT', `Unable to mint RFT collection for ${label}`) as UniqueRFTCollection;1498 }14991500 15011502150315041505150615071508 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }, label?: string): Promise<UniqueRFTToken> {1509 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1510 const creationResult = await this.helper.executeExtrinsic(1511 signer,1512 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1513 refungible: {1514 pieces: data.pieces,1515 properties: data.properties,1516 },1517 }],1518 true, `Unable to mint RFT token for ${label}`,1519 );1520 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1521 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1522 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1523 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1524 }15251526 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1527 throw Error('Not implemented');1528 if(typeof label === 'undefined') label = `collection #${collectionId}`;1529 const creationResult = await this.helper.executeExtrinsic(1530 signer,1531 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1532 true, `Unable to mint RFT tokens for ${label}`,1533 );1534 const collection = this.getCollectionObject(collectionId);1535 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1536 }15371538 1539154015411542154315441545154615471548 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1549 if(typeof label === 'undefined') label = `collection #${collectionId}`;1550 const rawTokens = [];1551 for (const token of tokens) {1552 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1553 rawTokens.push(raw);1554 }1555 const creationResult = await this.helper.executeExtrinsic(1556 signer,1557 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1558 true, `Unable to mint RFT tokens for ${label}`,1559 );1560 const collection = this.getCollectionObject(collectionId);1561 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1562 }15631564 1565156615671568156915701571157215731574 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string, amount=100n): Promise<{ success: boolean; token: number | null; }> {1575 return await super.burnToken(signer, collectionId, tokenId, label, amount);1576 }15771578 157915801581158215831584158515861587158815891590 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=100n) {1591 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, amount);1592 }15931594 1595159615971598159916001601 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1602 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1603 }16041605 1606160716081609161016111612161316141615 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint, label?: string): Promise<boolean> {1616 if(typeof label === 'undefined') label = `collection #${collectionId}`;1617 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1618 const repartitionResult = await this.helper.executeExtrinsic(1619 signer,1620 'api.tx.unique.repartition', [collectionId, tokenId, amount],1621 true, `Unable to repartition RFT token for ${label}`,1622 );1623 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated', label);1624 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed', label);1625 }1626}162716281629class FTGroup extends CollectionGroup {1630 163116321633163416351636 getCollectionObject(collectionId: number): UniqueFTCollection {1637 return new UniqueFTCollection(collectionId, this.helper);1638 }16391640 16411642164316441645164616471648164916501651165216531654 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0, errorLabel = 'Unable to mint collection'): Promise<UniqueFTCollection> {1655 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1656 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1657 collectionOptions.mode = {fungible: decimalPoints};1658 for (const key of ['name', 'description', 'tokenPrefix']) {1659 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);1660 }1661 const creationResult = await this.helper.executeExtrinsic(1662 signer,1663 'api.tx.unique.createCollectionEx', [collectionOptions],1664 true, errorLabel,1665 );1666 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1667 }16681669 1670167116721673167416751676167716781679 async mintTokens(signer: TSigner, collectionId: number, owner: ICrossAccountId | string, amount: bigint, label?: string): Promise<boolean> {1680 if(typeof label === 'undefined') label = `collection #${collectionId}`;1681 const creationResult = await this.helper.executeExtrinsic(1682 signer,1683 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1684 fungible: {1685 value: amount,1686 },1687 }],1688 true, `Unable to mint fungible tokens for ${label}`,1689 );1690 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1691 }16921693 169416951696169716981699170017011702 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string): Promise<boolean> {1703 if(typeof label === 'undefined') label = `collection #${collectionId}`;1704 const rawTokens = [];1705 for (const token of tokens) {1706 const raw = {Fungible: {Value: token.value}};1707 rawTokens.push(raw);1708 }1709 const creationResult = await this.helper.executeExtrinsic(1710 signer,1711 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1712 true, `Unable to mint RFT tokens for ${label}`,1713 );1714 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1715 }17161717 171817191720172117221723 async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1724 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1725 }17261727 1728172917301731173217331734 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1735 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1736 }17371738 173917401741174217431744174517461747 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount: bigint) {1748 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1749 }17501751 1752175317541755175617571758175917601761 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {1762 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1763 }17641765 176617671768176917701771177217731774 async burnTokens(signer: IKeyringPair, collectionId: number, amount=100n, label?: string): Promise<boolean> {1775 return (await super.burnToken(signer, collectionId, 0, label, amount)).success;1776 }17771778 1779178017811782178317841785178617871788 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=100n, label?: string): Promise<boolean> {1789 return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, label, amount);1790 }17911792 17931794179517961797 async getTotalPieces(collectionId: number): Promise<bigint> {1798 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1799 }18001801 18021803180418051806180718081809181018111812 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {1813 return super.approveToken(signer, collectionId, 0, toAddressObj, label, amount);1814 }18151816 1817181818191820182118221823 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1824 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1825 }1826}182718281829class ChainGroup extends HelperGroup {1830 18311832183318341835 getChainProperties(): IChainProperties {1836 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1837 return {1838 ss58Format: properties.ss58Format.toJSON(),1839 tokenDecimals: properties.tokenDecimals.toJSON(),1840 tokenSymbol: properties.tokenSymbol.toJSON(),1841 };1842 }18431844 18451846184718481849 async getLatestBlockNumber(): Promise<number> {1850 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1851 }18521853 185418551856185718581859 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1860 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1861 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1862 return blockHash;1863 }18641865 186618671868186918701871 async getNonce(address: TSubstrateAccount): Promise<number> {1872 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1873 }1874}187518761877class BalanceGroup extends HelperGroup {1878 18791880188118821883 getOneTokenNominal(): bigint {1884 const chainProperties = this.helper.chain.getChainProperties();1885 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1886 }18871888 188918901891189218931894 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {1895 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();1896 }18971898 189919001901190219031904 async getEthereum(address: TEthereumAccount): Promise<bigint> {1905 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();1906 }19071908 19091910191119121913191419151916 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {1917 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}`);19181919 let transfer = {from: null, to: null, amount: 0n} as any;1920 result.result.events.forEach(({event: {data, method, section}}) => {1921 if ((section === 'balances') && (method === 'Transfer')) {1922 transfer = {1923 from: this.helper.address.normalizeSubstrate(data[0]),1924 to: this.helper.address.normalizeSubstrate(data[1]),1925 amount: BigInt(data[2]),1926 };1927 }1928 });1929 let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;1930 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;1931 isSuccess = isSuccess && BigInt(amount) === transfer.amount;1932 return isSuccess;1933 }1934}193519361937class AddressGroup extends HelperGroup {1938 1939194019411942194319441945 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {1946 return this.helper.util.normalizeSubstrateAddress(address, ss58Format);1947 }19481949 195019511952195319541955 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {1956 const info = this.helper.chain.getChainProperties();1957 return encodeAddress(decodeAddress(address), info.ss58Format);1958 }19591960 1961196219631964196519661967 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {1968 if(!toChainFormat) return evmToAddress(ethAddress);1969 const info = this.helper.chain.getChainProperties();1970 return evmToAddress(ethAddress, info.ss58Format);1971 }19721973 197419751976197719781979 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {1980 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));1981 }1982}198319841985export class UniqueHelper extends ChainHelperBase {1986 chain: ChainGroup;1987 balance: BalanceGroup;1988 address: AddressGroup;1989 collection: CollectionGroup;1990 nft: NFTGroup;1991 rft: RFTGroup;1992 ft: FTGroup;19931994 constructor(logger?: ILogger) {1995 super(logger);1996 this.chain = new ChainGroup(this);1997 this.balance = new BalanceGroup(this);1998 this.address = new AddressGroup(this);1999 this.collection = new CollectionGroup(this);2000 this.nft = new NFTGroup(this);2001 this.rft = new RFTGroup(this);2002 this.ft = new FTGroup(this);2003 } 2004}200520062007class UniqueCollectionBase {2008 helper: UniqueHelper;2009 collectionId: number;20102011 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2012 this.collectionId = collectionId;2013 this.helper = uniqueHelper;2014 }20152016 async getData() {2017 return await this.helper.collection.getData(this.collectionId);2018 }20192020 async getLastTokenId() {2021 return await this.helper.collection.getLastTokenId(this.collectionId);2022 }20232024 async isTokenExists(tokenId: number) {2025 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2026 }20272028 async getAdmins() {2029 return await this.helper.collection.getAdmins(this.collectionId);2030 }20312032 async getAllowList() {2033 return await this.helper.collection.getAllowList(this.collectionId);2034 }20352036 async getEffectiveLimits() {2037 return await this.helper.collection.getEffectiveLimits(this.collectionId);2038 }20392040 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount, label?: string) {2041 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress, label);2042 }20432044 async confirmSponsorship(signer: TSigner, label?: string) {2045 return await this.helper.collection.confirmSponsorship(signer, this.collectionId, label);2046 }20472048 async setLimits(signer: TSigner, limits: ICollectionLimits, label?: string) {2049 return await this.helper.collection.setLimits(signer, this.collectionId, limits, label);2050 }20512052 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount, label?: string) {2053 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress, label);2054 }20552056 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {2057 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj, label);2058 }20592060 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId, label?: string) {2061 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj, label);2062 }20632064 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {2065 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj, label);2066 }20672068 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {2069 return await this.helper.collection.setProperties(signer, this.collectionId, properties, label);2070 }20712072 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {2073 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys, label);2074 }20752076 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2077 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2078 }20792080 async setPermissions(signer: TSigner, permissions: ICollectionPermissions, label?: string) {2081 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions, label);2082 }20832084 async enableNesting(signer: TSigner, permissions: INestingPermissions, label?: string) {2085 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions, label);2086 }20872088 async disableNesting(signer: TSigner, label?: string) {2089 return await this.helper.collection.disableNesting(signer, this.collectionId, label);2090 }20912092 async burn(signer: TSigner, label?: string) {2093 return await this.helper.collection.burn(signer, this.collectionId, label);2094 }2095}209620972098class UniqueNFTCollection extends UniqueCollectionBase {2099 getTokenObject(tokenId: number) {2100 return new UniqueNFTToken(tokenId, this);2101 }21022103 async getTokensByAddress(addressObj: ICrossAccountId) {2104 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2105 }21062107 async getToken(tokenId: number, blockHashAt?: string) {2108 return await this.helper.nft.getToken(this.collectionId, tokenId, blockHashAt);2109 }21102111 async getTokenOwner(tokenId: number, blockHashAt?: string) {2112 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2113 }21142115 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2116 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2117 }21182119 async getTokenChildren(tokenId: number, blockHashAt?: string) {2120 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2121 }21222123 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2124 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2125 }21262127 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2128 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2129 }21302131 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {2132 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label);2133 }21342135 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2136 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2137 }21382139 async mintToken(signer: TSigner, owner: ICrossAccountId, properties?: IProperty[], label?: string) {2140 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties}, label);2141 }21422143 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string) {2144 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens, label);2145 }21462147 async burnToken(signer: TSigner, tokenId: number, label?: string) {2148 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId, label);2149 }21502151 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {2152 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);2153 }21542155 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {2156 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);2157 }21582159 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {2160 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);2161 }21622163 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken, label?: string) {2164 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj, label);2165 }21662167 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {2168 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj, label);2169 }2170}217121722173class UniqueRFTCollection extends UniqueCollectionBase {2174 getTokenObject(tokenId: number) {2175 return new UniqueRFTToken(tokenId, this);2176 }21772178 async getTokensByAddress(addressObj: ICrossAccountId) {2179 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2180 }21812182 async getTop10TokenOwners(tokenId: number) {2183 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2184 }21852186 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2187 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2188 }21892190 async getTokenTotalPieces(tokenId: number) {2191 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2192 }21932194 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=100n) {2195 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2196 }21972198 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {2199 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2200 }22012202 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2203 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label, amount);2204 }22052206 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2207 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2208 }22092210 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint, label?: string) {2211 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount, label);2212 }22132214 async mintToken(signer: TSigner, owner: ICrossAccountId, pieces=100n, properties?: IProperty[], label?: string) {2215 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties}, label);2216 }22172218 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string) {2219 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens, label);2220 }22212222 async burnToken(signer: TSigner, tokenId: number, amount=100n, label?: string) {2223 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, label, amount);2224 }22252226 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {2227 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);2228 }22292230 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {2231 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);2232 }22332234 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {2235 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);2236 }2237}223822392240class UniqueFTCollection extends UniqueCollectionBase {2241 async mint(signer: TSigner, owner: ICrossAccountId, amount: bigint, label?: string) {2242 return await this.helper.ft.mintTokens(signer, this.collectionId, owner, amount, label);2243 }22442245 async mintWithOneOwner(signer: TSigner, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string) {2246 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, owner, tokens, label);2247 }22482249 async getBalance(addressObj: ICrossAccountId) {2250 return await this.helper.ft.getBalance(this.collectionId, addressObj);2251 }22522253 async getTop10Owners() {2254 return await this.helper.ft.getTop10Owners(this.collectionId);2255 }22562257 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount: bigint) {2258 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2259 }22602261 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {2262 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2263 }22642265 async burnTokens(signer: TSigner, amount: bigint, label?: string) {2266 return await this.helper.ft.burnTokens(signer, this.collectionId, amount, label);2267 }22682269 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount: bigint, label?: string) {2270 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount, label);2271 }22722273 async getTotalPieces() {2274 return await this.helper.ft.getTotalPieces(this.collectionId);2275 }22762277 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2278 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount, label);2279 }22802281 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2282 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2283 }2284}228522862287class UniqueTokenBase implements IToken {2288 collection: UniqueNFTCollection | UniqueRFTCollection;2289 collectionId: number;2290 tokenId: number;22912292 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2293 this.collection = collection;2294 this.collectionId = collection.collectionId;2295 this.tokenId = tokenId;2296 }22972298 async getNextSponsored(addressObj: ICrossAccountId) {2299 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2300 }23012302 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {2303 return await this.collection.setTokenProperties(signer, this.tokenId, properties, label);2304 }23052306 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {2307 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys, label);2308 }2309}231023112312class UniqueNFTToken extends UniqueTokenBase {2313 collection: UniqueNFTCollection;23142315 constructor(tokenId: number, collection: UniqueNFTCollection) {2316 super(tokenId, collection);2317 this.collection = collection;2318 }23192320 async getData(blockHashAt?: string) {2321 return await this.collection.getToken(this.tokenId, blockHashAt);2322 }23232324 async getOwner(blockHashAt?: string) {2325 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2326 }23272328 async getTopmostOwner(blockHashAt?: string) {2329 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2330 }23312332 async getChildren(blockHashAt?: string) {2333 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2334 }23352336 async nest(signer: TSigner, toTokenObj: IToken, label?: string) {2337 return await this.collection.nestToken(signer, this.tokenId, toTokenObj, label);2338 }23392340 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {2341 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj, label);2342 }23432344 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2345 return await this.collection.transferToken(signer, this.tokenId, addressObj);2346 }23472348 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2349 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2350 }23512352 async approve(signer: TSigner, toAddressObj: ICrossAccountId, label?: string) {2353 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, label);2354 }23552356 async isApproved(toAddressObj: ICrossAccountId) {2357 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2358 }23592360 async burn(signer: TSigner, label?: string) {2361 return await this.collection.burnToken(signer, this.tokenId, label);2362 }2363}23642365class UniqueRFTToken extends UniqueTokenBase {2366 collection: UniqueRFTCollection;23672368 constructor(tokenId: number, collection: UniqueRFTCollection) {2369 super(tokenId, collection);2370 this.collection = collection;2371 }23722373 async getTop10Owners() {2374 return await this.collection.getTop10TokenOwners(this.tokenId);2375 }23762377 async getBalance(addressObj: ICrossAccountId) {2378 return await this.collection.getTokenBalance(this.tokenId, addressObj);2379 }23802381 async getTotalPieces() {2382 return await this.collection.getTokenTotalPieces(this.tokenId);2383 }23842385 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=100n) {2386 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2387 }23882389 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {2390 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2391 }23922393 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2394 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount, label);2395 }23962397 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2398 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2399 }24002401 async repartition(signer: TSigner, amount: bigint, label?: string) {2402 return await this.collection.repartitionToken(signer, this.tokenId, amount, label);2403 }24042405 async burn(signer: TSigner, amount=100n, label?: string) {2406 return await this.collection.burnToken(signer, this.tokenId, amount, label);2407 }2408}