12345678import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314export const 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};2021const nesting = {22 toChecksumAddress(address: string): string {23 if (typeof address === 'undefined') return '';2425 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);2627 address = address.toLowerCase().replace(/^0x/i,'');28 const addressHash = keccakAsHex(address).replace(/^0x/i,'');29 const checksumAddress = ['0x'];3031 for (let i = 0; i < address.length; i++) {32 33 if (parseInt(addressHash[i], 16) > 7) {34 checksumAddress.push(address[i].toUpperCase());35 } else {36 checksumAddress.push(address[i]);37 }38 }39 return checksumAddress.join('');40 },41 tokenIdToAddress(collectionId: number, tokenId: number) {42 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);43 },44};4546class UniqueUtil {47 static transactionStatus = {48 NOT_READY: 'NotReady',49 FAIL: 'Fail',50 SUCCESS: 'Success',51 };5253 static chainLogType = {54 EXTRINSIC: 'extrinsic',55 RPC: 'rpc',56 };5758 static getTokenAccount(token: IToken) {59 return {Ethereum: this.getTokenAddress(token).toLowerCase()};60 }6162 static getTokenAddress(token: IToken) {63 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);64 }6566 static getDefaultLogger(): ILogger {67 return {68 log(msg: any, level = 'INFO') {69 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));70 },71 level: {72 ERROR: 'ERROR',73 WARNING: 'WARNING',74 INFO: 'INFO',75 },76 };77 }7879 static vec2str(arr: string[] | number[]) {80 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');81 }8283 static str2vec(string: string) {84 if (typeof string !== 'string') return string;85 return Array.from(string).map(x => x.charCodeAt(0));86 }8788 static fromSeed(seed: string, ss58Format = 42) {89 const keyring = new Keyring({type: 'sr25519', ss58Format});90 return keyring.addFromUri(seed);91 }9293 static normalizeSubstrateAddress(address: string, ss58Format = 42) {94 return encodeAddress(decodeAddress(address), ss58Format);95 }9697 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult) {98 if (creationResult.status !== this.transactionStatus.SUCCESS) {99 throw Error('Unable to create collection!');100 }101102 let collectionId = null;103 creationResult.result.events.forEach(({event: {data, method, section}}) => {104 if ((section === 'common') && (method === 'CollectionCreated')) {105 collectionId = parseInt(data[0].toString(), 10);106 }107 });108109 if (collectionId === null) {110 throw Error('No CollectionCreated event was found!');111 }112113 return collectionId;114 }115116 static extractTokensFromCreationResult(creationResult: ITransactionResult) {117 if (creationResult.status !== this.transactionStatus.SUCCESS) {118 throw Error('Unable to create tokens!');119 }120 let success = false;121 const tokens = [] as any;122 creationResult.result.events.forEach(({event: {data, method, section}}) => {123 if (method === 'ExtrinsicSuccess') {124 success = true;125 } else if ((section === 'common') && (method === 'ItemCreated')) {126 tokens.push({127 collectionId: parseInt(data[0].toString(), 10),128 tokenId: parseInt(data[1].toString(), 10),129 owner: data[2].toJSON(),130 });131 }132 });133 return {success, tokens};134 }135136 static extractTokensFromBurnResult(burnResult: ITransactionResult) {137 if (burnResult.status !== this.transactionStatus.SUCCESS) {138 throw Error('Unable to burn tokens!');139 }140 let success = false;141 const tokens = [] as any;142 burnResult.result.events.forEach(({event: {data, method, section}}) => {143 if (method === 'ExtrinsicSuccess') {144 success = true;145 } else if ((section === 'common') && (method === 'ItemDestroyed')) {146 tokens.push({147 collectionId: parseInt(data[0].toString(), 10),148 tokenId: parseInt(data[1].toString(), 10),149 owner: data[2].toJSON(),150 });151 }152 });153 return {success, tokens};154 }155156 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string) {157 let eventId = null;158 events.forEach(({event: {data, method, section}}) => {159 if ((section === expectedSection) && (method === expectedMethod)) {160 eventId = parseInt(data[0].toString(), 10);161 }162 });163164 if (eventId === null) {165 throw Error(`No ${expectedMethod} event was found!`);166 }167 return eventId === collectionId;168 }169170 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {171 const normalizeAddress = (address: string | ICrossAccountId) => {172 if(typeof address === 'string') return address;173 const obj = {} as any;174 Object.keys(address).forEach(k => {175 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];176 });177 if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};178 if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};179 return address;180 };181 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;182 events.forEach(({event: {data, method, section}}) => {183 if ((section === 'common') && (method === 'Transfer')) {184 const hData = (data as any).toJSON();185 transfer = {186 collectionId: hData[0],187 tokenId: hData[1],188 from: normalizeAddress(hData[2]),189 to: normalizeAddress(hData[3]),190 amount: BigInt(hData[4]),191 };192 }193 });194 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;195 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);196 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);197 isSuccess = isSuccess && amount === transfer.amount;198 return isSuccess;199 }200}201202class UniqueEventHelper {203 private static extractIndex(index: any): [number, number] | string {204 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];205 return index.toJSON();206 }207208 private static extractSub(data: any, subTypes: any): {[key: string]: any} {209 let obj: any = {};210 let index = 0;211212 if (data.entries) {213 for(const [key, value] of data.entries()) {214 obj[key] = this.extractData(value, subTypes[index]);215 index++;216 }217 } else obj = data.toJSON();218219 return obj;220 }221 222 private static extractData(data: any, type: any): any {223 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();224 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();225 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);226 return data.toHuman();227 }228229 public static extractEvents(records: ITransactionResult): IEvent[] {230 const parsedEvents: IEvent[] = [];231232 records.result.events.forEach((record) => {233 const {event, phase} = record;234 const types = (event as any).typeDef;235236 const eventData: IEvent = {237 section: event.section.toString(),238 method: event.method.toString(),239 index: this.extractIndex(event.index),240 data: [],241 phase: phase.toJSON(),242 };243244 event.data.forEach((val: any, index: number) => {245 eventData.data.push(this.extractData(val, types[index]));246 });247248 parsedEvents.push(eventData);249 });250251 return parsedEvents;252 }253}254255class ChainHelperBase {256 transactionStatus = UniqueUtil.transactionStatus;257 chainLogType = UniqueUtil.chainLogType;258 util: typeof UniqueUtil;259 eventHelper: typeof UniqueEventHelper;260 logger: ILogger;261 api: ApiPromise | null;262 forcedNetwork: TUniqueNetworks | null;263 network: TUniqueNetworks | null;264 chainLog: IUniqueHelperLog[];265266 constructor(logger?: ILogger) {267 this.util = UniqueUtil;268 this.eventHelper = UniqueEventHelper;269 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();270 this.logger = logger;271 this.api = null;272 this.forcedNetwork = null;273 this.network = null;274 this.chainLog = [];275 }276277 clearChainLog(): void {278 this.chainLog = [];279 }280281 forceNetwork(value: TUniqueNetworks): void {282 this.forcedNetwork = value;283 }284285 async connect(wsEndpoint: string, listeners?: IApiListeners) {286 if (this.api !== null) throw Error('Already connected');287 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);288 this.api = api;289 this.network = network;290 }291292 async disconnect() {293 if (this.api === null) return;294 await this.api.disconnect();295 this.api = null;296 this.network = null;297 }298299 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {300 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;301 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;302 return 'opal';303 }304305 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {306 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});307 await api.isReady;308309 const network = await this.detectNetwork(api);310311 await api.disconnect();312313 return network;314 }315316 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{317 api: ApiPromise;318 network: TUniqueNetworks;319 }> {320 if(typeof network === 'undefined' || network === null) network = 'opal';321 const supportedRPC = {322 opal: {323 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,324 },325 quartz: {326 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,327 },328 unique: {329 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,330 },331 };332 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);333 const rpc = supportedRPC[network];334335 336 337338 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});339340 await api.isReadyOrError;341342 if (typeof listeners === 'undefined') listeners = {};343 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {344 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;345 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);346 }347348 return {api, network};349 }350351 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {352 const {events, status} = data;353 if (status.isReady) {354 return this.transactionStatus.NOT_READY;355 }356 if (status.isBroadcast) {357 return this.transactionStatus.NOT_READY;358 }359 if (status.isInBlock || status.isFinalized) {360 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');361 if (errors.length > 0) {362 return this.transactionStatus.FAIL;363 }364 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {365 return this.transactionStatus.SUCCESS;366 }367 }368369 return this.transactionStatus.FAIL;370 }371372 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {373 const sign = (callback: any) => {374 if(options !== null) return transaction.signAndSend(sender, options, callback);375 return transaction.signAndSend(sender, callback);376 };377 378 return new Promise(async (resolve, reject) => {379 try {380 const unsub = await sign((result: any) => {381 const status = this.getTransactionStatus(result);382383 if (status === this.transactionStatus.SUCCESS) {384 this.logger.log(`${label} successful`);385 unsub();386 resolve({result, status});387 } else if (status === this.transactionStatus.FAIL) {388 let moduleError = null;389390 if (result.hasOwnProperty('dispatchError')) {391 const dispatchError = result['dispatchError'];392393 if (dispatchError) {394 if (dispatchError.isModule) {395 const modErr = dispatchError.asModule;396 const errorMeta = dispatchError.registry.findMetaError(modErr);397398 moduleError = `${errorMeta.section}.${errorMeta.name}`;399 } else {400 moduleError = dispatchError.toHuman();401 }402 } else {403 this.logger.log(result, this.logger.level.ERROR);404 }405 }406407 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);408 unsub();409 reject({status, moduleError, result});410 }411 });412 } catch (e) {413 this.logger.log(e, this.logger.level.ERROR);414 reject(e);415 }416 });417 }418419 constructApiCall(apiCall: string, params: any[]) {420 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);421 let call = this.api as any;422 for(const part of apiCall.slice(4).split('.')) {423 call = call[part];424 }425 return call(...params);426 }427428 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null) {429 if(this.api === null) throw Error('API not initialized');430 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);431432 const startTime = (new Date()).getTime();433 let result: ITransactionResult;434 let events: IEvent[] = [];435 try {436 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;437 events = this.eventHelper.extractEvents(result);438 }439 catch(e) {440 if(!(e as object).hasOwnProperty('status')) throw e;441 result = e as ITransactionResult;442 }443444 const endTime = (new Date()).getTime();445446 const log = {447 executedAt: endTime,448 executionTime: endTime - startTime,449 type: this.chainLogType.EXTRINSIC,450 status: result.status,451 call: extrinsic,452 signer: this.getSignerAddress(sender),453 params,454 } as IUniqueHelperLog;455456 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;457 if(events.length > 0) log.events = events;458459 this.chainLog.push(log);460461 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);462 return result;463 }464465 async callRpc(rpc: string, params?: any[]) {466 if(typeof params === 'undefined') params = [];467 if(this.api === null) throw Error('API not initialized');468 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);469470 const startTime = (new Date()).getTime();471 let result;472 let error = null;473 const log = {474 type: this.chainLogType.RPC,475 call: rpc,476 params,477 } as IUniqueHelperLog;478479 try {480 result = await this.constructApiCall(rpc, params);481 }482 catch(e) {483 error = e;484 }485486 const endTime = (new Date()).getTime();487488 log.executedAt = endTime;489 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';490 log.executionTime = endTime - startTime;491492 this.chainLog.push(log);493494 if(error !== null) throw error;495496 return result;497 }498499 getSignerAddress(signer: IKeyringPair | string): string {500 if(typeof signer === 'string') return signer;501 return signer.address;502 }503504 fetchAllPalletNames(): string[] {505 if(this.api === null) throw Error('API not initialized');506 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());507 }508509 fetchMissingPalletNames(requiredPallets: string[]): string[] {510 const palletNames = this.fetchAllPalletNames();511 return requiredPallets.filter(p => !palletNames.includes(p));512 }513}514515516class HelperGroup {517 helper: UniqueHelper;518519 constructor(uniqueHelper: UniqueHelper) {520 this.helper = uniqueHelper;521 }522}523524525class CollectionGroup extends HelperGroup {526 527528529530531532533534535 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {536 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();537 }538539 540541542543544 async getTotalCount(): Promise<number> {545 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();546 }547548 549550551552553554555556557 async getData(collectionId: number): Promise<{558 id: number;559 name: string;560 description: string;561 tokensCount: number;562 admins: ICrossAccountId[];563 normalizedOwner: TSubstrateAccount;564 raw: any565 } | null> {566 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);567 const humanCollection = collection.toHuman(), collectionData = {568 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],569 raw: humanCollection,570 } as any, jsonCollection = collection.toJSON();571 if (humanCollection === null) return null;572 collectionData.raw.limits = jsonCollection.limits;573 collectionData.raw.permissions = jsonCollection.permissions;574 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);575 for (const key of ['name', 'description']) {576 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);577 }578579 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))580 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)581 : 0;582 collectionData.admins = await this.getAdmins(collectionId);583584 return collectionData;585 }586587 588589590591592593594595 async getAdmins(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {596 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();597598 return normalize599 ? admins.map((address: any) => this.helper.address.normalizeCrossAccountIfSubstrate(address))600 : admins;601 }602603 604605606607608609610 async getAllowList(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {611 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();612 return normalize613 ? allowListed.map((address: any) => this.helper.address.normalizeCrossAccountIfSubstrate(address))614 : allowListed;615 }616617 618619620621622623624 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {625 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();626 }627628 629630631632633634635636 async burn(signer: TSigner, collectionId: number): Promise<boolean> {637 const result = await this.helper.executeExtrinsic(638 signer,639 'api.tx.unique.destroyCollection', [collectionId],640 true,641 );642643 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');644 }645646 647648649650651652653654655 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {656 const result = await this.helper.executeExtrinsic(657 signer,658 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],659 true,660 );661662 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');663 }664665 666667668669670671672673 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {674 const result = await this.helper.executeExtrinsic(675 signer,676 'api.tx.unique.confirmSponsorship', [collectionId],677 true,678 );679680 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');681 }682683 684685686687688689690691 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {692 const result = await this.helper.executeExtrinsic(693 signer,694 'api.tx.unique.removeCollectionSponsor', [collectionId],695 true,696 );697698 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');699 }700701 702703704705706707708709710711712713714715716717718 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {719 const result = await this.helper.executeExtrinsic(720 signer,721 'api.tx.unique.setCollectionLimits', [collectionId, limits],722 true,723 );724725 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');726 }727728 729730731732733734735736737 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {738 const result = await this.helper.executeExtrinsic(739 signer,740 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],741 true,742 );743744 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');745 }746747 748749750751752753754755756 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {757 const result = await this.helper.executeExtrinsic(758 signer,759 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],760 true,761 );762763 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');764 }765766 767768769770771772773774775 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {776 const result = await this.helper.executeExtrinsic(777 signer,778 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],779 true,780 );781782 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');783 }784785 786787788789790791792793 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {794 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();795 }796797 798799800801802803804 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {805 const result = await this.helper.executeExtrinsic(806 signer,807 'api.tx.unique.addToAllowList', [collectionId, addressObj],808 true,809 );810811 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');812 }813814 815816817818819820821822 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {823 const result = await this.helper.executeExtrinsic(824 signer,825 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],826 true,827 );828829 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');830 }831832 833834835836837838839840841 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {842 const result = await this.helper.executeExtrinsic(843 signer,844 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],845 true,846 );847848 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');849 }850851 852853854855856857858859860 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {861 return await this.setPermissions(signer, collectionId, {nesting: permissions});862 }863864 865866867868869870871872 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {873 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});874 }875876 877878879880881882883884885 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {886 const result = await this.helper.executeExtrinsic(887 signer,888 'api.tx.unique.setCollectionProperties', [collectionId, properties],889 true,890 );891892 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');893 }894895 896897898899900901902903 async getProperties(collectionId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {904 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();905 }906907 908909910911912913914915916 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {917 const result = await this.helper.executeExtrinsic(918 signer,919 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],920 true,921 );922923 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');924 }925926 927928929930931932933934935936937 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {938 const result = await this.helper.executeExtrinsic(939 signer,940 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],941 true, 942 );943944 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);945 }946947 948949950951952953954955956957958959960 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {961 const result = await this.helper.executeExtrinsic(962 signer,963 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],964 true, 965 );966 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);967 }968969 970971972973974975976977978979980 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<{981 success: boolean,982 token: number | null983 }> {984 const burnResult = await this.helper.executeExtrinsic(985 signer,986 'api.tx.unique.burnItem', [collectionId, tokenId, amount],987 true, 988 );989 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);990 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');991 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};992 }993994 995996997998999100010011002100310041005 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1006 const burnResult = await this.helper.executeExtrinsic(1007 signer,1008 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1009 true, 1010 );1011 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1012 return burnedTokens.success && burnedTokens.tokens.length > 0;1013 }10141015 1016101710181019102010211022102310241025 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1026 const approveResult = await this.helper.executeExtrinsic(1027 signer,1028 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1029 true, 1030 );10311032 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1033 }10341035 1036103710381039104010411042104310441045 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1046 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1047 }10481049 1050105110521053105410551056 async getLastTokenId(collectionId: number): Promise<number> {1057 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1058 }10591060 10611062106310641065106610671068 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {1069 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1070 }1071}10721073class NFTnRFT extends CollectionGroup {1074 10751076107710781079108010811082 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1083 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1084 }10851086 1087108810891090109110921093109410951096 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1097 properties: IProperty[];1098 owner: ICrossAccountId;1099 normalizedOwner: ICrossAccountId;1100 }| null> {1101 let tokenData;1102 if(typeof blockHashAt === 'undefined') {1103 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1104 }1105 else {1106 if(propertyKeys.length == 0) {1107 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1108 if(!collection) return null;1109 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1110 }1111 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1112 }1113 tokenData = tokenData.toHuman();1114 if (tokenData === null || tokenData.owner === null) return null;1115 const owner = {} as any;1116 for (const key of Object.keys(tokenData.owner)) {1117 owner[key.toLocaleLowerCase()] = this.helper.address.normalizeCrossAccountIfSubstrate(tokenData.owner[key]);1118 }1119 tokenData.normalizedOwner = crossAccountIdFromLower(owner);1120 return tokenData;1121 }11221123 11241125112611271128112911301131113211331134 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1135 const result = await this.helper.executeExtrinsic(1136 signer,1137 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1138 true,1139 );11401141 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1142 }11431144 11451146114711481149115011511152 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1153 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1154 }11551156 1157115811591160116111621163116411651166 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1167 const result = await this.helper.executeExtrinsic(1168 signer,1169 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1170 true,1171 );11721173 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1174 }11751176 117711781179118011811182118311841185 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {1186 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1187 }11881189 119011911192119311941195119611971198 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1199 const result = await this.helper.executeExtrinsic(1200 signer,1201 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1202 true,1203 );12041205 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1206 }12071208 120912101211121212131214121512161217 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueCollectionBase> {1218 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1219 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1220 for (const key of ['name', 'description', 'tokenPrefix']) {1221 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);1222 }1223 const creationResult = await this.helper.executeExtrinsic(1224 signer,1225 'api.tx.unique.createCollectionEx', [collectionOptions],1226 true, 1227 );1228 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1229 }12301231 getCollectionObject(_collectionId: number): any {1232 return null;1233 }12341235 getTokenObject(_collectionId: number, _tokenId: number): any {1236 return null;1237 }1238}123912401241class NFTGroup extends NFTnRFT {1242 124312441245124612471248 getCollectionObject(collectionId: number): UniqueNFTCollection {1249 return new UniqueNFTCollection(collectionId, this.helper);1250 }12511252 1253125412551256125712581259 getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1260 return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1261 }12621263 12641265126612671268126912701271 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1272 let owner;1273 if (typeof blockHashAt === 'undefined') {1274 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1275 } else {1276 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1277 }1278 return crossAccountIdFromLower(owner.toJSON());1279 }12801281 1282128312841285128612871288 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1289 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1290 }12911292 1293129412951296129712981299130013011302 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1303 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1304 }13051306 130713081309131013111312131313141315131613171318 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1319 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1320 }13211322 13231324132513261327132813291330 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1331 let owner;1332 if (typeof blockHashAt === 'undefined') {1333 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1334 } else {1335 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1336 }13371338 if (owner === null) return null;13391340 return owner.toHuman();1341 }13421343 13441345134613471348134913501351 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1352 let children;1353 if(typeof blockHashAt === 'undefined') {1354 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1355 } else {1356 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1357 }13581359 return children.toJSON().map((x: any) => {1360 return {collectionId: x.collection, tokenId: x.token};1361 });1362 }13631364 13651366136713681369137013711372 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1373 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1374 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1375 if(!result) {1376 throw Error('Unable to nest token!');1377 }1378 return result;1379 }13801381 138213831384138513861387138813891390 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1391 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1392 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1393 if(!result) {1394 throw Error('Unable to unnest token!');1395 }1396 return result;1397 }13981399 140014011402140314041405140614071408140914101411 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1412 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1413 }14141415 141614171418141914201421 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFTToken> {1422 const creationResult = await this.helper.executeExtrinsic(1423 signer,1424 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1425 nft: {1426 properties: data.properties,1427 },1428 }],1429 true,1430 );1431 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1432 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1433 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1434 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1435 }14361437 143814391440144114421443144414451446144714481449145014511452 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1453 const creationResult = await this.helper.executeExtrinsic(1454 signer,1455 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1456 true,1457 );1458 const collection = this.getCollectionObject(collectionId);1459 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1460 }14611462 146314641465146614671468146914701471147214731474147514761477147814791480 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1481 const rawTokens = [];1482 for (const token of tokens) {1483 const raw = {NFT: {properties: token.properties}};1484 rawTokens.push(raw);1485 }1486 const creationResult = await this.helper.executeExtrinsic(1487 signer,1488 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1489 true,1490 );1491 const collection = this.getCollectionObject(collectionId);1492 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1493 }14941495 1496149714981499150015011502150315041505 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1506 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1507 }1508}150915101511class RFTGroup extends NFTnRFT {1512 151315141515151615171518 getCollectionObject(collectionId: number): UniqueRFTCollection {1519 return new UniqueRFTCollection(collectionId, this.helper);1520 }15211522 1523152415251526152715281529 getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1530 return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1531 }15321533 1534153515361537153815391540 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1541 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1542 }15431544 15451546154715481549155015511552 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1553 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1554 }15551556 1557155815591560156115621563156415651566 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1567 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1568 }15691570 15711572157315741575157615771578157915801581 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1582 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1583 }15841585 158615871588158915901591159215931594159515961597 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1598 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1599 }16001601 1602160316041605160616071608 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFTToken> {1609 const creationResult = await this.helper.executeExtrinsic(1610 signer,1611 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1612 refungible: {1613 pieces: data.pieces,1614 properties: data.properties,1615 },1616 }],1617 true,1618 );1619 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1620 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1621 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1622 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1623 }16241625 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1626 throw Error('Not implemented');1627 const creationResult = await this.helper.executeExtrinsic(1628 signer,1629 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1630 true, 1631 );1632 const collection = this.getCollectionObject(collectionId);1633 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1634 }16351636 163716381639164016411642164316441645 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1646 const rawTokens = [];1647 for (const token of tokens) {1648 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1649 rawTokens.push(raw);1650 }1651 const creationResult = await this.helper.executeExtrinsic(1652 signer,1653 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1654 true,1655 );1656 const collection = this.getCollectionObject(collectionId);1657 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1658 }16591660 166116621663166416651666166716681669 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<{ success: boolean; token: number | null; }> {1670 return await super.burnToken(signer, collectionId, tokenId, amount);1671 }16721673 1674167516761677167816791680168116821683 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1684 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1685 }16861687 16881689169016911692169316941695169616971698 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1699 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1700 }17011702 1703170417051706170717081709 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1710 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1711 }17121713 171417151716171717181719172017211722 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1723 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1724 const repartitionResult = await this.helper.executeExtrinsic(1725 signer,1726 'api.tx.unique.repartition', [collectionId, tokenId, amount],1727 true,1728 );1729 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1730 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1731 }1732}173317341735class FTGroup extends CollectionGroup {1736 173717381739174017411742 getCollectionObject(collectionId: number): UniqueFTCollection {1743 return new UniqueFTCollection(collectionId, this.helper);1744 }17451746 1747174817491750175117521753175417551756175717581759 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1760 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1761 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1762 collectionOptions.mode = {fungible: decimalPoints};1763 for (const key of ['name', 'description', 'tokenPrefix']) {1764 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);1765 }1766 const creationResult = await this.helper.executeExtrinsic(1767 signer,1768 'api.tx.unique.createCollectionEx', [collectionOptions],1769 true,1770 );1771 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1772 }17731774 177517761777177817791780178117821783 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1784 const creationResult = await this.helper.executeExtrinsic(1785 signer,1786 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1787 fungible: {1788 value: amount,1789 },1790 }],1791 true, 1792 );1793 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1794 }17951796 17971798179918001801180218031804 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1805 const rawTokens = [];1806 for (const token of tokens) {1807 const raw = {Fungible: {Value: token.value}};1808 rawTokens.push(raw);1809 }1810 const creationResult = await this.helper.executeExtrinsic(1811 signer,1812 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1813 true,1814 );1815 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1816 }18171818 181918201821182218231824 async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1825 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1826 }18271828 1829183018311832183318341835 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1836 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1837 }18381839 184018411842184318441845184618471848 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1849 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1850 }18511852 1853185418551856185718581859186018611862 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1863 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1864 }18651866 18671868186918701871187218731874 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1875 return (await super.burnToken(signer, collectionId, 0, amount)).success;1876 }18771878 187918801881188218831884188518861887 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1888 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, 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 1901190219031904190519061907190819091910 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1911 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1912 }19131914 1915191619171918191919201921 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1922 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1923 }1924}192519261927class ChainGroup extends HelperGroup {1928 19291930193119321933 getChainProperties(): IChainProperties {1934 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1935 return {1936 ss58Format: properties.ss58Format.toJSON(),1937 tokenDecimals: properties.tokenDecimals.toJSON(),1938 tokenSymbol: properties.tokenSymbol.toJSON(),1939 };1940 }19411942 19431944194519461947 async getLatestBlockNumber(): Promise<number> {1948 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1949 }19501951 195219531954195519561957 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1958 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1959 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1960 return blockHash;1961 }19621963 1964 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {1965 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);1966 if (!blockHash) return null;1967 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;1968 }19691970 197119721973197419751976 async getNonce(address: TSubstrateAccount): Promise<number> {1977 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1978 }1979}198019811982class BalanceGroup extends HelperGroup {1983 19841985198619871988 getOneTokenNominal(): bigint {1989 const chainProperties = this.helper.chain.getChainProperties();1990 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1991 }19921993 199419951996199719981999 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2000 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2001 }20022003 20042005200620072008 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2009 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2010 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2011 }20122013 201420152016201720182019 async getEthereum(address: TEthereumAccount): Promise<bigint> {2020 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2021 }20222023 20242025202620272028202920302031 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2032 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);20332034 let transfer = {from: null, to: null, amount: 0n} as any;2035 result.result.events.forEach(({event: {data, method, section}}) => {2036 if ((section === 'balances') && (method === 'Transfer')) {2037 transfer = {2038 from: this.helper.address.normalizeSubstrate(data[0]),2039 to: this.helper.address.normalizeSubstrate(data[1]),2040 amount: BigInt(data[2]),2041 };2042 }2043 });2044 let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;2045 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;2046 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2047 return isSuccess;2048 }2049}205020512052class AddressGroup extends HelperGroup {2053 2054205520562057205820592060 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2061 return this.helper.util.normalizeSubstrateAddress(address, ss58Format);2062 }20632064 2065206620672068206920702071 normalizeCrossAccountIfSubstrate(account: ICrossAccountId, ss58Format = 42): ICrossAccountId {2072 return account.Substrate2073 ? {Substrate: this.normalizeSubstrate(account.Substrate, ss58Format)}2074 : account;2075 }20762077 207820792080208120822083 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {2084 const info = this.helper.chain.getChainProperties();2085 return encodeAddress(decodeAddress(address), info.ss58Format);2086 }20872088 2089209020912092209320942095 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {2096 if(!toChainFormat) return evmToAddress(ethAddress);2097 const info = this.helper.chain.getChainProperties();2098 return evmToAddress(ethAddress, info.ss58Format);2099 }21002101 210221032104210521062107 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2108 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));2109 }2110}21112112class StakingGroup extends HelperGroup {2113 2114211521162117211821192120 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2121 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2122 const stakeResult = await this.helper.executeExtrinsic(2123 signer, 'api.tx.appPromotion.stake',2124 [amountToStake], true,2125 );2126 2127 return true;2128 }21292130 2131213221332134213521362137 async unstake(signer: TSigner, label?: string): Promise<number> {2138 if(typeof label === 'undefined') label = `${signer.address}`;2139 const unstakeResult = await this.helper.executeExtrinsic(2140 signer, 'api.tx.appPromotion.unstake',2141 [], true,2142 );2143 2144 return 1;2145 }21462147 21482149215021512152 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2153 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2154 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2155 }21562157 21582159216021612162 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2163 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2164 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2165 return { 2166 block: block.toBigInt(),2167 amount: amount.toBigInt(),2168 };2169 });2170 }21712172 21732174217521762177 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2178 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2179 }21802181 21822183218421852186 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2187 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2188 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2189 return {2190 block: block.toBigInt(),2191 amount: amount.toBigInt(),2192 };2193 });2194 return result;2195 }2196}21972198export class UniqueHelper extends ChainHelperBase {2199 chain: ChainGroup;2200 balance: BalanceGroup;2201 address: AddressGroup;2202 collection: CollectionGroup;2203 nft: NFTGroup;2204 rft: RFTGroup;2205 ft: FTGroup;2206 staking: StakingGroup;22072208 constructor(logger?: ILogger) {2209 super(logger);2210 this.chain = new ChainGroup(this);2211 this.balance = new BalanceGroup(this);2212 this.address = new AddressGroup(this);2213 this.collection = new CollectionGroup(this);2214 this.nft = new NFTGroup(this);2215 this.rft = new RFTGroup(this);2216 this.ft = new FTGroup(this);2217 this.staking = new StakingGroup(this);2218 }2219}222022212222export class UniqueCollectionBase {2223 helper: UniqueHelper;2224 collectionId: number;22252226 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2227 this.collectionId = collectionId;2228 this.helper = uniqueHelper;2229 }22302231 async getData() {2232 return await this.helper.collection.getData(this.collectionId);2233 }22342235 async getLastTokenId() {2236 return await this.helper.collection.getLastTokenId(this.collectionId);2237 }22382239 async isTokenExists(tokenId: number) {2240 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2241 }22422243 async getAdmins() {2244 return await this.helper.collection.getAdmins(this.collectionId);2245 }22462247 async getAllowList() {2248 return await this.helper.collection.getAllowList(this.collectionId);2249 }22502251 async getEffectiveLimits() {2252 return await this.helper.collection.getEffectiveLimits(this.collectionId);2253 }22542255 async getProperties(propertyKeys: string[] | null = null) {2256 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2257 }22582259 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2260 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2261 }22622263 async confirmSponsorship(signer: TSigner) {2264 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2265 }22662267 async removeSponsor(signer: TSigner) {2268 return await this.helper.collection.removeSponsor(signer, this.collectionId);2269 }22702271 async setLimits(signer: TSigner, limits: ICollectionLimits) {2272 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2273 }22742275 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2276 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2277 }22782279 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2280 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2281 }22822283 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2284 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2285 }22862287 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2288 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2289 }22902291 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2292 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2293 }22942295 async setProperties(signer: TSigner, properties: IProperty[]) {2296 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2297 }22982299 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2300 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2301 }23022303 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2304 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2305 }23062307 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2308 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2309 }23102311 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2312 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2313 }23142315 async disableNesting(signer: TSigner) {2316 return await this.helper.collection.disableNesting(signer, this.collectionId);2317 }23182319 async burn(signer: TSigner) {2320 return await this.helper.collection.burn(signer, this.collectionId);2321 }2322}232323242325export class UniqueNFTCollection extends UniqueCollectionBase {2326 getTokenObject(tokenId: number) {2327 return new UniqueNFTToken(tokenId, this);2328 }23292330 async getTokensByAddress(addressObj: ICrossAccountId) {2331 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2332 }23332334 async getToken(tokenId: number, blockHashAt?: string) {2335 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2336 }23372338 async getTokenOwner(tokenId: number, blockHashAt?: string) {2339 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2340 }23412342 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2343 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2344 }23452346 async getTokenChildren(tokenId: number, blockHashAt?: string) {2347 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2348 }23492350 async getPropertyPermissions(propertyKeys: string[] | null = null) {2351 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2352 }23532354 async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {2355 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2356 }23572358 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2359 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2360 }23612362 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2363 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2364 }23652366 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2367 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2368 }23692370 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2371 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2372 }23732374 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2375 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2376 }23772378 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2379 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2380 }23812382 async burnToken(signer: TSigner, tokenId: number) {2383 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2384 }23852386 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2387 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2388 }23892390 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2391 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2392 }23932394 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2395 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2396 }23972398 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2399 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2400 }24012402 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2403 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2404 }24052406 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2407 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2408 }2409}241024112412export class UniqueRFTCollection extends UniqueCollectionBase {2413 getTokenObject(tokenId: number) {2414 return new UniqueRFTToken(tokenId, this);2415 }24162417 async getToken(tokenId: number, blockHashAt?: string) {2418 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);2419 }24202421 async getTokensByAddress(addressObj: ICrossAccountId) {2422 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2423 }24242425 async getTop10TokenOwners(tokenId: number) {2426 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2427 }24282429 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2430 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2431 }24322433 async getTokenTotalPieces(tokenId: number) {2434 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2435 }24362437 async getPropertyPermissions(propertyKeys: string[] | null = null) {2438 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);2439 }24402441 async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {2442 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2443 }24442445 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2446 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2447 }24482449 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2450 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2451 }24522453 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2454 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2455 }24562457 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2458 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2459 }24602461 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2462 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2463 }24642465 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2466 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2467 }24682469 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2470 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2471 }24722473 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2474 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2475 }24762477 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {2478 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);2479 }24802481 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2482 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2483 }24842485 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2486 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2487 }24882489 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2490 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2491 }2492}249324942495export class UniqueFTCollection extends UniqueCollectionBase {2496 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2497 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2498 }24992500 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2501 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2502 }25032504 async getBalance(addressObj: ICrossAccountId) {2505 return await this.helper.ft.getBalance(this.collectionId, addressObj);2506 }25072508 async getTop10Owners() {2509 return await this.helper.ft.getTop10Owners(this.collectionId);2510 }25112512 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2513 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2514 }25152516 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2517 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2518 }25192520 async burnTokens(signer: TSigner, amount=1n) {2521 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2522 }25232524 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2525 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2526 }25272528 async getTotalPieces() {2529 return await this.helper.ft.getTotalPieces(this.collectionId);2530 }25312532 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2533 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2534 }25352536 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2537 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2538 }2539}254025412542export class UniqueTokenBase implements IToken {2543 collection: UniqueNFTCollection | UniqueRFTCollection;2544 collectionId: number;2545 tokenId: number;25462547 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2548 this.collection = collection;2549 this.collectionId = collection.collectionId;2550 this.tokenId = tokenId;2551 }25522553 async getNextSponsored(addressObj: ICrossAccountId) {2554 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2555 }25562557 async getProperties(propertyKeys: string[] | null = null) {2558 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);2559 }25602561 async setProperties(signer: TSigner, properties: IProperty[]) {2562 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2563 }25642565 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2566 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2567 }25682569 nestingAccount() {2570 return this.collection.helper.util.getTokenAccount(this);2571 }2572}257325742575export class UniqueNFTToken extends UniqueTokenBase {2576 collection: UniqueNFTCollection;25772578 constructor(tokenId: number, collection: UniqueNFTCollection) {2579 super(tokenId, collection);2580 this.collection = collection;2581 }25822583 async getData(blockHashAt?: string) {2584 return await this.collection.getToken(this.tokenId, blockHashAt);2585 }25862587 async getOwner(blockHashAt?: string) {2588 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2589 }25902591 async getTopmostOwner(blockHashAt?: string) {2592 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2593 }25942595 async getChildren(blockHashAt?: string) {2596 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2597 }25982599 async nest(signer: TSigner, toTokenObj: IToken) {2600 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2601 }26022603 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2604 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2605 }26062607 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2608 return await this.collection.transferToken(signer, this.tokenId, addressObj);2609 }26102611 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2612 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2613 }26142615 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2616 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2617 }26182619 async isApproved(toAddressObj: ICrossAccountId) {2620 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2621 }26222623 async burn(signer: TSigner) {2624 return await this.collection.burnToken(signer, this.tokenId);2625 }26262627 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {2628 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);2629 }2630}26312632export class UniqueRFTToken extends UniqueTokenBase {2633 collection: UniqueRFTCollection;26342635 constructor(tokenId: number, collection: UniqueRFTCollection) {2636 super(tokenId, collection);2637 this.collection = collection;2638 }26392640 async getData(blockHashAt?: string) {2641 return await this.collection.getToken(this.tokenId, blockHashAt);2642 }26432644 async getTop10Owners() {2645 return await this.collection.getTop10TokenOwners(this.tokenId);2646 }26472648 async getBalance(addressObj: ICrossAccountId) {2649 return await this.collection.getTokenBalance(this.tokenId, addressObj);2650 }26512652 async getTotalPieces() {2653 return await this.collection.getTokenTotalPieces(this.tokenId);2654 }26552656 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2657 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2658 }26592660 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2661 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2662 }26632664 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2665 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2666 }26672668 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2669 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2670 }26712672 async repartition(signer: TSigner, amount: bigint) {2673 return await this.collection.repartitionToken(signer, this.tokenId, amount);2674 }26752676 async burn(signer: TSigner, amount=1n) {2677 return await this.collection.burnToken(signer, this.tokenId, amount);2678 }26792680 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2681 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);2682 }2683}