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 class CrossAccountId implements ICrossAccountId {15 Substrate?: TSubstrateAccount;16 Ethereum?: TEthereumAccount;1718 constructor(account: ICrossAccountId) {19 if (account.Substrate) this.Substrate = account.Substrate;20 if (account.Ethereum) this.Ethereum = account.Ethereum;21 }2223 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {24 switch (domain) {25 case 'Substrate': return new CrossAccountId({Substrate: account.address});26 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();27 }28 }2930 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {31 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});32 }3334 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {35 return encodeAddress(decodeAddress(address), ss58Format);36 }3738 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {39 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});40 }41 42 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {43 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);44 return this;45 }4647 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {48 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));49 }5051 toEthereum(): CrossAccountId {52 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});53 return this;54 }5556 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {57 return evmToAddress(address, ss58Format);58 }5960 toSubstrate(ss58Format?: number): CrossAccountId {61 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});62 return this;63 }64 65 toLowerCase(): CrossAccountId {66 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();67 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();68 return this;69 }70}7172const nesting = {73 toChecksumAddress(address: string): string {74 if (typeof address === 'undefined') return '';7576 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);7778 address = address.toLowerCase().replace(/^0x/i,'');79 const addressHash = keccakAsHex(address).replace(/^0x/i,'');80 const checksumAddress = ['0x'];8182 for (let i = 0; i < address.length; i++) {83 84 if (parseInt(addressHash[i], 16) > 7) {85 checksumAddress.push(address[i].toUpperCase());86 } else {87 checksumAddress.push(address[i]);88 }89 }90 return checksumAddress.join('');91 },92 tokenIdToAddress(collectionId: number, tokenId: number) {93 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);94 },95};9697class UniqueUtil {98 static transactionStatus = {99 NOT_READY: 'NotReady',100 FAIL: 'Fail',101 SUCCESS: 'Success',102 };103104 static chainLogType = {105 EXTRINSIC: 'extrinsic',106 RPC: 'rpc',107 };108109 static getTokenAccount(token: IToken): CrossAccountId {110 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});111 }112113 static getTokenAddress(token: IToken): string {114 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);115 }116117 static getDefaultLogger(): ILogger {118 return {119 log(msg: any, level = 'INFO') {120 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));121 },122 level: {123 ERROR: 'ERROR',124 WARNING: 'WARNING',125 INFO: 'INFO',126 },127 };128 }129130 static vec2str(arr: string[] | number[]) {131 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');132 }133134 static str2vec(string: string) {135 if (typeof string !== 'string') return string;136 return Array.from(string).map(x => x.charCodeAt(0));137 }138139 static fromSeed(seed: string, ss58Format = 42) {140 const keyring = new Keyring({type: 'sr25519', ss58Format});141 return keyring.addFromUri(seed);142 }143144 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult) {145 if (creationResult.status !== this.transactionStatus.SUCCESS) {146 throw Error('Unable to create collection!');147 }148149 let collectionId = null;150 creationResult.result.events.forEach(({event: {data, method, section}}) => {151 if ((section === 'common') && (method === 'CollectionCreated')) {152 collectionId = parseInt(data[0].toString(), 10);153 }154 });155156 if (collectionId === null) {157 throw Error('No CollectionCreated event was found!');158 }159160 return collectionId;161 }162163 static extractTokensFromCreationResult(creationResult: ITransactionResult) {164 if (creationResult.status !== this.transactionStatus.SUCCESS) {165 throw Error('Unable to create tokens!');166 }167 let success = false;168 const tokens = [] as any;169 creationResult.result.events.forEach(({event: {data, method, section}}) => {170 if (method === 'ExtrinsicSuccess') {171 success = true;172 } else if ((section === 'common') && (method === 'ItemCreated')) {173 tokens.push({174 collectionId: parseInt(data[0].toString(), 10),175 tokenId: parseInt(data[1].toString(), 10),176 owner: data[2].toJSON(),177 });178 }179 });180 return {success, tokens};181 }182183 static extractTokensFromBurnResult(burnResult: ITransactionResult) {184 if (burnResult.status !== this.transactionStatus.SUCCESS) {185 throw Error('Unable to burn tokens!');186 }187 let success = false;188 const tokens = [] as any;189 burnResult.result.events.forEach(({event: {data, method, section}}) => {190 if (method === 'ExtrinsicSuccess') {191 success = true;192 } else if ((section === 'common') && (method === 'ItemDestroyed')) {193 tokens.push({194 collectionId: parseInt(data[0].toString(), 10),195 tokenId: parseInt(data[1].toString(), 10),196 owner: data[2].toJSON(),197 });198 }199 });200 return {success, tokens};201 }202203 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string) {204 let eventId = null;205 events.forEach(({event: {data, method, section}}) => {206 if ((section === expectedSection) && (method === expectedMethod)) {207 eventId = parseInt(data[0].toString(), 10);208 }209 });210211 if (eventId === null) {212 throw Error(`No ${expectedMethod} event was found!`);213 }214 return eventId === collectionId;215 }216217 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {218 const normalizeAddress = (address: string | ICrossAccountId) => {219 if(typeof address === 'string') return address;220 const obj = {} as any;221 Object.keys(address).forEach(k => {222 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];223 });224 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);225 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();226 return address;227 };228 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;229 events.forEach(({event: {data, method, section}}) => {230 if ((section === 'common') && (method === 'Transfer')) {231 const hData = (data as any).toJSON();232 transfer = {233 collectionId: hData[0],234 tokenId: hData[1],235 from: normalizeAddress(hData[2]),236 to: normalizeAddress(hData[3]),237 amount: BigInt(hData[4]),238 };239 }240 });241 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;242 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);243 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);244 isSuccess = isSuccess && amount === transfer.amount;245 return isSuccess;246 }247}248249class UniqueEventHelper {250 private static extractIndex(index: any): [number, number] | string {251 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];252 return index.toJSON();253 }254255 private static extractSub(data: any, subTypes: any): {[key: string]: any} {256 let obj: any = {};257 let index = 0;258259 if (data.entries) {260 for(const [key, value] of data.entries()) {261 obj[key] = this.extractData(value, subTypes[index]);262 index++;263 }264 } else obj = data.toJSON();265266 return obj;267 }268 269 private static extractData(data: any, type: any): any {270 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();271 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();272 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);273 return data.toHuman();274 }275276 public static extractEvents(records: ITransactionResult): IEvent[] {277 const parsedEvents: IEvent[] = [];278279 records.result.events.forEach((record) => {280 const {event, phase} = record;281 const types = (event as any).typeDef;282283 const eventData: IEvent = {284 section: event.section.toString(),285 method: event.method.toString(),286 index: this.extractIndex(event.index),287 data: [],288 phase: phase.toJSON(),289 };290291 event.data.forEach((val: any, index: number) => {292 eventData.data.push(this.extractData(val, types[index]));293 });294295 parsedEvents.push(eventData);296 });297298 return parsedEvents;299 }300}301302class ChainHelperBase {303 transactionStatus = UniqueUtil.transactionStatus;304 chainLogType = UniqueUtil.chainLogType;305 util: typeof UniqueUtil;306 eventHelper: typeof UniqueEventHelper;307 logger: ILogger;308 api: ApiPromise | null;309 forcedNetwork: TUniqueNetworks | null;310 network: TUniqueNetworks | null;311 chainLog: IUniqueHelperLog[];312313 constructor(logger?: ILogger) {314 this.util = UniqueUtil;315 this.eventHelper = UniqueEventHelper;316 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();317 this.logger = logger;318 this.api = null;319 this.forcedNetwork = null;320 this.network = null;321 this.chainLog = [];322 }323324 clearChainLog(): void {325 this.chainLog = [];326 }327328 forceNetwork(value: TUniqueNetworks): void {329 this.forcedNetwork = value;330 }331332 async connect(wsEndpoint: string, listeners?: IApiListeners) {333 if (this.api !== null) throw Error('Already connected');334 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);335 this.api = api;336 this.network = network;337 }338339 async disconnect() {340 if (this.api === null) return;341 await this.api.disconnect();342 this.api = null;343 this.network = null;344 }345346 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {347 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;348 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;349 return 'opal';350 }351352 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {353 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});354 await api.isReady;355356 const network = await this.detectNetwork(api);357358 await api.disconnect();359360 return network;361 }362363 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{364 api: ApiPromise;365 network: TUniqueNetworks;366 }> {367 if(typeof network === 'undefined' || network === null) network = 'opal';368 const supportedRPC = {369 opal: {370 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,371 },372 quartz: {373 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,374 },375 unique: {376 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,377 },378 };379 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);380 const rpc = supportedRPC[network];381382 383 384385 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});386387 await api.isReadyOrError;388389 if (typeof listeners === 'undefined') listeners = {};390 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {391 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;392 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);393 }394395 return {api, network};396 }397398 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {399 const {events, status} = data;400 if (status.isReady) {401 return this.transactionStatus.NOT_READY;402 }403 if (status.isBroadcast) {404 return this.transactionStatus.NOT_READY;405 }406 if (status.isInBlock || status.isFinalized) {407 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');408 if (errors.length > 0) {409 return this.transactionStatus.FAIL;410 }411 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {412 return this.transactionStatus.SUCCESS;413 }414 }415416 return this.transactionStatus.FAIL;417 }418419 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {420 const sign = (callback: any) => {421 if(options !== null) return transaction.signAndSend(sender, options, callback);422 return transaction.signAndSend(sender, callback);423 };424 425 return new Promise(async (resolve, reject) => {426 try {427 const unsub = await sign((result: any) => {428 const status = this.getTransactionStatus(result);429430 if (status === this.transactionStatus.SUCCESS) {431 this.logger.log(`${label} successful`);432 unsub();433 resolve({result, status});434 } else if (status === this.transactionStatus.FAIL) {435 let moduleError = null;436437 if (result.hasOwnProperty('dispatchError')) {438 const dispatchError = result['dispatchError'];439440 if (dispatchError) {441 if (dispatchError.isModule) {442 const modErr = dispatchError.asModule;443 const errorMeta = dispatchError.registry.findMetaError(modErr);444445 moduleError = `${errorMeta.section}.${errorMeta.name}`;446 } else {447 moduleError = dispatchError.toHuman();448 }449 } else {450 this.logger.log(result, this.logger.level.ERROR);451 }452 }453454 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);455 unsub();456 reject({status, moduleError, result});457 }458 });459 } catch (e) {460 this.logger.log(e, this.logger.level.ERROR);461 reject(e);462 }463 });464 }465466 constructApiCall(apiCall: string, params: any[]) {467 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);468 let call = this.api as any;469 for(const part of apiCall.slice(4).split('.')) {470 call = call[part];471 }472 return call(...params);473 }474475 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null) {476 if(this.api === null) throw Error('API not initialized');477 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);478479 const startTime = (new Date()).getTime();480 let result: ITransactionResult;481 let events: IEvent[] = [];482 try {483 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;484 events = this.eventHelper.extractEvents(result);485 }486 catch(e) {487 if(!(e as object).hasOwnProperty('status')) throw e;488 result = e as ITransactionResult;489 }490491 const endTime = (new Date()).getTime();492493 const log = {494 executedAt: endTime,495 executionTime: endTime - startTime,496 type: this.chainLogType.EXTRINSIC,497 status: result.status,498 call: extrinsic,499 signer: this.getSignerAddress(sender),500 params,501 } as IUniqueHelperLog;502503 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;504 if(events.length > 0) log.events = events;505506 this.chainLog.push(log);507508 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);509 return result;510 }511512 async callRpc(rpc: string, params?: any[]) {513 if(typeof params === 'undefined') params = [];514 if(this.api === null) throw Error('API not initialized');515 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);516517 const startTime = (new Date()).getTime();518 let result;519 let error = null;520 const log = {521 type: this.chainLogType.RPC,522 call: rpc,523 params,524 } as IUniqueHelperLog;525526 try {527 result = await this.constructApiCall(rpc, params);528 }529 catch(e) {530 error = e;531 }532533 const endTime = (new Date()).getTime();534535 log.executedAt = endTime;536 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';537 log.executionTime = endTime - startTime;538539 this.chainLog.push(log);540541 if(error !== null) throw error;542543 return result;544 }545546 getSignerAddress(signer: IKeyringPair | string): string {547 if(typeof signer === 'string') return signer;548 return signer.address;549 }550551 fetchAllPalletNames(): string[] {552 if(this.api === null) throw Error('API not initialized');553 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());554 }555556 fetchMissingPalletNames(requiredPallets: string[]): string[] {557 const palletNames = this.fetchAllPalletNames();558 return requiredPallets.filter(p => !palletNames.includes(p));559 }560}561562563class HelperGroup {564 helper: UniqueHelper;565566 constructor(uniqueHelper: UniqueHelper) {567 this.helper = uniqueHelper;568 }569}570571572class CollectionGroup extends HelperGroup {573 574575576577578579580581582 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {583 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();584 }585586 587588589590591 async getTotalCount(): Promise<number> {592 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();593 }594595 596597598599600601602603604 async getData(collectionId: number): Promise<{605 id: number;606 name: string;607 description: string;608 tokensCount: number;609 admins: CrossAccountId[];610 normalizedOwner: TSubstrateAccount;611 raw: any612 } | null> {613 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);614 const humanCollection = collection.toHuman(), collectionData = {615 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],616 raw: humanCollection,617 } as any, jsonCollection = collection.toJSON();618 if (humanCollection === null) return null;619 collectionData.raw.limits = jsonCollection.limits;620 collectionData.raw.permissions = jsonCollection.permissions;621 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);622 for (const key of ['name', 'description']) {623 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);624 }625626 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))627 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)628 : 0;629 collectionData.admins = await this.getAdmins(collectionId);630631 return collectionData;632 }633634 635636637638639640641642 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {643 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();644645 return normalize646 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())647 : admins;648 }649650 651652653654655656657 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {658 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();659 return normalize660 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())661 : allowListed;662 }663664 665666667668669670671 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {672 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();673 }674675 676677678679680681682683 async burn(signer: TSigner, collectionId: number): Promise<boolean> {684 const result = await this.helper.executeExtrinsic(685 signer,686 'api.tx.unique.destroyCollection', [collectionId],687 true,688 );689690 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');691 }692693 694695696697698699700701702 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {703 const result = await this.helper.executeExtrinsic(704 signer,705 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],706 true,707 );708709 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');710 }711712 713714715716717718719720 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {721 const result = await this.helper.executeExtrinsic(722 signer,723 'api.tx.unique.confirmSponsorship', [collectionId],724 true,725 );726727 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');728 }729730 731732733734735736737738 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {739 const result = await this.helper.executeExtrinsic(740 signer,741 'api.tx.unique.removeCollectionSponsor', [collectionId],742 true,743 );744745 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');746 }747748 749750751752753754755756757758759760761762763764765 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {766 const result = await this.helper.executeExtrinsic(767 signer,768 'api.tx.unique.setCollectionLimits', [collectionId, limits],769 true,770 );771772 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');773 }774775 776777778779780781782783784 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {785 const result = await this.helper.executeExtrinsic(786 signer,787 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],788 true,789 );790791 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');792 }793794 795796797798799800801802803 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {804 const result = await this.helper.executeExtrinsic(805 signer,806 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],807 true,808 );809810 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');811 }812813 814815816817818819820821822 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {823 const result = await this.helper.executeExtrinsic(824 signer,825 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],826 true,827 );828829 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');830 }831832 833834835836837838839840 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {841 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();842 }843844 845846847848849850851 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {852 const result = await this.helper.executeExtrinsic(853 signer,854 'api.tx.unique.addToAllowList', [collectionId, addressObj],855 true,856 );857858 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');859 }860861 862863864865866867868869 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {870 const result = await this.helper.executeExtrinsic(871 signer,872 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],873 true,874 );875876 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');877 }878879 880881882883884885886887888 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {889 const result = await this.helper.executeExtrinsic(890 signer,891 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],892 true,893 );894895 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');896 }897898 899900901902903904905906907 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {908 return await this.setPermissions(signer, collectionId, {nesting: permissions});909 }910911 912913914915916917918919 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {920 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});921 }922923 924925926927928929930931932 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {933 const result = await this.helper.executeExtrinsic(934 signer,935 'api.tx.unique.setCollectionProperties', [collectionId, properties],936 true,937 );938939 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');940 }941942 943944945946947948949950 async getProperties(collectionId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {951 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();952 }953954 955956957958959960961962963 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {964 const result = await this.helper.executeExtrinsic(965 signer,966 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],967 true,968 );969970 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');971 }972973 974975976977978979980981982983984 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {985 const result = await this.helper.executeExtrinsic(986 signer,987 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],988 true, 989 );990991 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);992 }993994 99599699799899910001001100210031004100510061007 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1008 const result = await this.helper.executeExtrinsic(1009 signer,1010 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1011 true, 1012 );1013 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1014 }10151016 10171018101910201021102210231024102510261027 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<{1028 success: boolean,1029 token: number | null1030 }> {1031 const burnResult = await this.helper.executeExtrinsic(1032 signer,1033 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1034 true, 1035 );1036 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1037 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1038 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};1039 }10401041 10421043104410451046104710481049105010511052 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1053 const burnResult = await this.helper.executeExtrinsic(1054 signer,1055 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1056 true, 1057 );1058 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1059 return burnedTokens.success && burnedTokens.tokens.length > 0;1060 }10611062 1063106410651066106710681069107010711072 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1073 const approveResult = await this.helper.executeExtrinsic(1074 signer,1075 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1076 true, 1077 );10781079 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1080 }10811082 1083108410851086108710881089109010911092 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1093 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1094 }10951096 1097109810991100110111021103 async getLastTokenId(collectionId: number): Promise<number> {1104 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1105 }11061107 11081109111011111112111311141115 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {1116 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1117 }1118}11191120class NFTnRFT extends CollectionGroup {1121 11221123112411251126112711281129 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1130 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1131 }11321133 1134113511361137113811391140114111421143 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1144 properties: IProperty[];1145 owner: CrossAccountId;1146 normalizedOwner: CrossAccountId;1147 }| null> {1148 let tokenData;1149 if(typeof blockHashAt === 'undefined') {1150 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1151 }1152 else {1153 if(propertyKeys.length == 0) {1154 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1155 if(!collection) return null;1156 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1157 }1158 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1159 }1160 tokenData = tokenData.toHuman();1161 if (tokenData === null || tokenData.owner === null) return null;1162 const owner = {} as any;1163 for (const key of Object.keys(tokenData.owner)) {1164 owner[key.toLocaleLowerCase()] = new CrossAccountId(tokenData.owner[key]).withNormalizedSubstrate();1165 }1166 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1167 return tokenData;1168 }11691170 11711172117311741175117611771178117911801181 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1182 const result = await this.helper.executeExtrinsic(1183 signer,1184 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1185 true,1186 );11871188 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1189 }11901191 11921193119411951196119711981199 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1200 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1201 }12021203 1204120512061207120812091210121112121213 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1214 const result = await this.helper.executeExtrinsic(1215 signer,1216 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1217 true,1218 );12191220 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1221 }12221223 122412251226122712281229123012311232 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {1233 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1234 }12351236 123712381239124012411242124312441245 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1246 const result = await this.helper.executeExtrinsic(1247 signer,1248 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1249 true,1250 );12511252 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1253 }12541255 125612571258125912601261126212631264 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1265 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1266 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1267 for (const key of ['name', 'description', 'tokenPrefix']) {1268 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);1269 }1270 const creationResult = await this.helper.executeExtrinsic(1271 signer,1272 'api.tx.unique.createCollectionEx', [collectionOptions],1273 true, 1274 );1275 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1276 }12771278 getCollectionObject(_collectionId: number): any {1279 return null;1280 }12811282 getTokenObject(_collectionId: number, _tokenId: number): any {1283 return null;1284 }1285}128612871288class NFTGroup extends NFTnRFT {1289 129012911292129312941295 getCollectionObject(collectionId: number): UniqueNFTCollection {1296 return new UniqueNFTCollection(collectionId, this.helper);1297 }12981299 1300130113021303130413051306 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1307 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1308 }13091310 13111312131313141315131613171318 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1319 let owner;1320 if (typeof blockHashAt === 'undefined') {1321 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1322 } else {1323 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1324 }1325 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1326 }13271328 1329133013311332133313341335 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1336 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1337 }13381339 1340134113421343134413451346134713481349 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1350 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1351 }13521353 135413551356135713581359136013611362136313641365 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1366 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1367 }13681369 13701371137213731374137513761377 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1378 let owner;1379 if (typeof blockHashAt === 'undefined') {1380 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1381 } else {1382 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1383 }13841385 if (owner === null) return null;13861387 return owner.toHuman();1388 }13891390 13911392139313941395139613971398 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1399 let children;1400 if(typeof blockHashAt === 'undefined') {1401 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1402 } else {1403 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1404 }14051406 return children.toJSON().map((x: any) => {1407 return {collectionId: x.collection, tokenId: x.token};1408 });1409 }14101411 14121413141414151416141714181419 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1420 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1421 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1422 if(!result) {1423 throw Error('Unable to nest token!');1424 }1425 return result;1426 }14271428 142914301431143214331434143514361437 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1438 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1439 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1440 if(!result) {1441 throw Error('Unable to unnest token!');1442 }1443 return result;1444 }14451446 144714481449145014511452145314541455145614571458 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1459 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1460 }14611462 146314641465146614671468 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1469 const creationResult = await this.helper.executeExtrinsic(1470 signer,1471 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1472 nft: {1473 properties: data.properties,1474 },1475 }],1476 true,1477 );1478 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1479 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1480 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1481 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1482 }14831484 148514861487148814891490149114921493149414951496149714981499 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1500 const creationResult = await this.helper.executeExtrinsic(1501 signer,1502 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1503 true,1504 );1505 const collection = this.getCollectionObject(collectionId);1506 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1507 }15081509 151015111512151315141515151615171518151915201521152215231524152515261527 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1528 const rawTokens = [];1529 for (const token of tokens) {1530 const raw = {NFT: {properties: token.properties}};1531 rawTokens.push(raw);1532 }1533 const creationResult = await this.helper.executeExtrinsic(1534 signer,1535 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1536 true,1537 );1538 const collection = this.getCollectionObject(collectionId);1539 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1540 }15411542 1543154415451546154715481549155015511552 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1553 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1554 }1555}155615571558class RFTGroup extends NFTnRFT {1559 156015611562156315641565 getCollectionObject(collectionId: number): UniqueRFTCollection {1566 return new UniqueRFTCollection(collectionId, this.helper);1567 }15681569 1570157115721573157415751576 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1577 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1578 }15791580 1581158215831584158515861587 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1588 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1589 }15901591 15921593159415951596159715981599 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1600 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1601 }16021603 1604160516061607160816091610161116121613 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1614 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1615 }16161617 16181619162016211622162316241625162616271628 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1629 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1630 }16311632 163316341635163616371638163916401641164216431644 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1645 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1646 }16471648 1649165016511652165316541655 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1656 const creationResult = await this.helper.executeExtrinsic(1657 signer,1658 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1659 refungible: {1660 pieces: data.pieces,1661 properties: data.properties,1662 },1663 }],1664 true,1665 );1666 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1667 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1668 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1669 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1670 }16711672 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1673 throw Error('Not implemented');1674 const creationResult = await this.helper.executeExtrinsic(1675 signer,1676 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1677 true, 1678 );1679 const collection = this.getCollectionObject(collectionId);1680 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1681 }16821683 168416851686168716881689169016911692 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1693 const rawTokens = [];1694 for (const token of tokens) {1695 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1696 rawTokens.push(raw);1697 }1698 const creationResult = await this.helper.executeExtrinsic(1699 signer,1700 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1701 true,1702 );1703 const collection = this.getCollectionObject(collectionId);1704 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1705 }17061707 170817091710171117121713171417151716 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<{ success: boolean; token: number | null; }> {1717 return await super.burnToken(signer, collectionId, tokenId, amount);1718 }17191720 1721172217231724172517261727172817291730 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1731 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1732 }17331734 17351736173717381739174017411742174317441745 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1746 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1747 }17481749 1750175117521753175417551756 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1757 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1758 }17591760 176117621763176417651766176717681769 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1770 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1771 const repartitionResult = await this.helper.executeExtrinsic(1772 signer,1773 'api.tx.unique.repartition', [collectionId, tokenId, amount],1774 true,1775 );1776 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1777 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1778 }1779}178017811782class FTGroup extends CollectionGroup {1783 178417851786178717881789 getCollectionObject(collectionId: number): UniqueFTCollection {1790 return new UniqueFTCollection(collectionId, this.helper);1791 }17921793 1794179517961797179817991800180118021803180418051806 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1807 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1808 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1809 collectionOptions.mode = {fungible: decimalPoints};1810 for (const key of ['name', 'description', 'tokenPrefix']) {1811 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);1812 }1813 const creationResult = await this.helper.executeExtrinsic(1814 signer,1815 'api.tx.unique.createCollectionEx', [collectionOptions],1816 true,1817 );1818 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1819 }18201821 182218231824182518261827182818291830 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1831 const creationResult = await this.helper.executeExtrinsic(1832 signer,1833 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1834 fungible: {1835 value: amount,1836 },1837 }],1838 true, 1839 );1840 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1841 }18421843 18441845184618471848184918501851 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1852 const rawTokens = [];1853 for (const token of tokens) {1854 const raw = {Fungible: {Value: token.value}};1855 rawTokens.push(raw);1856 }1857 const creationResult = await this.helper.executeExtrinsic(1858 signer,1859 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1860 true,1861 );1862 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1863 }18641865 186618671868186918701871 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1872 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1873 }18741875 1876187718781879188018811882 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1883 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1884 }18851886 188718881889189018911892189318941895 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1896 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1897 }18981899 1900190119021903190419051906190719081909 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1910 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1911 }19121913 19141915191619171918191919201921 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1922 return (await super.burnToken(signer, collectionId, 0, amount)).success;1923 }19241925 192619271928192919301931193219331934 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1935 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);1936 }19371938 19391940194119421943 async getTotalPieces(collectionId: number): Promise<bigint> {1944 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1945 }19461947 1948194919501951195219531954195519561957 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1958 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1959 }19601961 1962196319641965196619671968 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1969 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1970 }1971}197219731974class ChainGroup extends HelperGroup {1975 19761977197819791980 getChainProperties(): IChainProperties {1981 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1982 return {1983 ss58Format: properties.ss58Format.toJSON(),1984 tokenDecimals: properties.tokenDecimals.toJSON(),1985 tokenSymbol: properties.tokenSymbol.toJSON(),1986 };1987 }19881989 19901991199219931994 async getLatestBlockNumber(): Promise<number> {1995 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1996 }19971998 199920002001200220032004 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2005 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2006 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2007 return blockHash;2008 }20092010 2011 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2012 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2013 if (!blockHash) return null;2014 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2015 }20162017 201820192020202120222023 async getNonce(address: TSubstrateAccount): Promise<number> {2024 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();2025 }2026}202720282029class BalanceGroup extends HelperGroup {2030 20312032203320342035 getOneTokenNominal(): bigint {2036 const chainProperties = this.helper.chain.getChainProperties();2037 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2038 }20392040 204120422043204420452046 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2047 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2048 }20492050 20512052205320542055 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2056 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2057 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2058 }20592060 206120622063206420652066 async getEthereum(address: TEthereumAccount): Promise<bigint> {2067 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2068 }20692070 20712072207320742075207620772078 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2079 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);20802081 let transfer = {from: null, to: null, amount: 0n} as any;2082 result.result.events.forEach(({event: {data, method, section}}) => {2083 if ((section === 'balances') && (method === 'Transfer')) {2084 transfer = {2085 from: this.helper.address.normalizeSubstrate(data[0]),2086 to: this.helper.address.normalizeSubstrate(data[1]),2087 amount: BigInt(data[2]),2088 };2089 }2090 });2091 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2092 && this.helper.address.normalizeSubstrate(address) === transfer.to 2093 && BigInt(amount) === transfer.amount;2094 return isSuccess;2095 }2096}209720982099class AddressGroup extends HelperGroup {2100 2101210221032104210521062107 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2108 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2109 }21102111 211221132114211521162117 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2118 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2119 }21202121 2122212321242125212621272128 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2129 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2130 }21312132 213321342135213621372138 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2139 return CrossAccountId.translateSubToEth(subAddress);2140 }2141}21422143class StakingGroup extends HelperGroup {2144 2145214621472148214921502151 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2152 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2153 const stakeResult = await this.helper.executeExtrinsic(2154 signer, 'api.tx.appPromotion.stake',2155 [amountToStake], true,2156 );2157 2158 return true;2159 }21602161 2162216321642165216621672168 async unstake(signer: TSigner, label?: string): Promise<number> {2169 if(typeof label === 'undefined') label = `${signer.address}`;2170 const unstakeResult = await this.helper.executeExtrinsic(2171 signer, 'api.tx.appPromotion.unstake',2172 [], true,2173 );2174 2175 return 1;2176 }21772178 21792180218121822183 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2184 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2185 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2186 }21872188 21892190219121922193 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2194 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2195 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2196 return { 2197 block: block.toBigInt(),2198 amount: amount.toBigInt(),2199 };2200 });2201 }22022203 22042205220622072208 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2209 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2210 }22112212 22132214221522162217 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2218 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2219 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2220 return {2221 block: block.toBigInt(),2222 amount: amount.toBigInt(),2223 };2224 });2225 return result;2226 }2227}22282229export class UniqueHelper extends ChainHelperBase {2230 chain: ChainGroup;2231 balance: BalanceGroup;2232 address: AddressGroup;2233 collection: CollectionGroup;2234 nft: NFTGroup;2235 rft: RFTGroup;2236 ft: FTGroup;2237 staking: StakingGroup;22382239 constructor(logger?: ILogger) {2240 super(logger);2241 this.chain = new ChainGroup(this);2242 this.balance = new BalanceGroup(this);2243 this.address = new AddressGroup(this);2244 this.collection = new CollectionGroup(this);2245 this.nft = new NFTGroup(this);2246 this.rft = new RFTGroup(this);2247 this.ft = new FTGroup(this);2248 this.staking = new StakingGroup(this);2249 }2250}225122522253export class UniqueBaseCollection {2254 helper: UniqueHelper;2255 collectionId: number;22562257 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2258 this.collectionId = collectionId;2259 this.helper = uniqueHelper;2260 }22612262 async getData() {2263 return await this.helper.collection.getData(this.collectionId);2264 }22652266 async getLastTokenId() {2267 return await this.helper.collection.getLastTokenId(this.collectionId);2268 }22692270 async isTokenExists(tokenId: number) {2271 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2272 }22732274 async getAdmins() {2275 return await this.helper.collection.getAdmins(this.collectionId);2276 }22772278 async getAllowList() {2279 return await this.helper.collection.getAllowList(this.collectionId);2280 }22812282 async getEffectiveLimits() {2283 return await this.helper.collection.getEffectiveLimits(this.collectionId);2284 }22852286 async getProperties(propertyKeys: string[] | null = null) {2287 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2288 }22892290 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2291 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2292 }22932294 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2295 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2296 }22972298 async confirmSponsorship(signer: TSigner) {2299 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2300 }23012302 async removeSponsor(signer: TSigner) {2303 return await this.helper.collection.removeSponsor(signer, this.collectionId);2304 }23052306 async setLimits(signer: TSigner, limits: ICollectionLimits) {2307 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2308 }23092310 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2311 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2312 }23132314 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2315 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2316 }23172318 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2319 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2320 }23212322 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2323 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2324 }23252326 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2327 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2328 }23292330 async setProperties(signer: TSigner, properties: IProperty[]) {2331 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2332 }23332334 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2335 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2336 }23372338 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2339 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2340 }23412342 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2343 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2344 }23452346 async disableNesting(signer: TSigner) {2347 return await this.helper.collection.disableNesting(signer, this.collectionId);2348 }23492350 async burn(signer: TSigner) {2351 return await this.helper.collection.burn(signer, this.collectionId);2352 }2353}235423552356export class UniqueNFTCollection extends UniqueBaseCollection {2357 getTokenObject(tokenId: number) {2358 return new UniqueNFToken(tokenId, this);2359 }23602361 async getTokensByAddress(addressObj: ICrossAccountId) {2362 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2363 }23642365 async getToken(tokenId: number, blockHashAt?: string) {2366 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2367 }23682369 async getTokenOwner(tokenId: number, blockHashAt?: string) {2370 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2371 }23722373 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2374 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2375 }23762377 async getTokenChildren(tokenId: number, blockHashAt?: string) {2378 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2379 }23802381 async getPropertyPermissions(propertyKeys: string[] | null = null) {2382 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2383 }23842385 async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {2386 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2387 }23882389 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2390 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2391 }23922393 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2394 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2395 }23962397 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2398 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2399 }24002401 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2402 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2403 }24042405 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2406 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2407 }24082409 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2410 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2411 }24122413 async burnToken(signer: TSigner, tokenId: number) {2414 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2415 }24162417 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2418 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2419 }24202421 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2422 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2423 }24242425 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2426 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2427 }24282429 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2430 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2431 }24322433 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2434 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2435 }24362437 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2438 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2439 }2440}244124422443export class UniqueRFTCollection extends UniqueBaseCollection {2444 getTokenObject(tokenId: number) {2445 return new UniqueRFToken(tokenId, this);2446 }24472448 async getToken(tokenId: number, blockHashAt?: string) {2449 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);2450 }24512452 async getTokensByAddress(addressObj: ICrossAccountId) {2453 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2454 }24552456 async getTop10TokenOwners(tokenId: number) {2457 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2458 }24592460 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2461 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2462 }24632464 async getTokenTotalPieces(tokenId: number) {2465 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2466 }24672468 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2469 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2470 }24712472 async getPropertyPermissions(propertyKeys: string[] | null = null) {2473 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);2474 }24752476 async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {2477 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2478 }24792480 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2481 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2482 }24832484 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2485 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2486 }24872488 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2489 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2490 }24912492 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2493 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2494 }24952496 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2497 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2498 }24992500 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2501 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2502 }25032504 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2505 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2506 }25072508 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {2509 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);2510 }25112512 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2513 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2514 }25152516 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2517 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2518 }25192520 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2521 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2522 }2523}252425252526export class UniqueFTCollection extends UniqueBaseCollection {2527 async getBalance(addressObj: ICrossAccountId) {2528 return await this.helper.ft.getBalance(this.collectionId, addressObj);2529 }25302531 async getTotalPieces() {2532 return await this.helper.ft.getTotalPieces(this.collectionId);2533 }25342535 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2536 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2537 }25382539 async getTop10Owners() {2540 return await this.helper.ft.getTop10Owners(this.collectionId);2541 }25422543 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2544 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2545 }25462547 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2548 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2549 }25502551 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2552 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2553 }25542555 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2556 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2557 }25582559 async burnTokens(signer: TSigner, amount=1n) {2560 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2561 }25622563 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2564 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2565 }25662567 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2568 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2569 }2570}257125722573export class UniqueBaseToken {2574 collection: UniqueNFTCollection | UniqueRFTCollection;2575 collectionId: number;2576 tokenId: number;25772578 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2579 this.collection = collection;2580 this.collectionId = collection.collectionId;2581 this.tokenId = tokenId;2582 }25832584 async getNextSponsored(addressObj: ICrossAccountId) {2585 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2586 }25872588 async getProperties(propertyKeys: string[] | null = null) {2589 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);2590 }25912592 async setProperties(signer: TSigner, properties: IProperty[]) {2593 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2594 }25952596 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2597 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2598 }25992600 nestingAccount() {2601 return this.collection.helper.util.getTokenAccount(this);2602 }2603}260426052606export class UniqueNFToken extends UniqueBaseToken {2607 collection: UniqueNFTCollection;26082609 constructor(tokenId: number, collection: UniqueNFTCollection) {2610 super(tokenId, collection);2611 this.collection = collection;2612 }26132614 async getData(blockHashAt?: string) {2615 return await this.collection.getToken(this.tokenId, blockHashAt);2616 }26172618 async getOwner(blockHashAt?: string) {2619 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2620 }26212622 async getTopmostOwner(blockHashAt?: string) {2623 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2624 }26252626 async getChildren(blockHashAt?: string) {2627 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2628 }26292630 async nest(signer: TSigner, toTokenObj: IToken) {2631 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2632 }26332634 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2635 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2636 }26372638 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2639 return await this.collection.transferToken(signer, this.tokenId, addressObj);2640 }26412642 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2643 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2644 }26452646 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2647 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2648 }26492650 async isApproved(toAddressObj: ICrossAccountId) {2651 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2652 }26532654 async burn(signer: TSigner) {2655 return await this.collection.burnToken(signer, this.tokenId);2656 }26572658 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {2659 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);2660 }2661}26622663export class UniqueRFToken extends UniqueBaseToken {2664 collection: UniqueRFTCollection;26652666 constructor(tokenId: number, collection: UniqueRFTCollection) {2667 super(tokenId, collection);2668 this.collection = collection;2669 }26702671 async getData(blockHashAt?: string) {2672 return await this.collection.getToken(this.tokenId, blockHashAt);2673 }26742675 async getTop10Owners() {2676 return await this.collection.getTop10TokenOwners(this.tokenId);2677 }26782679 async getBalance(addressObj: ICrossAccountId) {2680 return await this.collection.getTokenBalance(this.tokenId, addressObj);2681 }26822683 async getTotalPieces() {2684 return await this.collection.getTokenTotalPieces(this.tokenId);2685 }26862687 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2688 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2689 }26902691 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2692 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2693 }26942695 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2696 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2697 }26982699 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2700 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2701 }27022703 async repartition(signer: TSigner, amount: bigint) {2704 return await this.collection.repartitionToken(signer, this.tokenId, amount);2705 }27062707 async burn(signer: TSigner, amount=1n) {2708 return await this.collection.burnToken(signer, this.tokenId, amount);2709 }27102711 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2712 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);2713 }2714}