12345678import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IChainEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {15 const address = {} as ICrossAccountId;16 if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;17 if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;18 return address;19};202122const nesting = {23 toChecksumAddress(address: string): string {24 if (typeof address === 'undefined') return '';2526 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);2728 address = address.toLowerCase().replace(/^0x/i,'');29 const addressHash = keccakAsHex(address).replace(/^0x/i,'');30 const checksumAddress = ['0x'];3132 for (let i = 0; i < address.length; i++) {33 34 if (parseInt(addressHash[i], 16) > 7) {35 checksumAddress.push(address[i].toUpperCase());36 } else {37 checksumAddress.push(address[i]);38 }39 }40 return checksumAddress.join('');41 },42 tokenIdToAddress(collectionId: number, tokenId: number) {43 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);44 },45};4647class UniqueUtil {48 static transactionStatus = {49 NOT_READY: 'NotReady',50 FAIL: 'Fail',51 SUCCESS: 'Success',52 };5354 static chainLogType = {55 EXTRINSIC: 'extrinsic',56 RPC: 'rpc',57 };5859 static getNestingTokenAddress(collectionId: number, tokenId: number) {60 return nesting.tokenIdToAddress(collectionId, tokenId);61 }6263 static getDefaultLogger(): ILogger {64 return {65 log(msg: any, level = 'INFO') {66 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));67 },68 level: {69 ERROR: 'ERROR',70 WARNING: 'WARNING',71 INFO: 'INFO',72 },73 };74 }7576 static vec2str(arr: string[] | number[]) {77 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');78 }7980 static str2vec(string: string) {81 if (typeof string !== 'string') return string;82 return Array.from(string).map(x => x.charCodeAt(0));83 }8485 static fromSeed(seed: string, ss58Format = 42) {86 const keyring = new Keyring({type: 'sr25519', ss58Format});87 return keyring.addFromUri(seed);88 }8990 static normalizeSubstrateAddress(address: string, ss58Format = 42) {91 return encodeAddress(decodeAddress(address), ss58Format);92 }9394 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult, label = 'new collection') {95 if (creationResult.status !== this.transactionStatus.SUCCESS) {96 throw Error(`Unable to create collection for ${label}`);97 }9899 let collectionId = null;100 creationResult.result.events.forEach(({event: {data, method, section}}) => {101 if ((section === 'common') && (method === 'CollectionCreated')) {102 collectionId = parseInt(data[0].toString(), 10);103 }104 });105106 if (collectionId === null) {107 throw Error(`No CollectionCreated event for ${label}`);108 }109110 return collectionId;111 }112113 static extractTokensFromCreationResult(creationResult: ITransactionResult, label = 'new tokens') {114 if (creationResult.status !== this.transactionStatus.SUCCESS) {115 throw Error(`Unable to create tokens for ${label}`);116 }117 let success = false;118 const tokens = [] as any;119 creationResult.result.events.forEach(({event: {data, method, section}}) => {120 if (method === 'ExtrinsicSuccess') {121 success = true;122 } else if ((section === 'common') && (method === 'ItemCreated')) {123 tokens.push({124 collectionId: parseInt(data[0].toString(), 10),125 tokenId: parseInt(data[1].toString(), 10),126 owner: data[2].toJSON(),127 });128 }129 });130 return {success, tokens};131 }132133 static extractTokensFromBurnResult(burnResult: ITransactionResult, label = 'burned tokens') {134 if (burnResult.status !== this.transactionStatus.SUCCESS) {135 throw Error(`Unable to burn tokens for ${label}`);136 }137 let success = false;138 const tokens = [] as any;139 burnResult.result.events.forEach(({event: {data, method, section}}) => {140 if (method === 'ExtrinsicSuccess') {141 success = true;142 } else if ((section === 'common') && (method === 'ItemDestroyed')) {143 tokens.push({144 collectionId: parseInt(data[0].toString(), 10),145 tokenId: parseInt(data[1].toString(), 10),146 owner: data[2].toJSON(),147 });148 }149 });150 return {success, tokens};151 }152153 static findCollectionInEvents(events: {event: IChainEvent}[], collectionId: number, expectedSection: string, expectedMethod: string, label?: string) {154 let eventId = null;155 events.forEach(({event: {data, method, section}}) => {156 if ((section === expectedSection) && (method === expectedMethod)) {157 eventId = parseInt(data[0].toString(), 10);158 }159 });160161 if (eventId === null) {162 throw Error(`No ${expectedMethod} event for ${label}`);163 }164 return eventId === collectionId;165 }166167 static isTokenTransferSuccess(events: {event: IChainEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {168 const normalizeAddress = (address: string | ICrossAccountId) => {169 if(typeof address === 'string') return address;170 const obj = {} as any;171 Object.keys(address).forEach(k => {172 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];173 });174 if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};175 if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};176 return address;177 };178 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;179 events.forEach(({event: {data, method, section}}) => {180 if ((section === 'common') && (method === 'Transfer')) {181 const hData = (data as any).toJSON();182 transfer = {183 collectionId: hData[0],184 tokenId: hData[1],185 from: normalizeAddress(hData[2]),186 to: normalizeAddress(hData[3]),187 amount: BigInt(hData[4]),188 };189 }190 });191 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;192 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);193 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);194 isSuccess = isSuccess && amount === transfer.amount;195 return isSuccess;196 }197}198199200class ChainHelperBase {201 transactionStatus = UniqueUtil.transactionStatus;202 chainLogType = UniqueUtil.chainLogType;203 util: typeof UniqueUtil;204 logger: ILogger;205 api: ApiPromise | null;206 forcedNetwork: TUniqueNetworks | null;207 network: TUniqueNetworks | null;208 chainLog: IUniqueHelperLog[];209210 constructor(logger?: ILogger) {211 this.util = UniqueUtil;212 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();213 this.logger = logger;214 this.api = null;215 this.forcedNetwork = null;216 this.network = null;217 this.chainLog = [];218 }219220 clearChainLog(): void {221 this.chainLog = [];222 }223224 forceNetwork(value: TUniqueNetworks): void {225 this.forcedNetwork = value;226 }227228 async connect(wsEndpoint: string, listeners?: IApiListeners) {229 if (this.api !== null) throw Error('Already connected');230 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);231 this.api = api;232 this.network = network;233 }234235 async disconnect() {236 if (this.api === null) return;237 await this.api.disconnect();238 this.api = null;239 this.network = null;240 }241242 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {243 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;244 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;245 return 'opal';246 }247248 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {249 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});250 await api.isReady;251252 const network = await this.detectNetwork(api);253254 await api.disconnect();255256 return network;257 }258259 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{ 260 api: ApiPromise; 261 network: TUniqueNetworks; 262 }> {263 if(typeof network === 'undefined' || network === null) network = 'opal';264 const supportedRPC = {265 opal: {266 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,267 },268 quartz: {269 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,270 },271 unique: {272 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,273 },274 };275 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);276 const rpc = supportedRPC[network];277278 279 280281 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});282283 await api.isReadyOrError;284285 if (typeof listeners === 'undefined') listeners = {};286 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {287 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;288 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);289 }290291 return {api, network};292 }293294 getTransactionStatus(data: {events: {event: IChainEvent}[], status: any}) {295 const {events, status} = data;296 if (status.isReady) {297 return this.transactionStatus.NOT_READY;298 }299 if (status.isBroadcast) {300 return this.transactionStatus.NOT_READY;301 }302 if (status.isInBlock || status.isFinalized) {303 const errors = events.filter(e => e.event.data.method === 'ExtrinsicFailed');304 if (errors.length > 0) {305 return this.transactionStatus.FAIL;306 }307 if (events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {308 return this.transactionStatus.SUCCESS;309 }310 }311312 return this.transactionStatus.FAIL;313 }314315 signTransaction(sender: TSigner, transaction: any, label = 'transaction', options: any = null) {316 const sign = (callback: any) => {317 if(options !== null) return transaction.signAndSend(sender, options, callback);318 return transaction.signAndSend(sender, callback);319 };320 return new Promise(async (resolve, reject) => {321 try {322 const unsub = await sign((result: any) => {323 const status = this.getTransactionStatus(result);324325 if (status === this.transactionStatus.SUCCESS) {326 this.logger.log(`${label} successful`);327 unsub();328 resolve({result, status});329 } else if (status === this.transactionStatus.FAIL) {330 let moduleError = null;331332 if (result.hasOwnProperty('dispatchError')) {333 const dispatchError = result['dispatchError'];334335 if (dispatchError && dispatchError.isModule) {336 const modErr = dispatchError.asModule;337 const errorMeta = dispatchError.registry.findMetaError(modErr);338339 moduleError = `${errorMeta.section}.${errorMeta.name}`;340 }341 else {342 this.logger.log(result, this.logger.level.ERROR);343 }344 }345346 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);347 unsub();348 reject({status, moduleError, result});349 }350 });351 } catch (e) {352 this.logger.log(e, this.logger.level.ERROR);353 reject(e);354 }355 });356 }357358 constructApiCall(apiCall: string, params: any[]) {359 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);360 let call = this.api as any;361 for(const part of apiCall.slice(4).split('.')) {362 call = call[part];363 }364 return call(...params);365 }366367 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=false, failureMessage='expected success') {368 if(this.api === null) throw Error('API not initialized');369 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);370371 const startTime = (new Date()).getTime();372 let result: ITransactionResult;373 let events = [];374 try {375 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), extrinsic) as ITransactionResult;376 events = result.result.events.map((x: any) => x.toHuman());377 }378 catch(e) {379 if(!(e as object).hasOwnProperty('status')) throw e;380 result = e as ITransactionResult;381 }382383 const endTime = (new Date()).getTime();384385 const log = {386 executedAt: endTime,387 executionTime: endTime - startTime,388 type: this.chainLogType.EXTRINSIC,389 status: result.status,390 call: extrinsic,391 params,392 } as IUniqueHelperLog;393394 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;395 if(events.length > 0) log.events = events;396397 this.chainLog.push(log);398399 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(failureMessage);400 return result;401 }402403 async callRpc(rpc: string, params?: any[]) {404 if(typeof params === 'undefined') params = [];405 if(this.api === null) throw Error('API not initialized');406 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);407408 const startTime = (new Date()).getTime();409 let result;410 let error = null;411 const log = {412 type: this.chainLogType.RPC,413 call: rpc,414 params,415 } as IUniqueHelperLog;416417 try {418 result = await this.constructApiCall(rpc, params);419 }420 catch(e) {421 error = e;422 }423424 const endTime = (new Date()).getTime();425426 log.executedAt = endTime;427 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';428 log.executionTime = endTime - startTime;429430 this.chainLog.push(log);431432 if(error !== null) throw error;433434 return result;435 }436437 getSignerAddress(signer: IKeyringPair | string): string {438 if(typeof signer === 'string') return signer;439 return signer.address;440 }441}442443444class HelperGroup {445 helper: UniqueHelper;446447 constructor(uniqueHelper: UniqueHelper) {448 this.helper = uniqueHelper;449 }450}451452453class CollectionGroup extends HelperGroup {454 455456457458459460461462463 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {464 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();465 }466467 468469470471472 async getTotalCount(): Promise<number> {473 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();474 }475476 477478479480481482483 async getData(collectionId: number): Promise<{484 id: number;485 name: string;486 description: string;487 tokensCount: number;488 admins: ICrossAccountId[];489 normalizedOwner: TSubstrateAccount;490 raw: any491 } | null> {492 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);493 const humanCollection = collection.toHuman(), collectionData = {494 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],495 raw: humanCollection,496 } as any, jsonCollection = collection.toJSON();497 if (humanCollection === null) return null;498 collectionData.raw.limits = jsonCollection.limits;499 collectionData.raw.permissions = jsonCollection.permissions;500 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);501 for (const key of ['name', 'description']) {502 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);503 }504505 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode)) ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId) : 0;506 collectionData.admins = await this.getAdmins(collectionId);507508 return collectionData;509 }510511 512513514515516517518 async getAdmins(collectionId: number): Promise<ICrossAccountId[]> {519 const normalized = [];520 for(const admin of (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman()) {521 if(admin.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(admin.Substrate)});522 else normalized.push(admin);523 }524 return normalized;525 }526527 528529530531532533 async getAllowList(collectionId: number): Promise<ICrossAccountId[]> {534 const normalized = [];535 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();536 for (const address of allowListed) {537 if (address.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(address.Substrate)});538 else normalized.push(address);539 }540 return normalized;541 }542543 544545546547548549550 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {551 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();552 }553554 555556557558559560561562563 async burn(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {564 if(typeof label === 'undefined') label = `collection #${collectionId}`;565 const result = await this.helper.executeExtrinsic(566 signer,567 'api.tx.unique.destroyCollection', [collectionId],568 true, `Unable to burn collection for ${label}`,569 );570571 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed', label);572 }573574 575576577578579580581582583584 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount, label?: string): Promise<boolean> {585 if(typeof label === 'undefined') label = `collection #${collectionId}`;586 const result = await this.helper.executeExtrinsic(587 signer,588 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],589 true, `Unable to set collection sponsor for ${label}`,590 );591592 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet', label);593 }594595 596597598599600601602603604 async confirmSponsorship(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {605 if(typeof label === 'undefined') label = `collection #${collectionId}`;606 const result = await this.helper.executeExtrinsic(607 signer,608 'api.tx.unique.confirmSponsorship', [collectionId],609 true, `Unable to confirm collection sponsorship for ${label}`,610 );611612 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed', label);613 }614615 616617618619620621622623624625626627628629630631632633 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits, label?: string): Promise<boolean> {634 if(typeof label === 'undefined') label = `collection #${collectionId}`;635 const result = await this.helper.executeExtrinsic(636 signer,637 'api.tx.unique.setCollectionLimits', [collectionId, limits],638 true, `Unable to set collection limits for ${label}`,639 );640641 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet', label);642 }643644 645646647648649650651652653654 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount, label?: string): Promise<boolean> {655 if(typeof label === 'undefined') label = `collection #${collectionId}`;656 const result = await this.helper.executeExtrinsic(657 signer,658 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],659 true, `Unable to change collection owner for ${label}`,660 );661662 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged', label);663 }664665 666667668669670671672673674675 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {676 if(typeof label === 'undefined') label = `collection #${collectionId}`;677 const result = await this.helper.executeExtrinsic(678 signer,679 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],680 true, `Unable to add collection admin for ${label}`,681 );682683 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded', label);684 }685686 687688689690691692693694 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId, label?: string): Promise<boolean> {695 if(typeof label === 'undefined') label = `collection #${collectionId}`;696 const result = await this.helper.executeExtrinsic(697 signer,698 'api.tx.unique.addToAllowList', [collectionId, addressObj],699 true, `Unable to add address to allow list for ${label}`,700 );701702 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');703 }704705 706707708709710711712713714715 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {716 if(typeof label === 'undefined') label = `collection #${collectionId}`;717 const result = await this.helper.executeExtrinsic(718 signer,719 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],720 true, `Unable to remove collection admin for ${label}`,721 );722723 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved', label);724 }725726 727728729730731732733734735736 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions, label?: string): Promise<boolean> {737 if(typeof label === 'undefined') label = `collection #${collectionId}`;738 const result = await this.helper.executeExtrinsic(739 signer,740 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],741 true, `Unable to set collection permissions for ${label}`,742 );743744 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet', label);745 }746747 748749750751752753754755756757 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions, label?: string): Promise<boolean> {758 return await this.setPermissions(signer, collectionId, {nesting: permissions}, label);759 }760761 762763764765766767768769770 async disableNesting(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {771 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}}, label);772 }773774 775776777778779780781782783784 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[], label?: string): Promise<boolean> {785 if(typeof label === 'undefined') label = `collection #${collectionId}`;786 const result = await this.helper.executeExtrinsic(787 signer,788 'api.tx.unique.setCollectionProperties', [collectionId, properties],789 true, `Unable to set collection properties for ${label}`,790 );791792 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet', label);793 }794795 796797798799800801802803804805 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[], label?: string): Promise<boolean> {806 if(typeof label === 'undefined') label = `collection #${collectionId}`;807 const result = await this.helper.executeExtrinsic(808 signer,809 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],810 true, `Unable to delete collection properties for ${label}`,811 );812813 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted', label);814 }815816 817818819820821822823824825826827 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {828 const result = await this.helper.executeExtrinsic(829 signer,830 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],831 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,832 );833834 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);835 }836837 838839840841842843844845846847848849850 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {851 const result = await this.helper.executeExtrinsic(852 signer,853 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],854 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,855 );856 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);857 }858859 860861862863864865866867868869870871 async burnToken(signer: TSigner, collectionId: number, tokenId: number, label?: string, amount=1n): Promise<{872 success: boolean,873 token: number | null874 }> {875 if(typeof label === 'undefined') label = `collection #${collectionId}`;876 const burnResult = await this.helper.executeExtrinsic(877 signer,878 'api.tx.unique.burnItem', [collectionId, tokenId, amount],879 true, `Unable to burn token for ${label}`,880 );881 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);882 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');883 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};884 }885886 887888889890891892893894895896897898 async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, label?: string, amount=1n): Promise<boolean> {899 if(typeof label === 'undefined') label = `collection #${collectionId}`;900 const burnResult = await this.helper.executeExtrinsic(901 signer,902 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],903 true, `Unable to burn token from for ${label}`,904 );905 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);906 return burnedTokens.success && burnedTokens.tokens.length > 0;907 }908909 910911912913914915916917918919920 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=1n) {921 if(typeof label === 'undefined') label = `collection #${collectionId}`;922 const approveResult = await this.helper.executeExtrinsic(923 signer, 924 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],925 true, `Unable to approve token for ${label}`,926 );927928 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved', label);929 }930931 932933934935936937938939940 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {941 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();942 }943944 945946947948949950 async getLastTokenId(collectionId: number): Promise<number> {951 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();952 }953954 955956957958959960961 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {962 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();963 }964}965966class NFTnRFT extends CollectionGroup {967 968969970971972973974975 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {976 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();977 }978979 980981982983984985986987988 async getToken(collectionId: number, tokenId: number, blockHashAt?: string, propertyKeys?: string[]): Promise<{989 properties: IProperty[];990 owner: ICrossAccountId;991 normalizedOwner: ICrossAccountId;992 }| null> {993 let tokenData;994 if(typeof blockHashAt === 'undefined') {995 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);996 }997 else {998 if(typeof propertyKeys === 'undefined') {999 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1000 if(!collection) return null;1001 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1002 }1003 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1004 }1005 tokenData = tokenData.toHuman();1006 if (tokenData === null || tokenData.owner === null) return null;1007 const owner = {} as any;1008 for (const key of Object.keys(tokenData.owner)) {1009 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];1010 }1011 tokenData.normalizedOwner = crossAccountIdFromLower(owner);1012 return tokenData;1013 }10141015 10161017101810191020102110221023102410251026 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[], label?: string): Promise<boolean> {1027 if(typeof label === 'undefined') label = `collection #${collectionId}`;1028 const result = await this.helper.executeExtrinsic(1029 signer,1030 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1031 true, `Unable to set token property permissions for ${label}`,1032 );10331034 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet', label);1035 }10361037 1038103910401041104210431044104510461047 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[], label?: string): Promise<boolean> {1048 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;1049 const result = await this.helper.executeExtrinsic(1050 signer,1051 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1052 true, `Unable to set token properties for ${label}`,1053 );10541055 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet', label);1056 }10571058 1059106010611062106310641065106610671068 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[], label?: string): Promise<boolean> {1069 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;1070 const result = await this.helper.executeExtrinsic(1071 signer,1072 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1073 true, `Unable to delete token properties for ${label}`,1074 );10751076 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted', label);1077 }10781079 108010811082108310841085108610871088 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT', errorLabel = 'Unable to mint collection'): Promise<UniqueCollectionBase> {1089 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1090 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1091 for (const key of ['name', 'description', 'tokenPrefix']) {1092 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);1093 }1094 const creationResult = await this.helper.executeExtrinsic(1095 signer,1096 'api.tx.unique.createCollectionEx', [collectionOptions],1097 true, errorLabel,1098 );1099 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1100 }11011102 getCollectionObject(collectionId: number): any {1103 return null;1104 }11051106 getTokenObject(collectionId: number, tokenId: number): any {1107 return null;1108 }1109}111011111112class NFTGroup extends NFTnRFT {1113 111411151116111711181119 getCollectionObject(collectionId: number): UniqueNFTCollection {1120 return new UniqueNFTCollection(collectionId, this.helper);1121 }11221123 1124112511261127112811291130 getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1131 return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1132 }11331134 11351136113711381139114011411142 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1143 let owner;1144 if (typeof blockHashAt === 'undefined') {1145 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1146 } else {1147 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1148 }1149 return crossAccountIdFromLower(owner.toJSON());1150 }11511152 1153115411551156115711581159 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1160 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1161 }11621163 1164116511661167116811691170117111721173 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1174 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1175 }11761177 117811791180118111821183118411851186118711881189 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1190 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1191 }11921193 11941195119611971198119912001201 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1202 let owner;1203 if (typeof blockHashAt === 'undefined') {1204 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1205 } else {1206 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1207 }12081209 if (owner === null) return null;12101211 owner = owner.toHuman();12121213 return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1214 }12151216 12171218121912201221122212231224 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1225 let children;1226 if(typeof blockHashAt === 'undefined') {1227 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1228 } else {1229 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1230 }12311232 return children.toJSON().map((x: any) => {1233 return {collectionId: x.collection, tokenId: x.token};1234 });1235 }12361237 123812391240124112421243124412451246 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, label='nest token'): Promise<boolean> {1247 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1248 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1249 if(!result) {1250 throw Error(`Unable to nest token for ${label}`);1251 }1252 return result;1253 }12541255 1256125712581259126012611262126312641265 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId, label='unnest token'): Promise<boolean> {1266 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1267 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1268 if(!result) {1269 throw Error(`Unable to unnest token for ${label}`);1270 }1271 return result;1272 }12731274 1275127612771278127912801281128212831284128512861287 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueNFTCollection> {1288 return await super.mintCollection(signer, collectionOptions, 'NFT', `Unable to mint NFT collection for ${label}`) as UniqueNFTCollection;1289 }12901291 1292129312941295129612971298 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }, label?: string): Promise<UniqueNFTToken> {1299 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1300 const creationResult = await this.helper.executeExtrinsic(1301 signer,1302 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1303 nft: {1304 properties: data.properties,1305 },1306 }],1307 true, `Unable to mint NFT token for ${label}`,1308 );1309 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1310 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1311 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1312 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1313 }13141315 1316131713181319132013211322132313241325132613271328132913301331 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1332 if(typeof label === 'undefined') label = `collection #${collectionId}`;1333 const creationResult = await this.helper.executeExtrinsic(1334 signer,1335 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1336 true, `Unable to mint NFT tokens for ${label}`,1337 );1338 const collection = this.getCollectionObject(collectionId);1339 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1340 }13411342 1343134413451346134713481349135013511352135313541355135613571358135913601361 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1362 if(typeof label === 'undefined') label = `collection #${collectionId}`;1363 const rawTokens = [];1364 for (const token of tokens) {1365 const raw = {NFT: {properties: token.properties}};1366 rawTokens.push(raw);1367 }1368 const creationResult = await this.helper.executeExtrinsic(1369 signer,1370 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1371 true, `Unable to mint NFT tokens for ${label}`,1372 );1373 const collection = this.getCollectionObject(collectionId);1374 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1375 }13761377 137813791380138113821383138413851386 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string): Promise<{ success: boolean; token: number | null; }> {1387 return await super.burnToken(signer, collectionId, tokenId, label, 1n);1388 }13891390 13911392139313941395139613971398139914001401 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {1402 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, 1n);1403 }1404}140514061407class RFTGroup extends NFTnRFT {1408 140914101411141214131414 getCollectionObject(collectionId: number): UniqueRFTCollection {1415 return new UniqueRFTCollection(collectionId, this.helper);1416 }14171418 1419142014211422142314241425 getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1426 return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1427 }14281429 1430143114321433143414351436 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1437 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1438 }14391440 14411442144314441445144614471448 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1449 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1450 }14511452 1453145414551456145714581459146014611462 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=100n): Promise<boolean> {1463 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1464 }14651466 14671468146914701471147214731474147514761477 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n): Promise<boolean> {1478 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1479 }14801481 1482148314841485148614871488148914901491149214931494 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueRFTCollection> {1495 return await super.mintCollection(signer, collectionOptions, 'RFT', `Unable to mint RFT collection for ${label}`) as UniqueRFTCollection;1496 }14971498 14991500150115021503150415051506 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }, label?: string): Promise<UniqueRFTToken> {1507 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1508 const creationResult = await this.helper.executeExtrinsic(1509 signer,1510 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1511 refungible: {1512 pieces: data.pieces,1513 properties: data.properties,1514 },1515 }],1516 true, `Unable to mint RFT token for ${label}`,1517 );1518 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1519 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1520 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1521 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1522 }15231524 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1525 throw Error('Not implemented');1526 if(typeof label === 'undefined') label = `collection #${collectionId}`;1527 const creationResult = await this.helper.executeExtrinsic(1528 signer,1529 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1530 true, `Unable to mint RFT tokens for ${label}`,1531 );1532 const collection = this.getCollectionObject(collectionId);1533 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1534 }15351536 1537153815391540154115421543154415451546 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1547 if(typeof label === 'undefined') label = `collection #${collectionId}`;1548 const rawTokens = [];1549 for (const token of tokens) {1550 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1551 rawTokens.push(raw);1552 }1553 const creationResult = await this.helper.executeExtrinsic(1554 signer,1555 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1556 true, `Unable to mint RFT tokens for ${label}`,1557 );1558 const collection = this.getCollectionObject(collectionId);1559 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1560 }15611562 1563156415651566156715681569157015711572 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string, amount=100n): Promise<{ success: boolean; token: number | null; }> {1573 return await super.burnToken(signer, collectionId, tokenId, label, amount);1574 }15751576 157715781579158015811582158315841585158615871588 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=100n) {1589 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, amount);1590 }15911592 1593159415951596159715981599 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1600 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1601 }16021603 1604160516061607160816091610161116121613 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint, label?: string): Promise<boolean> {1614 if(typeof label === 'undefined') label = `collection #${collectionId}`;1615 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1616 const repartitionResult = await this.helper.executeExtrinsic(1617 signer,1618 'api.tx.unique.repartition', [collectionId, tokenId, amount],1619 true, `Unable to repartition RFT token for ${label}`,1620 );1621 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated', label);1622 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed', label);1623 }1624}162516261627class FTGroup extends CollectionGroup {1628 162916301631163216331634 getCollectionObject(collectionId: number): UniqueFTCollection {1635 return new UniqueFTCollection(collectionId, this.helper);1636 }16371638 16391640164116421643164416451646164716481649165016511652 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0, errorLabel = 'Unable to mint collection'): Promise<UniqueFTCollection> {1653 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1654 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1655 collectionOptions.mode = {fungible: decimalPoints};1656 for (const key of ['name', 'description', 'tokenPrefix']) {1657 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);1658 }1659 const creationResult = await this.helper.executeExtrinsic(1660 signer,1661 'api.tx.unique.createCollectionEx', [collectionOptions],1662 true, errorLabel,1663 );1664 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1665 }16661667 1668166916701671167216731674167516761677 async mintTokens(signer: TSigner, collectionId: number, owner: ICrossAccountId | string, amount: bigint, label?: string): Promise<boolean> {1678 if(typeof label === 'undefined') label = `collection #${collectionId}`;1679 const creationResult = await this.helper.executeExtrinsic(1680 signer,1681 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1682 fungible: {1683 value: amount,1684 },1685 }],1686 true, `Unable to mint fungible tokens for ${label}`,1687 );1688 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1689 }16901691 169216931694169516961697169816991700 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string): Promise<boolean> {1701 if(typeof label === 'undefined') label = `collection #${collectionId}`;1702 const rawTokens = [];1703 for (const token of tokens) {1704 const raw = {Fungible: {Value: token.value}};1705 rawTokens.push(raw);1706 }1707 const creationResult = await this.helper.executeExtrinsic(1708 signer,1709 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1710 true, `Unable to mint RFT tokens for ${label}`,1711 );1712 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1713 }17141715 171617171718171917201721 async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1722 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1723 }17241725 1726172717281729173017311732 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1733 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1734 }17351736 173717381739174017411742174317441745 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount: bigint) {1746 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1747 }17481749 1750175117521753175417551756175717581759 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {1760 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1761 }17621763 176417651766176717681769177017711772 async burnTokens(signer: IKeyringPair, collectionId: number, amount=100n, label?: string): Promise<boolean> {1773 return (await super.burnToken(signer, collectionId, 0, label, amount)).success;1774 }17751776 1777177817791780178117821783178417851786 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=100n, label?: string): Promise<boolean> {1787 return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, label, amount);1788 }17891790 17911792179317941795 async getTotalPieces(collectionId: number): Promise<bigint> {1796 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1797 }17981799 18001801180218031804180518061807180818091810 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {1811 return super.approveToken(signer, collectionId, 0, toAddressObj, label, amount);1812 }18131814 1815181618171818181918201821 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1822 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1823 }1824}182518261827class ChainGroup extends HelperGroup {1828 18291830183118321833 getChainProperties(): IChainProperties {1834 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1835 return {1836 ss58Format: properties.ss58Format.toJSON(),1837 tokenDecimals: properties.tokenDecimals.toJSON(),1838 tokenSymbol: properties.tokenSymbol.toJSON(),1839 };1840 }18411842 18431844184518461847 async getLatestBlockNumber(): Promise<number> {1848 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1849 }18501851 185218531854185518561857 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1858 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1859 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1860 return blockHash;1861 }18621863 186418651866186718681869 async getNonce(address: TSubstrateAccount): Promise<number> {1870 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1871 }1872}187318741875class BalanceGroup extends HelperGroup {1876 18771878187918801881 getOneTokenNominal(): bigint {1882 const chainProperties = this.helper.chain.getChainProperties();1883 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1884 }18851886 188718881889189018911892 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {1893 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();1894 }18951896 189718981899190019011902 async getEthereum(address: TEthereumAccount): Promise<bigint> {1903 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();1904 }19051906 19071908190919101911191219131914 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {1915 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}`);19161917 let transfer = {from: null, to: null, amount: 0n} as any;1918 result.result.events.forEach(({event: {data, method, section}}) => {1919 if ((section === 'balances') && (method === 'Transfer')) {1920 transfer = {1921 from: this.helper.address.normalizeSubstrate(data[0]),1922 to: this.helper.address.normalizeSubstrate(data[1]),1923 amount: BigInt(data[2]),1924 };1925 }1926 });1927 let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;1928 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;1929 isSuccess = isSuccess && BigInt(amount) === transfer.amount;1930 return isSuccess;1931 }1932}193319341935class AddressGroup extends HelperGroup {1936 1937193819391940194119421943 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {1944 return this.helper.util.normalizeSubstrateAddress(address, ss58Format);1945 }19461947 194819491950195119521953 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {1954 const info = this.helper.chain.getChainProperties();1955 return encodeAddress(decodeAddress(address), info.ss58Format);1956 }19571958 1959196019611962196319641965 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {1966 if(!toChainFormat) return evmToAddress(ethAddress);1967 const info = this.helper.chain.getChainProperties();1968 return evmToAddress(ethAddress, info.ss58Format);1969 }19701971 197219731974197519761977 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {1978 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));1979 }1980}19811982class StakingGroup extends HelperGroup {1983 1984198519861987198819891990 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {1991 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;1992 const stakeResult = await this.helper.executeExtrinsic(1993 signer,1994 'api.tx.promotion.stake', [amountToStake],1995 true, `stake failed for ${label}`,1996 );1997 1998 return true;1999 }20002001 2002200320042005200620072008 async unstake(signer: TSigner, amountToUnstake: bigint, label?: string): Promise<boolean> {2009 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToUnstake}`;2010 const unstakeResult = await this.helper.executeExtrinsic(2011 signer,2012 'api.tx.promotion.unstake', [amountToUnstake],2013 true, `unstake failed for ${label}`,2014 );2015 2016 return true;2017 }20182019 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2020 if (address) return (await this.helper.callRpc('api.rpc.unique.totalStaked', [address])).toBigInt();2021 return (await this.helper.callRpc('api.rpc.unique.totalStaked')).toBigInt();2022 }20232024 async getTotalStakingLocked(address: ICrossAccountId): Promise<bigint> {2025 return (await this.helper.callRpc('api.rpc.unique.totalStakingLocked', [address])).toBigInt();2026 }20272028 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<bigint[][]> {2029 return (await this.helper.callRpc('api.rpc.unique.totalStakedPerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);2030 }20312032 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2033 return (await this.helper.callRpc('api.rpc.unique.pendingUnstake')).toBigInt();2034 }2035}20362037export class UniqueHelper extends ChainHelperBase {2038 chain: ChainGroup;2039 balance: BalanceGroup;2040 address: AddressGroup;2041 collection: CollectionGroup;2042 nft: NFTGroup;2043 rft: RFTGroup;2044 ft: FTGroup;2045 staking: StakingGroup;20462047 constructor(logger?: ILogger) {2048 super(logger);2049 this.chain = new ChainGroup(this);2050 this.balance = new BalanceGroup(this);2051 this.address = new AddressGroup(this);2052 this.collection = new CollectionGroup(this);2053 this.nft = new NFTGroup(this);2054 this.rft = new RFTGroup(this);2055 this.ft = new FTGroup(this);2056 this.staking = new StakingGroup(this);2057 } 2058}205920602061class UniqueCollectionBase {2062 helper: UniqueHelper;2063 collectionId: number;20642065 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2066 this.collectionId = collectionId;2067 this.helper = uniqueHelper;2068 }20692070 async getData() {2071 return await this.helper.collection.getData(this.collectionId);2072 }20732074 async getLastTokenId() {2075 return await this.helper.collection.getLastTokenId(this.collectionId);2076 }20772078 async isTokenExists(tokenId: number) {2079 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2080 }20812082 async getAdmins() {2083 return await this.helper.collection.getAdmins(this.collectionId);2084 }20852086 async getAllowList() {2087 return await this.helper.collection.getAllowList(this.collectionId);2088 }20892090 async getEffectiveLimits() {2091 return await this.helper.collection.getEffectiveLimits(this.collectionId);2092 }20932094 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount, label?: string) {2095 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress, label);2096 }20972098 async confirmSponsorship(signer: TSigner, label?: string) {2099 return await this.helper.collection.confirmSponsorship(signer, this.collectionId, label);2100 }21012102 async setLimits(signer: TSigner, limits: ICollectionLimits, label?: string) {2103 return await this.helper.collection.setLimits(signer, this.collectionId, limits, label);2104 }21052106 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount, label?: string) {2107 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress, label);2108 }21092110 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {2111 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj, label);2112 }21132114 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId, label?: string) {2115 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj, label);2116 }21172118 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {2119 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj, label);2120 }21212122 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {2123 return await this.helper.collection.setProperties(signer, this.collectionId, properties, label);2124 }21252126 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {2127 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys, label);2128 }21292130 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2131 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2132 }21332134 async setPermissions(signer: TSigner, permissions: ICollectionPermissions, label?: string) {2135 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions, label);2136 }21372138 async enableNesting(signer: TSigner, permissions: INestingPermissions, label?: string) {2139 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions, label);2140 }21412142 async disableNesting(signer: TSigner, label?: string) {2143 return await this.helper.collection.disableNesting(signer, this.collectionId, label);2144 }21452146 async burn(signer: TSigner, label?: string) {2147 return await this.helper.collection.burn(signer, this.collectionId, label);2148 }2149}215021512152class UniqueNFTCollection extends UniqueCollectionBase {2153 getTokenObject(tokenId: number) {2154 return new UniqueNFTToken(tokenId, this);2155 }21562157 async getTokensByAddress(addressObj: ICrossAccountId) {2158 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2159 }21602161 async getToken(tokenId: number, blockHashAt?: string) {2162 return await this.helper.nft.getToken(this.collectionId, tokenId, blockHashAt);2163 }21642165 async getTokenOwner(tokenId: number, blockHashAt?: string) {2166 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2167 }21682169 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2170 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2171 }21722173 async getTokenChildren(tokenId: number, blockHashAt?: string) {2174 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2175 }21762177 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2178 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2179 }21802181 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2182 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2183 }21842185 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {2186 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label);2187 }21882189 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2190 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2191 }21922193 async mintToken(signer: TSigner, owner: ICrossAccountId, properties?: IProperty[], label?: string) {2194 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties}, label);2195 }21962197 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string) {2198 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens, label);2199 }22002201 async burnToken(signer: TSigner, tokenId: number, label?: string) {2202 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId, label);2203 }22042205 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {2206 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);2207 }22082209 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {2210 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);2211 }22122213 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {2214 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);2215 }22162217 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken, label?: string) {2218 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj, label);2219 }22202221 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {2222 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj, label);2223 }2224}222522262227class UniqueRFTCollection extends UniqueCollectionBase {2228 getTokenObject(tokenId: number) {2229 return new UniqueRFTToken(tokenId, this);2230 }22312232 async getTokensByAddress(addressObj: ICrossAccountId) {2233 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2234 }22352236 async getTop10TokenOwners(tokenId: number) {2237 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2238 }22392240 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2241 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2242 }22432244 async getTokenTotalPieces(tokenId: number) {2245 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2246 }22472248 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=100n) {2249 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2250 }22512252 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {2253 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2254 }22552256 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2257 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label, amount);2258 }22592260 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2261 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2262 }22632264 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint, label?: string) {2265 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount, label);2266 }22672268 async mintToken(signer: TSigner, owner: ICrossAccountId, pieces=100n, properties?: IProperty[], label?: string) {2269 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties}, label);2270 }22712272 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string) {2273 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens, label);2274 }22752276 async burnToken(signer: TSigner, tokenId: number, amount=100n, label?: string) {2277 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, label, amount);2278 }22792280 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {2281 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);2282 }22832284 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {2285 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);2286 }22872288 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {2289 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);2290 }2291}229222932294class UniqueFTCollection extends UniqueCollectionBase {2295 async mint(signer: TSigner, owner: ICrossAccountId, amount: bigint, label?: string) {2296 return await this.helper.ft.mintTokens(signer, this.collectionId, owner, amount, label);2297 }22982299 async mintWithOneOwner(signer: TSigner, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string) {2300 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, owner, tokens, label);2301 }23022303 async getBalance(addressObj: ICrossAccountId) {2304 return await this.helper.ft.getBalance(this.collectionId, addressObj);2305 }23062307 async getTop10Owners() {2308 return await this.helper.ft.getTop10Owners(this.collectionId);2309 }23102311 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount: bigint) {2312 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2313 }23142315 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {2316 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2317 }23182319 async burnTokens(signer: TSigner, amount: bigint, label?: string) {2320 return await this.helper.ft.burnTokens(signer, this.collectionId, amount, label);2321 }23222323 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount: bigint, label?: string) {2324 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount, label);2325 }23262327 async getTotalPieces() {2328 return await this.helper.ft.getTotalPieces(this.collectionId);2329 }23302331 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2332 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount, label);2333 }23342335 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2336 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2337 }2338}233923402341class UniqueTokenBase implements IToken {2342 collection: UniqueNFTCollection | UniqueRFTCollection;2343 collectionId: number;2344 tokenId: number;23452346 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2347 this.collection = collection;2348 this.collectionId = collection.collectionId;2349 this.tokenId = tokenId;2350 }23512352 async getNextSponsored(addressObj: ICrossAccountId) {2353 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2354 }23552356 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {2357 return await this.collection.setTokenProperties(signer, this.tokenId, properties, label);2358 }23592360 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {2361 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys, label);2362 }2363}236423652366class UniqueNFTToken extends UniqueTokenBase {2367 collection: UniqueNFTCollection;23682369 constructor(tokenId: number, collection: UniqueNFTCollection) {2370 super(tokenId, collection);2371 this.collection = collection;2372 }23732374 async getData(blockHashAt?: string) {2375 return await this.collection.getToken(this.tokenId, blockHashAt);2376 }23772378 async getOwner(blockHashAt?: string) {2379 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2380 }23812382 async getTopmostOwner(blockHashAt?: string) {2383 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2384 }23852386 async getChildren(blockHashAt?: string) {2387 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2388 }23892390 async nest(signer: TSigner, toTokenObj: IToken, label?: string) {2391 return await this.collection.nestToken(signer, this.tokenId, toTokenObj, label);2392 }23932394 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {2395 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj, label);2396 }23972398 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2399 return await this.collection.transferToken(signer, this.tokenId, addressObj);2400 }24012402 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2403 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2404 }24052406 async approve(signer: TSigner, toAddressObj: ICrossAccountId, label?: string) {2407 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, label);2408 }24092410 async isApproved(toAddressObj: ICrossAccountId) {2411 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2412 }24132414 async burn(signer: TSigner, label?: string) {2415 return await this.collection.burnToken(signer, this.tokenId, label);2416 }2417}24182419class UniqueRFTToken extends UniqueTokenBase {2420 collection: UniqueRFTCollection;24212422 constructor(tokenId: number, collection: UniqueRFTCollection) {2423 super(tokenId, collection);2424 this.collection = collection;2425 }24262427 async getTop10Owners() {2428 return await this.collection.getTop10TokenOwners(this.tokenId);2429 }24302431 async getBalance(addressObj: ICrossAccountId) {2432 return await this.collection.getTokenBalance(this.tokenId, addressObj);2433 }24342435 async getTotalPieces() {2436 return await this.collection.getTokenTotalPieces(this.tokenId);2437 }24382439 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=100n) {2440 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2441 }24422443 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {2444 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2445 }24462447 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2448 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount, label);2449 }24502451 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2452 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2453 }24542455 async repartition(signer: TSigner, amount: bigint, label?: string) {2456 return await this.collection.repartitionToken(signer, this.tokenId, amount, label);2457 }24582459 async burn(signer: TSigner, amount=100n, label?: string) {2460 return await this.collection.burnToken(signer, this.tokenId, amount, label);2461 }2462}