12345import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';6import {ApiInterfaceEvents} from '@polkadot/api/types';7import {IKeyringPair} from '@polkadot/types/types';8import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';91011const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {12 const address = {} as ICrossAccountId;13 if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;14 if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;15 return address;16};171819const nesting = {20 toChecksumAddress(address: string): string {21 if (typeof address === 'undefined') return '';2223 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);2425 address = address.toLowerCase().replace(/^0x/i,'');26 const addressHash = keccakAsHex(address).replace(/^0x/i,'');27 const checksumAddress = ['0x'];2829 for (let i = 0; i < address.length; i++) {30 31 if (parseInt(addressHash[i], 16) > 7) {32 checksumAddress.push(address[i].toUpperCase());33 } else {34 checksumAddress.push(address[i]);35 }36 }37 return checksumAddress.join('');38 },39 tokenIdToAddress(collectionId: number, tokenId: number) {40 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);41 },42};434445interface IChainEvent {46 data: any;47 method: string;48 section: string;49}5051interface ITransactionResult {52 status: 'Fail' | 'Success';53 result: {54 events: {55 event: IChainEvent56 }[];57 },58 moduleError?: string;59}6061interface ILogger {62 log: (msg: any, level?: string) => void;63 level: {64 ERROR: 'ERROR';65 WARNING: 'WARNING';66 INFO: 'INFO';67 [key: string]: string;68 }69}7071interface IUniqueHelperLog {72 executedAt: number;73 executionTime: number;74 type: 'extrinsic' | 'rpc';75 status: 'Fail' | 'Success';76 call: string;77 params: any[];78 moduleError?: string;79 events?: any;80}8182interface IApiListeners {83 connected?: (...args: any[]) => any;84 disconnected?: (...args: any[]) => any;85 error?: (...args: any[]) => any;86 ready?: (...args: any[]) => any; 87 decorated?: (...args: any[]) => any;88}8990interface ICrossAccountId {91 Substrate?: TSubstrateAccount;92 Ethereum?: TEthereumAccount;93}9495interface ICrossAccountIdLower {96 substrate?: TSubstrateAccount;97 ethereum?: TEthereumAccount;98}99100interface ICollectionLimits {101 accountTokenOwnershipLimit?: number | null;102 sponsoredDataSize?: number | null;103 sponsoredDataRateLimit?: {blocks: number} | {sponsoringDisabled: null} | null;104 tokenLimit?: number | null;105 sponsorTransferTimeout?: number | null;106 sponsorApproveTimeout?: number | null;107 ownerCanTransfer?: boolean | null;108 ownerCanDestroy?: boolean | null;109 transfersEnabled?: boolean | null;110}111112interface INestingPermissions {113 tokenOwner?: boolean;114 collectionAdmin?: boolean;115 restricted?: number[] | null;116}117118interface ICollectionPermissions {119 access?: 'Normal' | 'AllowList';120 mintMode?: boolean;121 nesting?: INestingPermissions;122}123124interface IProperty {125 key: string;126 value: string;127}128129interface ITokenPropertyPermission {130 key: string;131 permission: {132 mutable: boolean;133 tokenOwner: boolean;134 collectionAdmin: boolean;135 }136}137138interface IToken {139 collectionId: number;140 tokenId: number;141}142143interface ICollectionCreationOptions {144 name: string | number[];145 description: string | number[];146 tokenPrefix: string | number[];147 mode?: {148 nft?: null;149 refungible?: null;150 fungible?: number;151 }152 permissions?: ICollectionPermissions;153 properties?: IProperty[];154 tokenPropertyPermissions?: ITokenPropertyPermission[];155 limits?: ICollectionLimits;156 pendingSponsor?: TSubstrateAccount;157}158159interface IChainProperties {160 ss58Format: number;161 tokenDecimals: number[];162 tokenSymbol: string[]163}164165type TSubstrateAccount = string;166type TEthereumAccount = string;167type TApiAllowedListeners = 'connected' | 'disconnected' | 'error' | 'ready' | 'decorated';168type TUniqueNetworks = 'opal' | 'quartz' | 'unique';169type TSigner = IKeyringPair; 170171class UniqueUtil {172 static transactionStatus = {173 NOT_READY: 'NotReady',174 FAIL: 'Fail',175 SUCCESS: 'Success',176 };177178 static chainLogType = {179 EXTRINSIC: 'extrinsic',180 RPC: 'rpc',181 };182183 static getNestingTokenAddress(collectionId: number, tokenId: number) {184 return nesting.tokenIdToAddress(collectionId, tokenId);185 }186187 static getDefaultLogger(): ILogger {188 return {189 log(msg: any, level = 'INFO') {190 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));191 },192 level: {193 ERROR: 'ERROR',194 WARNING: 'WARNING',195 INFO: 'INFO',196 },197 };198 }199200 static vec2str(arr: string[] | number[]) {201 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');202 }203204 static str2vec(string: string) {205 if (typeof string !== 'string') return string;206 return Array.from(string).map(x => x.charCodeAt(0));207 }208209 static fromSeed(seed: string, ss58Format = 42) {210 const keyring = new Keyring({type: 'sr25519', ss58Format});211 return keyring.addFromUri(seed);212 }213214 static normalizeSubstrateAddress(address: string, ss58Format = 42) {215 return encodeAddress(decodeAddress(address), ss58Format);216 }217218 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult, label = 'new collection') {219 if (creationResult.status !== this.transactionStatus.SUCCESS) {220 throw Error(`Unable to create collection for ${label}`);221 }222223 let collectionId = null;224 creationResult.result.events.forEach(({event: {data, method, section}}) => {225 if ((section === 'common') && (method === 'CollectionCreated')) {226 collectionId = parseInt(data[0].toString(), 10);227 }228 });229230 if (collectionId === null) {231 throw Error(`No CollectionCreated event for ${label}`);232 }233234 return collectionId;235 }236237 static extractTokensFromCreationResult(creationResult: ITransactionResult, label = 'new tokens') {238 if (creationResult.status !== this.transactionStatus.SUCCESS) {239 throw Error(`Unable to create tokens for ${label}`);240 }241 let success = false;242 const tokens = [] as any;243 creationResult.result.events.forEach(({event: {data, method, section}}) => {244 if (method === 'ExtrinsicSuccess') {245 success = true;246 } else if ((section === 'common') && (method === 'ItemCreated')) {247 tokens.push({248 collectionId: parseInt(data[0].toString(), 10),249 tokenId: parseInt(data[1].toString(), 10),250 owner: data[2].toJSON(),251 });252 }253 });254 return {success, tokens};255 }256257 static extractTokensFromBurnResult(burnResult: ITransactionResult, label = 'burned tokens') {258 if (burnResult.status !== this.transactionStatus.SUCCESS) {259 throw Error(`Unable to burn tokens for ${label}`);260 }261 let success = false;262 const tokens = [] as any;263 burnResult.result.events.forEach(({event: {data, method, section}}) => {264 if (method === 'ExtrinsicSuccess') {265 success = true;266 } else if ((section === 'common') && (method === 'ItemDestroyed')) {267 tokens.push({268 collectionId: parseInt(data[0].toString(), 10),269 tokenId: parseInt(data[1].toString(), 10),270 owner: data[2].toJSON(),271 });272 }273 });274 return {success, tokens};275 }276277 static findCollectionInEvents(events: {event: IChainEvent}[], collectionId: number, expectedSection: string, expectedMethod: string, label?: string) {278 let eventId = null;279 events.forEach(({event: {data, method, section}}) => {280 if ((section === expectedSection) && (method === expectedMethod)) {281 eventId = parseInt(data[0].toString(), 10);282 }283 });284285 if (eventId === null) {286 throw Error(`No ${expectedMethod} event for ${label}`);287 }288 return eventId === collectionId;289 }290291 static isTokenTransferSuccess(events: {event: IChainEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {292 const normalizeAddress = (address: string | ICrossAccountId) => {293 if(typeof address === 'string') return address;294 const obj = {} as any;295 Object.keys(address).forEach(k => {296 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];297 });298 if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};299 if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};300 return address;301 };302 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;303 events.forEach(({event: {data, method, section}}) => {304 if ((section === 'common') && (method === 'Transfer')) {305 const hData = (data as any).toJSON();306 transfer = {307 collectionId: hData[0],308 tokenId: hData[1],309 from: normalizeAddress(hData[2]),310 to: normalizeAddress(hData[3]),311 amount: BigInt(hData[4]),312 };313 }314 });315 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;316 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);317 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);318 isSuccess = isSuccess && amount === transfer.amount;319 return isSuccess;320 }321}322323324class ChainHelperBase {325 transactionStatus = UniqueUtil.transactionStatus;326 chainLogType = UniqueUtil.chainLogType;327 util: typeof UniqueUtil;328 logger: ILogger;329 api: ApiPromise | null;330 forcedNetwork: TUniqueNetworks | null;331 network: TUniqueNetworks | null;332 chainLog: IUniqueHelperLog[];333334 constructor(logger?: ILogger) {335 this.util = UniqueUtil;336 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();337 this.logger = logger;338 this.api = null;339 this.forcedNetwork = null;340 this.network = null;341 this.chainLog = [];342 }343344 clearChainLog(): void {345 this.chainLog = [];346 }347348 forceNetwork(value: TUniqueNetworks): void {349 this.forcedNetwork = value;350 }351352 async connect(wsEndpoint: string, listeners?: IApiListeners) {353 if (this.api !== null) throw Error('Already connected');354 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);355 this.api = api;356 this.network = network;357 }358359 async disconnect() {360 if (this.api === null) return;361 await this.api.disconnect();362 this.api = null;363 this.network = null;364 }365366 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {367 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;368 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;369 return 'opal';370 }371372 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {373 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});374 await api.isReady;375376 const network = await this.detectNetwork(api);377378 await api.disconnect();379380 return network;381 }382383 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{ 384 api: ApiPromise; 385 network: TUniqueNetworks; 386 }> {387 if(typeof network === 'undefined' || network === null) network = 'opal';388 const supportedRPC = {389 opal: {390 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,391 },392 quartz: {393 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,394 },395 unique: {396 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,397 },398 };399 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);400 const rpc = supportedRPC[network];401402 403 404405 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});406407 await api.isReadyOrError;408409 if (typeof listeners === 'undefined') listeners = {};410 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {411 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;412 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);413 }414415 return {api, network};416 }417418 getTransactionStatus(data: {events: {event: IChainEvent}[], status: any}) {419 const {events, status} = data;420 if (status.isReady) {421 return this.transactionStatus.NOT_READY;422 }423 if (status.isBroadcast) {424 return this.transactionStatus.NOT_READY;425 }426 if (status.isInBlock || status.isFinalized) {427 const errors = events.filter(e => e.event.data.method === 'ExtrinsicFailed');428 if (errors.length > 0) {429 return this.transactionStatus.FAIL;430 }431 if (events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {432 return this.transactionStatus.SUCCESS;433 }434 }435436 return this.transactionStatus.FAIL;437 }438439 signTransaction(sender: TSigner, transaction: any, label = 'transaction', options = null) {440 const sign = (callback: any) => {441 if(options !== null) return transaction.signAndSend(sender, options, callback);442 return transaction.signAndSend(sender, callback);443 };444 return new Promise(async (resolve, reject) => {445 try {446 const unsub = await sign((result: any) => {447 const status = this.getTransactionStatus(result);448449 if (status === this.transactionStatus.SUCCESS) {450 this.logger.log(`${label} successful`);451 unsub();452 resolve({result, status});453 } else if (status === this.transactionStatus.FAIL) {454 let moduleError = null;455456 if (result.hasOwnProperty('dispatchError')) {457 const dispatchError = result['dispatchError'];458459 if (dispatchError && dispatchError.isModule) {460 const modErr = dispatchError.asModule;461 const errorMeta = dispatchError.registry.findMetaError(modErr);462463 moduleError = `${errorMeta.section}.${errorMeta.name}`;464 }465 else {466 this.logger.log(result, this.logger.level.ERROR);467 }468 }469470 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);471 unsub();472 reject({status, moduleError, result});473 }474 });475 } catch (e) {476 this.logger.log(e, this.logger.level.ERROR);477 reject(e);478 }479 });480 }481482 constructApiCall(apiCall: string, params: any[]) {483 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);484 let call = this.api as any;485 for(const part of apiCall.slice(4).split('.')) {486 call = call[part];487 }488 return call(...params);489 }490491 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=false, failureMessage='expected success') {492 if(this.api === null) throw Error('API not initialized');493 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);494495 const startTime = (new Date()).getTime();496 let result: ITransactionResult;497 let events = [];498 try {499 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), extrinsic) as ITransactionResult;500 events = result.result.events.map((x: any) => x.toHuman());501 }502 catch(e) {503 if(!(e as object).hasOwnProperty('status')) throw e;504 result = e as ITransactionResult;505 }506507 const endTime = (new Date()).getTime();508509 const log = {510 executedAt: endTime,511 executionTime: endTime - startTime,512 type: this.chainLogType.EXTRINSIC,513 status: result.status,514 call: extrinsic,515 params,516 } as IUniqueHelperLog;517518 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;519 if(events.length > 0) log.events = events;520521 this.chainLog.push(log);522523 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(failureMessage);524 return result;525 }526527 async callRpc(rpc: string, params?: any[]) {528 if(typeof params === 'undefined') params = [];529 if(this.api === null) throw Error('API not initialized');530 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);531532 const startTime = (new Date()).getTime();533 let result;534 let error = null;535 const log = {536 type: this.chainLogType.RPC,537 call: rpc,538 params,539 } as IUniqueHelperLog;540541 try {542 result = await this.constructApiCall(rpc, params);543 }544 catch(e) {545 error = e;546 }547548 const endTime = (new Date()).getTime();549550 log.executedAt = endTime;551 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';552 log.executionTime = endTime - startTime;553554 this.chainLog.push(log);555556 if(error !== null) throw error;557558 return result;559 }560561 getSignerAddress(signer: IKeyringPair | string): string {562 if(typeof signer === 'string') return signer;563 return signer.address;564 }565}566567568class HelperGroup {569 helper: UniqueHelper;570571 constructor(uniqueHelper: UniqueHelper) {572 this.helper = uniqueHelper;573 }574}575576577class CollectionGroup extends HelperGroup {578 579580581582583584585586587 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {588 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();589 }590591 592593594595596 async getTotalCount(): Promise<number> {597 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();598 }599600 601602603604605606607 async getData(collectionId: number): Promise<{608 id: number;609 name: string;610 description: string;611 tokensCount: number;612 admins: ICrossAccountId[];613 normalizedOwner: TSubstrateAccount;614 raw: any615 } | null> {616 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);617 const humanCollection = collection.toHuman(), collectionData = {618 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],619 raw: humanCollection,620 } as any, jsonCollection = collection.toJSON();621 if (humanCollection === null) return null;622 collectionData.raw.limits = jsonCollection.limits;623 collectionData.raw.permissions = jsonCollection.permissions;624 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);625 for (const key of ['name', 'description']) {626 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);627 }628629 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode)) ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId) : 0;630 collectionData.admins = await this.getAdmins(collectionId);631632 return collectionData;633 }634635 636637638639640641642 async getAdmins(collectionId: number): Promise<ICrossAccountId[]> {643 const normalized = [];644 for(const admin of (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman()) {645 if(admin.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(admin.Substrate)});646 else normalized.push(admin);647 }648 return normalized;649 }650651 652653654655656657658 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {659 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();660 }661662 663664665666667668669670671 async burn(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {672 if(typeof label === 'undefined') label = `collection #${collectionId}`;673 const result = await this.helper.executeExtrinsic(674 signer,675 'api.tx.unique.destroyCollection', [collectionId],676 true, `Unable to burn collection for ${label}`,677 );678679 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed', label);680 }681682 683684685686687688689690691692 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount, label?: string): Promise<boolean> {693 if(typeof label === 'undefined') label = `collection #${collectionId}`;694 const result = await this.helper.executeExtrinsic(695 signer,696 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],697 true, `Unable to set collection sponsor for ${label}`,698 );699700 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet', label);701 }702703 704705706707708709710711712 async confirmSponsorship(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {713 if(typeof label === 'undefined') label = `collection #${collectionId}`;714 const result = await this.helper.executeExtrinsic(715 signer,716 'api.tx.unique.confirmSponsorship', [collectionId],717 true, `Unable to confirm collection sponsorship for ${label}`,718 );719720 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed', label);721 }722723 724725726727728729730731732733734735736737738739740741 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits, label?: string): Promise<boolean> {742 if(typeof label === 'undefined') label = `collection #${collectionId}`;743 const result = await this.helper.executeExtrinsic(744 signer,745 'api.tx.unique.setCollectionLimits', [collectionId, limits],746 true, `Unable to set collection limits for ${label}`,747 );748749 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet', label);750 }751752 753754755756757758759760761762 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount, label?: string): Promise<boolean> {763 if(typeof label === 'undefined') label = `collection #${collectionId}`;764 const result = await this.helper.executeExtrinsic(765 signer,766 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],767 true, `Unable to change collection owner for ${label}`,768 );769770 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged', label);771 }772773 774775776777778779780781782783 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {784 if(typeof label === 'undefined') label = `collection #${collectionId}`;785 const result = await this.helper.executeExtrinsic(786 signer,787 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],788 true, `Unable to add collection admin for ${label}`,789 );790791 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded', label);792 }793794 795796797798799800801802803804 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {805 if(typeof label === 'undefined') label = `collection #${collectionId}`;806 const result = await this.helper.executeExtrinsic(807 signer,808 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],809 true, `Unable to remove collection admin for ${label}`,810 );811812 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved', label);813 }814815 816817818819820821822823824825 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions, label?: string): Promise<boolean> {826 if(typeof label === 'undefined') label = `collection #${collectionId}`;827 const result = await this.helper.executeExtrinsic(828 signer,829 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],830 true, `Unable to set collection permissions for ${label}`,831 );832833 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet', label);834 }835836 837838839840841842843844845846 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions, label?: string): Promise<boolean> {847 return await this.setPermissions(signer, collectionId, {nesting: permissions}, label);848 }849850 851852853854855856857858859 async disableNesting(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {860 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}}, label);861 }862863 864865866867868869870871872873874 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[], label?: string): Promise<boolean> {875 if(typeof label === 'undefined') label = `collection #${collectionId}`;876 const result = await this.helper.executeExtrinsic(877 signer,878 'api.tx.unique.setCollectionProperties', [collectionId, properties],879 true, `Unable to set collection properties for ${label}`,880 );881882 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet', label);883 }884885 886887888889890891892893894895 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[], label?: string): Promise<boolean> {896 if(typeof label === 'undefined') label = `collection #${collectionId}`;897 const result = await this.helper.executeExtrinsic(898 signer,899 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],900 true, `Unable to delete collection properties for ${label}`,901 );902903 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted', label);904 }905906 907908909910911912913914915916917 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {918 const result = await this.helper.executeExtrinsic(919 signer,920 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],921 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,922 );923924 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);925 }926927 928929930931932933934935936937938939940 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {941 const result = await this.helper.executeExtrinsic(942 signer,943 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],944 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,945 );946 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);947 }948949 950951952953954955956957958959960961 async burnToken(signer: TSigner, collectionId: number, tokenId: number, label?: string, amount=1n): Promise<{962 success: boolean,963 token: number | null964 }> {965 if(typeof label === 'undefined') label = `collection #${collectionId}`;966 const burnResult = await this.helper.executeExtrinsic(967 signer,968 'api.tx.unique.burnItem', [collectionId, tokenId, amount],969 true, `Unable to burn token for ${label}`,970 );971 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);972 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');973 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};974 }975976 977978979980981982983984985986987988 async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, label?: string, amount=1n): Promise<boolean> {989 if(typeof label === 'undefined') label = `collection #${collectionId}`;990 const burnResult = await this.helper.executeExtrinsic(991 signer,992 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],993 true, `Unable to burn token from for ${label}`,994 );995 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);996 return burnedTokens.success && burnedTokens.tokens.length > 0;997 }998999 10001001100210031004100510061007100810091010 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=1n) {1011 if(typeof label === 'undefined') label = `collection #${collectionId}`;1012 const approveResult = await this.helper.executeExtrinsic(1013 signer, 1014 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1015 true, `Unable to approve token for ${label}`,1016 );10171018 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved', label);1019 }10201021 102210231024102510261027102810291030 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1031 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1032 }10331034 103510361037103810391040 async getLastTokenId(collectionId: number): Promise<number> {1041 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1042 }10431044 1045104610471048104910501051 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {1052 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1053 }1054}10551056class NFTnRFT extends CollectionGroup {1057 10581059106010611062106310641065 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1066 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1067 }10681069 107010711072107310741075107610771078 async getToken(collectionId: number, tokenId: number, blockHashAt?: string, propertyKeys?: string[]): Promise<{1079 properties: IProperty[];1080 owner: ICrossAccountId;1081 normalizedOwner: ICrossAccountId;1082 }| null> {1083 let tokenData;1084 if(typeof blockHashAt === 'undefined') {1085 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1086 }1087 else {1088 if(typeof propertyKeys === 'undefined') {1089 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1090 if(!collection) return null;1091 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1092 }1093 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1094 }1095 tokenData = tokenData.toHuman();1096 if (tokenData === null || tokenData.owner === null) return null;1097 const owner = {} as any;1098 for (const key of Object.keys(tokenData.owner)) {1099 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];1100 }1101 tokenData.normalizedOwner = crossAccountIdFromLower(owner);1102 return tokenData;1103 }11041105 11061107110811091110111111121113111411151116 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[], label?: string): Promise<boolean> {1117 if(typeof label === 'undefined') label = `collection #${collectionId}`;1118 const result = await this.helper.executeExtrinsic(1119 signer,1120 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1121 true, `Unable to set token property permissions for ${label}`,1122 );11231124 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet', label);1125 }11261127 1128112911301131113211331134113511361137 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[], label?: string): Promise<boolean> {1138 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;1139 const result = await this.helper.executeExtrinsic(1140 signer,1141 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1142 true, `Unable to set token properties for ${label}`,1143 );11441145 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet', label);1146 }11471148 1149115011511152115311541155115611571158 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[], label?: string): Promise<boolean> {1159 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;1160 const result = await this.helper.executeExtrinsic(1161 signer,1162 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1163 true, `Unable to delete token properties for ${label}`,1164 );11651166 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted', label);1167 }11681169 117011711172117311741175117611771178 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT', errorLabel = 'Unable to mint collection'): Promise<UniqueCollectionBase> {1179 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1180 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1181 for (const key of ['name', 'description', 'tokenPrefix']) {1182 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);1183 }1184 const creationResult = await this.helper.executeExtrinsic(1185 signer,1186 'api.tx.unique.createCollectionEx', [collectionOptions],1187 true, errorLabel,1188 );1189 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1190 }11911192 getCollectionObject(collectionId: number): any {1193 return null;1194 }11951196 getTokenObject(collectionId: number, tokenId: number): any {1197 return null;1198 }1199}120012011202class NFTGroup extends NFTnRFT {1203 120412051206120712081209 getCollectionObject(collectionId: number): UniqueNFTCollection {1210 return new UniqueNFTCollection(collectionId, this.helper);1211 }12121213 1214121512161217121812191220 getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1221 return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1222 }12231224 12251226122712281229123012311232 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1233 let owner;1234 if (typeof blockHashAt === 'undefined') {1235 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1236 } else {1237 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1238 }1239 return crossAccountIdFromLower(owner.toJSON());1240 }12411242 1243124412451246124712481249 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1250 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1251 }12521253 1254125512561257125812591260126112621263 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1264 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1265 }12661267 126812691270127112721273127412751276127712781279 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1280 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1281 }12821283 12841285128612871288128912901291 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1292 let owner;1293 if (typeof blockHashAt === 'undefined') {1294 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1295 } else {1296 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1297 }12981299 if (owner === null) return null;13001301 owner = owner.toHuman();13021303 return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1304 }13051306 13071308130913101311131213131314 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1315 let children;1316 if(typeof blockHashAt === 'undefined') {1317 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1318 } else {1319 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1320 }13211322 return children.toJSON().map((x: any) => {1323 return {collectionId: x.collection, tokenId: x.token};1324 });1325 }13261327 132813291330133113321333133413351336 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, label='nest token'): Promise<boolean> {1337 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1338 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1339 if(!result) {1340 throw Error(`Unable to nest token for ${label}`);1341 }1342 return result;1343 }13441345 1346134713481349135013511352135313541355 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId, label='unnest token'): Promise<boolean> {1356 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1357 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1358 if(!result) {1359 throw Error(`Unable to unnest token for ${label}`);1360 }1361 return result;1362 }13631364 1365136613671368136913701371137213731374137513761377 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueNFTCollection> {1378 return await super.mintCollection(signer, collectionOptions, 'NFT', `Unable to mint NFT collection for ${label}`) as UniqueNFTCollection;1379 }13801381 1382138313841385138613871388 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }, label?: string): Promise<UniqueNFTToken> {1389 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1390 const creationResult = await this.helper.executeExtrinsic(1391 signer,1392 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1393 nft: {1394 properties: data.properties,1395 },1396 }],1397 true, `Unable to mint NFT token for ${label}`,1398 );1399 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1400 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1401 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1402 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1403 }14041405 1406140714081409141014111412141314141415141614171418141914201421 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1422 if(typeof label === 'undefined') label = `collection #${collectionId}`;1423 const creationResult = await this.helper.executeExtrinsic(1424 signer,1425 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1426 true, `Unable to mint NFT tokens for ${label}`,1427 );1428 const collection = this.getCollectionObject(collectionId);1429 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1430 }14311432 1433143414351436143714381439144014411442144314441445144614471448144914501451 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1452 if(typeof label === 'undefined') label = `collection #${collectionId}`;1453 const rawTokens = [];1454 for (const token of tokens) {1455 const raw = {NFT: {properties: token.properties}};1456 rawTokens.push(raw);1457 }1458 const creationResult = await this.helper.executeExtrinsic(1459 signer,1460 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1461 true, `Unable to mint NFT tokens for ${label}`,1462 );1463 const collection = this.getCollectionObject(collectionId);1464 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1465 }14661467 146814691470147114721473147414751476 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string): Promise<{ success: boolean; token: number | null; }> {1477 return await super.burnToken(signer, collectionId, tokenId, label, 1n);1478 }14791480 14811482148314841485148614871488148914901491 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {1492 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, 1n);1493 }1494}149514961497class RFTGroup extends NFTnRFT {1498 149915001501150215031504 getCollectionObject(collectionId: number): UniqueRFTCollection {1505 return new UniqueRFTCollection(collectionId, this.helper);1506 }15071508 1509151015111512151315141515 getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1516 return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1517 }15181519 1520152115221523152415251526 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1527 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1528 }15291530 15311532153315341535153615371538 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1539 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1540 }15411542 1543154415451546154715481549155015511552 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=100n): Promise<boolean> {1553 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1554 }15551556 15571558155915601561156215631564156515661567 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n): Promise<boolean> {1568 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1569 }15701571 1572157315741575157615771578157915801581158215831584 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueRFTCollection> {1585 return await super.mintCollection(signer, collectionOptions, 'RFT', `Unable to mint RFT collection for ${label}`) as UniqueRFTCollection;1586 }15871588 15891590159115921593159415951596 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }, label?: string): Promise<UniqueRFTToken> {1597 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1598 const creationResult = await this.helper.executeExtrinsic(1599 signer,1600 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1601 refungible: {1602 pieces: data.pieces,1603 properties: data.properties,1604 },1605 }],1606 true, `Unable to mint RFT token for ${label}`,1607 );1608 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1609 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1610 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1611 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1612 }16131614 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1615 throw Error('Not implemented');1616 if(typeof label === 'undefined') label = `collection #${collectionId}`;1617 const creationResult = await this.helper.executeExtrinsic(1618 signer,1619 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1620 true, `Unable to mint RFT tokens for ${label}`,1621 );1622 const collection = this.getCollectionObject(collectionId);1623 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1624 }16251626 1627162816291630163116321633163416351636 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1637 if(typeof label === 'undefined') label = `collection #${collectionId}`;1638 const rawTokens = [];1639 for (const token of tokens) {1640 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1641 rawTokens.push(raw);1642 }1643 const creationResult = await this.helper.executeExtrinsic(1644 signer,1645 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1646 true, `Unable to mint RFT tokens for ${label}`,1647 );1648 const collection = this.getCollectionObject(collectionId);1649 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1650 }16511652 1653165416551656165716581659166016611662 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string, amount=100n): Promise<{ success: boolean; token: number | null; }> {1663 return await super.burnToken(signer, collectionId, tokenId, label, amount);1664 }16651666 166716681669167016711672167316741675167616771678 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=100n) {1679 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, amount);1680 }16811682 1683168416851686168716881689 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1690 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1691 }16921693 1694169516961697169816991700170117021703 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint, label?: string): Promise<boolean> {1704 if(typeof label === 'undefined') label = `collection #${collectionId}`;1705 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1706 const repartitionResult = await this.helper.executeExtrinsic(1707 signer,1708 'api.tx.unique.repartition', [collectionId, tokenId, amount],1709 true, `Unable to repartition RFT token for ${label}`,1710 );1711 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated', label);1712 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed', label);1713 }1714}171517161717class FTGroup extends CollectionGroup {1718 171917201721172217231724 getCollectionObject(collectionId: number): UniqueFTCollection {1725 return new UniqueFTCollection(collectionId, this.helper);1726 }17271728 17291730173117321733173417351736173717381739174017411742 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0, errorLabel = 'Unable to mint collection'): Promise<UniqueFTCollection> {1743 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1744 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1745 collectionOptions.mode = {fungible: decimalPoints};1746 for (const key of ['name', 'description', 'tokenPrefix']) {1747 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);1748 }1749 const creationResult = await this.helper.executeExtrinsic(1750 signer,1751 'api.tx.unique.createCollectionEx', [collectionOptions],1752 true, errorLabel,1753 );1754 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1755 }17561757 1758175917601761176217631764176517661767 async mintTokens(signer: TSigner, collectionId: number, owner: ICrossAccountId | string, amount: bigint, label?: string): Promise<boolean> {1768 if(typeof label === 'undefined') label = `collection #${collectionId}`;1769 const creationResult = await this.helper.executeExtrinsic(1770 signer,1771 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1772 fungible: {1773 value: amount,1774 },1775 }],1776 true, `Unable to mint fungible tokens for ${label}`,1777 );1778 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1779 }17801781 17821783178417851786178717881789179017911792 179317941795179617971798179918001801 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string): Promise<boolean> {1802 if(typeof label === 'undefined') label = `collection #${collectionId}`;1803 const rawTokens = [];1804 for (const token of tokens) {1805 const raw = {Fungible: {Value: token.value}};1806 rawTokens.push(raw);1807 }1808 const creationResult = await this.helper.executeExtrinsic(1809 signer,1810 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1811 true, `Unable to mint RFT tokens for ${label}`,1812 );1813 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1814 }18151816 181718181819182018211822 async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1823 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1824 }18251826 1827182818291830183118321833 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1834 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1835 }18361837 183818391840184118421843184418451846 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount: bigint) {1847 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1848 }18491850 1851185218531854185518561857185818591860 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {1861 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1862 }18631864 186518661867186818691870187118721873 async burnTokens(signer: IKeyringPair, collectionId: number, amount=100n, label?: string): Promise<boolean> {1874 return (await super.burnToken(signer, collectionId, 0, label, amount)).success;1875 }18761877 1878187918801881188218831884188518861887 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=100n, label?: string): Promise<boolean> {1888 return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, label, amount);1889 }18901891 18921893189418951896 async getTotalPieces(collectionId: number): Promise<bigint> {1897 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1898 }18991900 19011902190319041905190619071908190919101911 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {1912 return super.approveToken(signer, collectionId, 0, toAddressObj, label, amount);1913 }19141915 1916191719181919192019211922 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1923 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1924 }1925}192619271928class ChainGroup extends HelperGroup {1929 19301931193219331934 getChainProperties(): IChainProperties {1935 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1936 return {1937 ss58Format: properties.ss58Format.toJSON(),1938 tokenDecimals: properties.tokenDecimals.toJSON(),1939 tokenSymbol: properties.tokenSymbol.toJSON(),1940 };1941 }19421943 19441945194619471948 async getLatestBlockNumber(): Promise<number> {1949 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1950 }19511952 195319541955195619571958 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1959 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1960 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1961 return blockHash;1962 }19631964 196519661967196819691970 async getNonce(address: TSubstrateAccount): Promise<number> {1971 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1972 }1973}197419751976class BalanceGroup extends HelperGroup {1977 getOneTokenNominal(): bigint {1978 const chainProperties = this.helper.chain.getChainProperties();1979 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1980 }19811982 198319841985198619871988 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {1989 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();1990 }19911992 199319941995199619971998 async getEthereum(address: TEthereumAccount): Promise<bigint> {1999 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2000 }20012002 20032004200520062007200820092010 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2011 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}`);20122013 let transfer = {from: null, to: null, amount: 0n} as any;2014 result.result.events.forEach(({event: {data, method, section}}) => {2015 if ((section === 'balances') && (method === 'Transfer')) {2016 transfer = {2017 from: this.helper.address.normalizeSubstrate(data[0]),2018 to: this.helper.address.normalizeSubstrate(data[1]),2019 amount: BigInt(data[2]),2020 };2021 }2022 });2023 let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;2024 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;2025 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2026 return isSuccess;2027 }2028}202920302031class AddressGroup extends HelperGroup {2032 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2033 return this.helper.util.normalizeSubstrateAddress(address, ss58Format);2034 }20352036 203720382039204020412042 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {2043 const info = this.helper.chain.getChainProperties();2044 return encodeAddress(decodeAddress(address), info.ss58Format);2045 }20462047 2048204920502051205220532054 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {2055 if(!toChainFormat) return evmToAddress(ethAddress);2056 const info = this.helper.chain.getChainProperties();2057 return evmToAddress(ethAddress, info.ss58Format);2058 }20592060 206120622063206420652066 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2067 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));2068 }2069}207020712072export class UniqueHelper extends ChainHelperBase {2073 chain: ChainGroup;2074 balance: BalanceGroup;2075 address: AddressGroup;2076 collection: CollectionGroup;2077 nft: NFTGroup;2078 rft: RFTGroup;2079 ft: FTGroup;20802081 constructor(logger?: ILogger) {2082 super(logger);2083 this.chain = new ChainGroup(this);2084 this.balance = new BalanceGroup(this);2085 this.address = new AddressGroup(this);2086 this.collection = new CollectionGroup(this);2087 this.nft = new NFTGroup(this);2088 this.rft = new RFTGroup(this);2089 this.ft = new FTGroup(this);2090 } 2091}209220932094class UniqueCollectionBase {2095 helper: UniqueHelper;2096 collectionId: number;20972098 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2099 this.collectionId = collectionId;2100 this.helper = uniqueHelper;2101 }21022103 async getData() {2104 return await this.helper.collection.getData(this.collectionId);2105 }21062107 async getLastTokenId() {2108 return await this.helper.collection.getLastTokenId(this.collectionId);2109 }21102111 async isTokenExists(tokenId: number) {2112 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2113 }21142115 async getAdmins() {2116 return await this.helper.collection.getAdmins(this.collectionId);2117 }21182119 async getEffectiveLimits() {2120 return await this.helper.collection.getEffectiveLimits(this.collectionId);2121 }21222123 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount, label?: string) {2124 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress, label);2125 }21262127 async confirmSponsorship(signer: TSigner, label?: string) {2128 return await this.helper.collection.confirmSponsorship(signer, this.collectionId, label);2129 }21302131 async setLimits(signer: TSigner, limits: ICollectionLimits, label?: string) {2132 return await this.helper.collection.setLimits(signer, this.collectionId, limits, label);2133 }21342135 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount, label?: string) {2136 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress, label);2137 }21382139 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {2140 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj, label);2141 }21422143 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {2144 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj, label);2145 }21462147 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {2148 return await this.helper.collection.setProperties(signer, this.collectionId, properties, label);2149 }21502151 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {2152 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys, label);2153 }21542155 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2156 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2157 }21582159 async setPermissions(signer: TSigner, permissions: ICollectionPermissions, label?: string) {2160 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions, label);2161 }21622163 async enableNesting(signer: TSigner, permissions: INestingPermissions, label?: string) {2164 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions, label);2165 }21662167 async disableNesting(signer: TSigner, label?: string) {2168 return await this.helper.collection.disableNesting(signer, this.collectionId, label);2169 }21702171 async burn(signer: TSigner, label?: string) {2172 return await this.helper.collection.burn(signer, this.collectionId, label);2173 }2174}217521762177class UniqueNFTCollection extends UniqueCollectionBase {2178 getTokenObject(tokenId: number) {2179 return new UniqueNFTToken(tokenId, this);2180 }21812182 async getTokensByAddress(addressObj: ICrossAccountId) {2183 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2184 }21852186 async getToken(tokenId: number, blockHashAt?: string) {2187 return await this.helper.nft.getToken(this.collectionId, tokenId, blockHashAt);2188 }21892190 async getTokenOwner(tokenId: number, blockHashAt?: string) {2191 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2192 }21932194 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2195 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2196 }21972198 async getTokenChildren(tokenId: number, blockHashAt?: string) {2199 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2200 }22012202 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2203 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2204 }22052206 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2207 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2208 }22092210 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {2211 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label);2212 }22132214 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2215 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2216 }22172218 async mintToken(signer: TSigner, owner: ICrossAccountId, properties?: IProperty[], label?: string) {2219 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties}, label);2220 }22212222 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string) {2223 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens, label);2224 }22252226 async burnToken(signer: TSigner, tokenId: number, label?: string) {2227 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId, label);2228 }22292230 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {2231 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);2232 }22332234 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {2235 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);2236 }22372238 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {2239 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);2240 }22412242 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken, label?: string) {2243 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj, label);2244 }22452246 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {2247 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj, label);2248 }2249}225022512252class UniqueRFTCollection extends UniqueCollectionBase {2253 getTokenObject(tokenId: number) {2254 return new UniqueRFTToken(tokenId, this);2255 }22562257 async getTokensByAddress(addressObj: ICrossAccountId) {2258 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2259 }22602261 async getTop10TokenOwners(tokenId: number) {2262 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2263 }22642265 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2266 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2267 }22682269 async getTokenTotalPieces(tokenId: number) {2270 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2271 }22722273 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=100n) {2274 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2275 }22762277 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {2278 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2279 }22802281 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2282 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label, amount);2283 }22842285 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2286 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2287 }22882289 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint, label?: string) {2290 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount, label);2291 }22922293 async mintToken(signer: TSigner, owner: ICrossAccountId, pieces=100n, properties?: IProperty[], label?: string) {2294 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties}, label);2295 }22962297 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string) {2298 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens, label);2299 }23002301 async burnToken(signer: TSigner, tokenId: number, amount=100n, label?: string) {2302 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, label, amount);2303 }23042305 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {2306 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);2307 }23082309 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {2310 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);2311 }23122313 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {2314 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);2315 }2316}231723182319class UniqueFTCollection extends UniqueCollectionBase {2320 async mint(signer: TSigner, owner: ICrossAccountId, amount: bigint, label?: string) {2321 return await this.helper.ft.mintTokens(signer, this.collectionId, owner, amount, label);2322 }23232324 async mintWithOneOwner(signer: TSigner, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string) {2325 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, owner, tokens, label);2326 }23272328 async getBalance(addressObj: ICrossAccountId) {2329 return await this.helper.ft.getBalance(this.collectionId, addressObj);2330 }23312332 async getTop10Owners() {2333 return await this.helper.ft.getTop10Owners(this.collectionId);2334 }23352336 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount: bigint) {2337 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2338 }23392340 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {2341 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2342 }23432344 async burnTokens(signer: TSigner, amount: bigint, label?: string) {2345 return await this.helper.ft.burnTokens(signer, this.collectionId, amount, label);2346 }23472348 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount: bigint, label?: string) {2349 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount, label);2350 }23512352 async getTotalPieces() {2353 return await this.helper.ft.getTotalPieces(this.collectionId);2354 }23552356 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2357 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount, label);2358 }23592360 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2361 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2362 }2363}236423652366class UniqueTokenBase implements IToken {2367 collection: UniqueNFTCollection | UniqueRFTCollection;2368 collectionId: number;2369 tokenId: number;23702371 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2372 this.collection = collection;2373 this.collectionId = collection.collectionId;2374 this.tokenId = tokenId;2375 }23762377 async getNextSponsored(addressObj: ICrossAccountId) {2378 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2379 }23802381 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {2382 return await this.collection.setTokenProperties(signer, this.tokenId, properties, label);2383 }23842385 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {2386 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys, label);2387 }2388}238923902391class UniqueNFTToken extends UniqueTokenBase {2392 collection: UniqueNFTCollection;23932394 constructor(tokenId: number, collection: UniqueNFTCollection) {2395 super(tokenId, collection);2396 this.collection = collection;2397 }23982399 async getData(blockHashAt?: string) {2400 return await this.collection.getToken(this.tokenId, blockHashAt);2401 }24022403 async getOwner(blockHashAt?: string) {2404 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2405 }24062407 async getTopmostOwner(blockHashAt?: string) {2408 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2409 }24102411 async getChildren(blockHashAt?: string) {2412 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2413 }24142415 async nest(signer: TSigner, toTokenObj: IToken, label?: string) {2416 return await this.collection.nestToken(signer, this.tokenId, toTokenObj, label);2417 }24182419 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {2420 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj, label);2421 }24222423 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2424 return await this.collection.transferToken(signer, this.tokenId, addressObj);2425 }24262427 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2428 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2429 }24302431 async approve(signer: TSigner, toAddressObj: ICrossAccountId, label?: string) {2432 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, label);2433 }24342435 async isApproved(toAddressObj: ICrossAccountId) {2436 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2437 }24382439 async burn(signer: TSigner, label?: string) {2440 return await this.collection.burnToken(signer, this.tokenId, label);2441 }2442}24432444class UniqueRFTToken extends UniqueTokenBase {2445 collection: UniqueRFTCollection;24462447 constructor(tokenId: number, collection: UniqueRFTCollection) {2448 super(tokenId, collection);2449 this.collection = collection;2450 }24512452 async getTop10Owners() {2453 return await this.collection.getTop10TokenOwners(this.tokenId);2454 }24552456 async getBalance(addressObj: ICrossAccountId) {2457 return await this.collection.getTokenBalance(this.tokenId, addressObj);2458 }24592460 async getTotalPieces() {2461 return await this.collection.getTokenTotalPieces(this.tokenId);2462 }24632464 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=100n) {2465 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2466 }24672468 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {2469 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2470 }24712472 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2473 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount, label);2474 }24752476 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2477 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2478 }24792480 async repartition(signer: TSigner, amount: bigint, label?: string) {2481 return await this.collection.repartitionToken(signer, this.tokenId, amount, label);2482 }24832484 async burn(signer: TSigner, amount=100n, label?: string) {2485 return await this.collection.burnToken(signer, this.tokenId, amount, label);2486 }2487}