difftreelog
fix eslint errors in playgrounds
in: master
2 files changed
tests/src/util/playgrounds/index.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/index.ts
+++ b/tests/src/util/playgrounds/index.ts
@@ -1,18 +1,18 @@
-import { IKeyringPair } from '@polkadot/types/types';
-import { UniqueHelper } from './unique';
+import {IKeyringPair} from '@polkadot/types/types';
+import {UniqueHelper} from './unique';
import config from '../../config';
import '../../interfaces/augment-api-events';
import * as defs from '../../interfaces/definitions';
-import { ApiPromise, WsProvider } from '@polkadot/api';
+import {ApiPromise, WsProvider} from '@polkadot/api';
class SilentLogger {
log(msg: any, level: any): void {}
level = {
- ERROR: 'ERROR' as 'ERROR',
- WARNING: 'WARNING' as 'WARNING',
- INFO: 'INFO' as 'INFO'
- }
+ ERROR: 'ERROR' as const,
+ WARNING: 'WARNING' as const,
+ INFO: 'INFO' as const,
+ };
}
@@ -87,4 +87,4 @@
console.log = consoleLog;
console.warn = consoleWarn;
}
-}
\ No newline at end of file
+};
\ No newline at end of file
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth12import { ApiPromise, WsProvider, Keyring } from '@polkadot/api';3import { ApiInterfaceEvents } from '@polkadot/api/types';4import { IKeyringPair } from '@polkadot/types/types';5import { encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm } from '@polkadot/util-crypto';678const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {9 let address = {} as ICrossAccountId;10 if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;11 if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;12 return address;13}141516const nesting = {17 toChecksumAddress(address: string): string {18 if (typeof address === 'undefined') return '';1920 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);2122 address = address.toLowerCase().replace(/^0x/i,'');23 const addressHash = keccakAsHex(address).replace(/^0x/i,'');24 let checksumAddress = ['0x'];2526 for (let i = 0; i < address.length; i++ ) {27 // If ith character is 8 to f then make it uppercase28 if (parseInt(addressHash[i], 16) > 7) {29 checksumAddress.push(address[i].toUpperCase());30 } else {31 checksumAddress.push(address[i]);32 }33 }34 return checksumAddress.join('');35 },36 tokenIdToAddress(collectionId: number, tokenId: number) {37 return this.toChecksumAddress(38 `0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`39 );40 }41};424344interface IChainEvent {45 data: any;46 method: string;47 section: string;48}4950interface ITransactionResult {51 status: 'Fail' | 'Success';52 result: {53 events: {54 event: IChainEvent55 }[];56 },57 moduleError?: string;58}5960interface ILogger {61 log: (msg: any, level?: string) => void;62 level: {63 ERROR: 'ERROR';64 WARNING: 'WARNING';65 INFO: 'INFO';66 [key: string]: string;67 }68}6970interface IUniqueHelperLog {71 executedAt: number;72 executionTime: number;73 type: 'extrinsic' | 'rpc';74 status: 'Fail' | 'Success';75 call: string;76 params: any[];77 moduleError?: string;78 events?: any;79}8081interface IApiListeners {82 connected?: (...args: any[]) => any;83 disconnected?: (...args: any[]) => any;84 error?: (...args: any[]) => any;85 ready?: (...args: any[]) => any; 86 decorated?: (...args: any[]) => any;87}8889interface ICrossAccountId {90 Substrate?: TSubstrateAccount;91 Ethereum?: TEthereumAccount;92}9394interface ICrossAccountIdLower {95 substrate?: TSubstrateAccount;96 ethereum?: TEthereumAccount;97}9899interface ICollectionLimits {100 accountTokenOwnershipLimit?: number | null;101 sponsoredDataSize?: number | null;102 sponsoredDataRateLimit?: {blocks: number} | {sponsoringDisabled: null} | null;103 tokenLimit?: number | null;104 sponsorTransferTimeout?: number | null;105 sponsorApproveTimeout?: number | null;106 ownerCanTransfer?: boolean | null;107 ownerCanDestroy?: boolean | null;108 transfersEnabled?: boolean | null;109}110111interface INestingPermissions {112 tokenOwner?: boolean;113 collectionAdmin?: boolean;114 restricted?: number[] | null;115}116117interface ICollectionPermissions {118 access?: 'Normal' | 'AllowList';119 mintMode?: boolean;120 nesting?: INestingPermissions;121}122123interface IProperty {124 key: string;125 value: string;126}127128interface ITokenPropertyPermission {129 key: string;130 permission: {131 mutable: boolean;132 tokenOwner: boolean;133 collectionAdmin: boolean;134 }135}136137interface IToken {138 collectionId: number;139 tokenId: number;140}141142interface ICollectionCreationOptions {143 name: string | number[];144 description: string | number[];145 tokenPrefix: string | number[];146 mode?: {147 nft?: null;148 refungible?: null;149 fungible?: number;150 }151 permissions?: ICollectionPermissions;152 properties?: IProperty[];153 tokenPropertyPermissions?: ITokenPropertyPermission[];154 limits?: ICollectionLimits;155 pendingSponsor?: TSubstrateAccount;156}157158interface IChainProperties {159 ss58Format: number;160 tokenDecimals: number[];161 tokenSymbol: string[]162}163164type TSubstrateAccount = string;165type TEthereumAccount = string;166type TApiAllowedListeners = 'connected' | 'disconnected' | 'error' | 'ready' | 'decorated';167type TUniqueNetworks = 'opal' | 'quartz' | 'unique';168type TSigner = IKeyringPair; // | 'string'169170class UniqueUtil {171 static transactionStatus = {172 NOT_READY: 'NotReady',173 FAIL: 'Fail',174 SUCCESS: 'Success'175 }176177 static chainLogType = {178 EXTRINSIC: 'extrinsic',179 RPC: 'rpc'180 }181182 static getNestingTokenAddress(collectionId: number, tokenId: number) {183 return nesting.tokenIdToAddress(collectionId, tokenId);184 }185186 static getDefaultLogger(): ILogger {187 return {188 log(msg: any, level = 'INFO') {189 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));190 },191 level: {192 ERROR: 'ERROR',193 WARNING: 'WARNING',194 INFO: 'INFO'195 }196 };197 }198199 static vec2str(arr: string[] | number[]) {200 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');201 }202203 static str2vec(string: string) {204 if (typeof string !== 'string') return string;205 return Array.from(string).map(x => x.charCodeAt(0));206 }207208 static fromSeed(seed: string, ss58Format = 42) {209 const keyring = new Keyring({type: 'sr25519', ss58Format});210 return keyring.addFromUri(seed);211 }212213 static normalizeSubstrateAddress(address: string, ss58Format = 42) {214 return encodeAddress(decodeAddress(address), ss58Format);215 }216217 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult, label = 'new collection') {218 if (creationResult.status !== this.transactionStatus.SUCCESS) {219 throw Error(`Unable to create collection for ${label}`);220 }221222 let collectionId = null;223 creationResult.result.events.forEach(({event: {data, method, section}}) => {224 if ((section === 'common') && (method === 'CollectionCreated')) {225 collectionId = parseInt(data[0].toString(), 10);226 }227 });228229 if (collectionId === null) {230 throw Error(`No CollectionCreated event for ${label}`)231 }232233 return collectionId;234 }235236 static extractTokensFromCreationResult(creationResult: ITransactionResult, label = 'new tokens') {237 if (creationResult.status !== this.transactionStatus.SUCCESS) {238 throw Error(`Unable to create tokens for ${label}`);239 }240 let success = false, tokens = [] as any;241 creationResult.result.events.forEach(({event: {data, method, section}}) => {242 if (method === 'ExtrinsicSuccess') {243 success = true;244 } else if ((section === 'common') && (method === 'ItemCreated')) {245 tokens.push({246 collectionId: parseInt(data[0].toString(), 10),247 tokenId: parseInt(data[1].toString(), 10),248 owner: data[2].toJSON()249 });250 }251 });252 return {success, tokens};253 }254255 static extractTokensFromBurnResult(burnResult: ITransactionResult, label = 'burned tokens') {256 if (burnResult.status !== this.transactionStatus.SUCCESS) {257 throw Error(`Unable to burn tokens for ${label}`);258 }259 let success = false, tokens = [] as any;260 burnResult.result.events.forEach(({event: {data, method, section}}) => {261 if (method === 'ExtrinsicSuccess') {262 success = true;263 } else if ((section === 'common') && (method === 'ItemDestroyed')) {264 tokens.push({265 collectionId: parseInt(data[0].toString(), 10),266 tokenId: parseInt(data[1].toString(), 10),267 owner: data[2].toJSON()268 });269 }270 });271 return {success, tokens};272 }273274 static findCollectionInEvents(events: {event: IChainEvent}[], collectionId: number, expectedSection: string, expectedMethod: string, label?: string) {275 let eventId = null;276 events.forEach(({event: {data, method, section}}) => {277 if ((section === expectedSection) && (method === expectedMethod)) {278 eventId = parseInt(data[0].toString(), 10);279 }280 });281282 if (eventId === null) {283 throw Error(`No ${expectedMethod} event for ${label}`);284 }285 return eventId === collectionId;286 }287288 static isTokenTransferSuccess(events: {event: IChainEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {289 const normalizeAddress = (address: string | ICrossAccountId) => {290 if(typeof address === 'string') return address;291 let obj = {} as any;292 Object.keys(address).forEach(k => {293 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];294 });295 if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};296 if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};297 return address;298 }299 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;300 events.forEach(({event: {data, method, section}}) => {301 if ((section === 'common') && (method === 'Transfer')) {302 let hData = (data as any).toJSON();303 transfer = {304 collectionId: hData[0],305 tokenId: hData[1],306 from: normalizeAddress(hData[2]),307 to: normalizeAddress(hData[3]),308 amount: BigInt(hData[4])309 };310 }311 });312 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;313 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);314 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);315 isSuccess = isSuccess && amount === transfer.amount;316 return isSuccess;317 }318}319320321class ChainHelperBase {322 transactionStatus = UniqueUtil.transactionStatus;323 chainLogType = UniqueUtil.chainLogType;324 util: typeof UniqueUtil;325 logger: ILogger;326 api: ApiPromise | null;327 forcedNetwork: TUniqueNetworks | null;328 network: TUniqueNetworks | null;329 chainLog: IUniqueHelperLog[];330331 constructor(logger?: ILogger) {332 this.util = UniqueUtil;333 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();334 this.logger = logger;335 this.api = null;336 this.forcedNetwork = null;337 this.network = null;338 this.chainLog = [];339 }340341 clearChainLog(): void {342 this.chainLog = [];343 }344345 forceNetwork(value: TUniqueNetworks): void {346 this.forcedNetwork = value;347 }348349 async connect(wsEndpoint: string, listeners?: IApiListeners) {350 if (this.api !== null) throw Error('Already connected');351 const { api, network } = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);352 this.api = api;353 this.network = network;354 }355356 async disconnect() {357 if (this.api === null) return;358 await this.api.disconnect();359 this.api = null;360 this.network = null;361 }362363 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {364 let spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;365 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;366 return 'opal';367 }368369 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {370 let api = new ApiPromise({provider: new WsProvider(wsEndpoint)});371 await api.isReady;372373 const network = await this.detectNetwork(api);374375 await api.disconnect();376377 return network;378 }379380 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{ 381 api: ApiPromise; 382 network: TUniqueNetworks; 383 }> {384 if(typeof network === 'undefined' || network === null) network = 'opal';385 const supportedRPC = {386 opal: {387 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc388 },389 quartz: {390 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc391 },392 unique: {393 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc394 }395 }396 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);397 const rpc = supportedRPC[network];398399 // TODO: investigate how to replace rpc in runtime400 // api._rpcCore.addUserInterfaces(rpc);401402 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});403404 await api.isReadyOrError;405406 if (typeof listeners === 'undefined') listeners = {};407 for (let event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {408 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;409 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);410 }411412 return {api, network};413 }414415 getTransactionStatus(data: {events: {event: IChainEvent}[], status: any}) {416 const {events, status} = data;417 if (status.isReady) {418 return this.transactionStatus.NOT_READY;419 }420 if (status.isBroadcast) {421 return this.transactionStatus.NOT_READY;422 }423 if (status.isInBlock || status.isFinalized) {424 const errors = events.filter(e => e.event.data.method === 'ExtrinsicFailed');425 if (errors.length > 0) {426 return this.transactionStatus.FAIL;427 }428 if (events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {429 return this.transactionStatus.SUCCESS;430 }431 }432433 return this.transactionStatus.FAIL;434 }435436 signTransaction(sender: TSigner, transaction: any, label = 'transaction', options = null) {437 const sign = (callback: any) => {438 if(options !== null) return transaction.signAndSend(sender, options, callback);439 return transaction.signAndSend(sender, callback);440 }441 return new Promise(async (resolve, reject) => {442 try {443 let unsub = await sign((result: any) => {444 const status = this.getTransactionStatus(result);445446 if (status === this.transactionStatus.SUCCESS) {447 this.logger.log(`${label} successful`);448 unsub();449 resolve({result, status});450 } else if (status === this.transactionStatus.FAIL) {451 let moduleError = null;452453 if (result.hasOwnProperty('dispatchError')) {454 const dispatchError = result['dispatchError'];455456 if (dispatchError && dispatchError.isModule) {457 const modErr = dispatchError.asModule;458 const errorMeta = dispatchError.registry.findMetaError(modErr);459460 moduleError = `${errorMeta.section}.${errorMeta.name}`;461 }462 else {463 this.logger.log(result, this.logger.level.ERROR);464 }465 }466467 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);468 unsub();469 reject({status, moduleError, result});470 }471 });472 } catch (e) {473 this.logger.log(e, this.logger.level.ERROR);474 reject(e);475 }476 });477 }478479 constructApiCall(apiCall: string, params: any[]) {480 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);481 let call = this.api as any;482 for(let part of apiCall.slice(4).split('.')) {483 call = call[part];484 }485 return call(...params);486 }487488 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=false, failureMessage='expected success') {489 if(this.api === null) throw Error('API not initialized');490 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);491492 const startTime = (new Date()).getTime();493 let result: ITransactionResult;494 let events = [];495 try {496 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), extrinsic) as ITransactionResult;497 events = result.result.events.map((x: any) => x.toHuman());498 }499 catch(e) {500 if(!(e as object).hasOwnProperty('status')) throw e;501 result = e as ITransactionResult;502 }503504 const endTime = (new Date()).getTime();505506 let log = {507 executedAt: endTime,508 executionTime: endTime - startTime,509 type: this.chainLogType.EXTRINSIC,510 status: result.status,511 call: extrinsic,512 params513 } as IUniqueHelperLog;514515 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;516 if(events.length > 0) log.events = events;517518 this.chainLog.push(log);519520 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(failureMessage);521 return result;522 }523524 async callRpc(rpc: string, params?: any[]) {525 if(typeof params === 'undefined') params = [];526 if(this.api === null) throw Error('API not initialized');527 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);528529 const startTime = (new Date()).getTime();530 let result, log = {531 type: this.chainLogType.RPC,532 call: rpc,533 params534 } as IUniqueHelperLog, error = null;535536 try {537 result = await this.constructApiCall(rpc, params);538 }539 catch(e) {540 error = e;541 }542543 const endTime = (new Date()).getTime();544545 log.executedAt = endTime;546 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';547 log.executionTime = endTime - startTime;548549 this.chainLog.push(log);550551 if(error !== null) throw error;552553 return result;554 }555556 getSignerAddress(signer: IKeyringPair | string): string {557 if(typeof signer === 'string') return signer;558 return signer.address;559 }560}561562563class HelperGroup {564 helper: UniqueHelper;565566 constructor(uniqueHelper: UniqueHelper) {567 this.helper = uniqueHelper;568 }569}570571572class CollectionGroup extends HelperGroup {573 /**574 * Get number of blocks when sponsored transaction is available.575 *576 * @param collectionId ID of collection577 * @param tokenId ID of token578 * @param addressObj 579 * @returns number of blocks or null if sponsorship hasn't been set580 */581 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {582 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();583 }584585 /**586 * Get number of collection created on current chain.587 * 588 * @returns number of created collections589 */590 async getTotalCount(): Promise<number> {591 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();592 }593594 /**595 * Get information about the collection with additional data, including the number of tokens it contains, its administrators, the normalized address of the collection's owner, and decoded name and description.596 * 597 * @param collectionId ID of collection598 * @returns collection information object599 */600 async getData(collectionId: number): Promise<{601 id: number;602 name: string;603 description: string;604 tokensCount: number;605 admins: ICrossAccountId[];606 normalizedOwner: TSubstrateAccount;607 raw: any608 } | null> {609 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);610 let humanCollection = collection.toHuman(), collectionData = {611 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],612 raw: humanCollection613 } as any, jsonCollection = collection.toJSON();614 if (humanCollection === null) return null;615 collectionData.raw.limits = jsonCollection.limits;616 collectionData.raw.permissions = jsonCollection.permissions;617 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);618 for (let key of ['name', 'description']) {619 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);620 }621622 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode)) ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId) : 0;623 collectionData.admins = await this.getAdmins(collectionId);624625 return collectionData;626 }627628 /**629 * Get the normalized addresses of the collection's administrators.630 * 631 * @param collectionId ID of collection632 * @returns array of administrators633 */634 async getAdmins(collectionId: number): Promise<ICrossAccountId[]> {635 let normalized = [];636 for(let admin of (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman()) {637 if(admin.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(admin.Substrate)});638 else normalized.push(admin);639 }640 return normalized;641 }642643 /**644 * Get the effective limits of the collection instead of null for default values645 * 646 * @param collectionId ID of collection647 * @returns object of collection limits648 */649 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {650 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();651 }652653 /**654 * Burns the collection if the signer has sufficient permissions and collection is empty.655 * 656 * @param signer keyring of signer657 * @param collectionId ID of collection658 * @param label extra label for log659 * @returns bool true on success660 */661 async burn(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {662 if(typeof label === 'undefined') label = `collection #${collectionId}`;663 const result = await this.helper.executeExtrinsic(664 signer,665 'api.tx.unique.destroyCollection', [collectionId],666 true, `Unable to burn collection for ${label}`667 );668669 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed', label);670 }671672 /**673 * Sets the sponsor for the collection (Requires the Substrate address).674 * 675 * @param signer keyring of signer676 * @param collectionId ID of collection677 * @param sponsorAddress Sponsor substrate address678 * @param label extra label for log679 * @returns bool true on success680 */681 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount, label?: string): Promise<boolean> {682 if(typeof label === 'undefined') label = `collection #${collectionId}`;683 const result = await this.helper.executeExtrinsic(684 signer,685 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],686 true, `Unable to set collection sponsor for ${label}`687 );688689 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet', label);690 }691692 /**693 * Confirms consent to sponsor the collection on behalf of the signer.694 * 695 * @param signer keyring of signer696 * @param collectionId ID of collection697 * @param label extra label for log698 * @returns bool true on success699 */700 async confirmSponsorship(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {701 if(typeof label === 'undefined') label = `collection #${collectionId}`;702 const result = await this.helper.executeExtrinsic(703 signer,704 'api.tx.unique.confirmSponsorship', [collectionId],705 true, `Unable to confirm collection sponsorship for ${label}`706 );707708 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed', label);709 }710711 /**712 * Sets the limits of the collection. At least one limit must be specified for a correct call.713 * 714 * @param signer keyring of signer715 * @param collectionId ID of collection716 * @param limits collection limits object717 * @param label extra label for log718 * @returns bool true on success719 */720 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits, label?: string): Promise<boolean> {721 if(typeof label === 'undefined') label = `collection #${collectionId}`;722 const result = await this.helper.executeExtrinsic(723 signer,724 'api.tx.unique.setCollectionLimits', [collectionId, limits],725 true, `Unable to set collection limits for ${label}`726 );727728 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet', label);729 }730731 /**732 * Changes the owner of the collection to the new Substrate address.733 * 734 * @param signer keyring of signer735 * @param collectionId ID of collection736 * @param ownerAddress substrate address of new owner737 * @param label extra label for log738 * @returns bool true on success739 */740 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount, label?: string): Promise<boolean> {741 if(typeof label === 'undefined') label = `collection #${collectionId}`;742 const result = await this.helper.executeExtrinsic(743 signer,744 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],745 true, `Unable to change collection owner for ${label}`746 );747748 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged', label);749 }750751 /**752 * Adds a collection administrator. 753 * 754 * @param signer keyring of signer755 * @param collectionId ID of collection756 * @param adminAddressObj Administrator address (substrate or ethereum)757 * @param label extra label for log758 * @returns bool true on success759 */760 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {761 if(typeof label === 'undefined') label = `collection #${collectionId}`;762 const result = await this.helper.executeExtrinsic(763 signer,764 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],765 true, `Unable to add collection admin for ${label}`766 );767768 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded', label);769 }770771 /**772 * Removes a collection administrator.773 * 774 * @param signer keyring of signer775 * @param collectionId ID of collection776 * @param adminAddressObj Administrator address (substrate or ethereum)777 * @param label extra label for log778 * @returns bool true on success779 */780 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {781 if(typeof label === 'undefined') label = `collection #${collectionId}`;782 const result = await this.helper.executeExtrinsic(783 signer,784 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],785 true, `Unable to remove collection admin for ${label}`786 );787788 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved', label);789 }790791 /**792 * Sets onchain permissions for selected collection.793 * 794 * @param signer keyring of signer795 * @param collectionId ID of collection796 * @param permissions collection permissions object797 * @param label extra label for log798 * @returns bool true on success799 */800 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions, label?: string): Promise<boolean> {801 if(typeof label === 'undefined') label = `collection #${collectionId}`;802 const result = await this.helper.executeExtrinsic(803 signer,804 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],805 true, `Unable to set collection permissions for ${label}`806 );807808 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet', label);809 }810811 /**812 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.813 * 814 * @param signer keyring of signer815 * @param collectionId ID of collection816 * @param permissions nesting permissions object817 * @param label extra label for log818 * @returns bool true on success819 */820 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions, label?: string): Promise<boolean> {821 return await this.setPermissions(signer, collectionId, {nesting: permissions}, label);822 }823824 /**825 * Disables nesting for selected collection.826 * 827 * @param signer keyring of signer828 * @param collectionId ID of collection829 * @param label extra label for log830 * @returns bool true on success831 */832 async disableNesting(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {833 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}}, label);834 }835836 /**837 * Sets onchain properties to the collection.838 * 839 * @param signer keyring of signer840 * @param collectionId ID of collection841 * @param properties array of property objects842 * @param label extra label for log843 * @returns bool true on success844 */845 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[], label?: string): Promise<boolean> {846 if(typeof label === 'undefined') label = `collection #${collectionId}`;847 const result = await this.helper.executeExtrinsic(848 signer,849 'api.tx.unique.setCollectionProperties', [collectionId, properties],850 true, `Unable to set collection properties for ${label}`851 );852853 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet', label);854 }855856 /**857 * Deletes onchain properties from the collection.858 * 859 * @param signer keyring of signer860 * @param collectionId ID of collection861 * @param propertyKeys array of property keys to delete862 * @param label 863 * @returns 864 */865 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[], label?: string): Promise<boolean> {866 if(typeof label === 'undefined') label = `collection #${collectionId}`;867 const result = await this.helper.executeExtrinsic(868 signer,869 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],870 true, `Unable to delete collection properties for ${label}`871 );872873 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted', label);874 }875876 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {877 const result = await this.helper.executeExtrinsic(878 signer,879 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],880 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`881 );882883 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);884 }885886 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {887 const result = await this.helper.executeExtrinsic(888 signer,889 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],890 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`891 );892 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);893 }894895 async burnToken(signer: TSigner, collectionId: number, tokenId: number, label?: string, amount=1n): Promise<{896 success: boolean,897 token: number | null898 }> {899 if(typeof label === 'undefined') label = `collection #${collectionId}`;900 const burnResult = await this.helper.executeExtrinsic(901 signer,902 'api.tx.unique.burnItem', [collectionId, tokenId, amount],903 true, `Unable to burn token for ${label}`904 );905 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);906 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');907 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};908 }909910 async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, label?: string, amount=1n): Promise<boolean> {911 if(typeof label === 'undefined') label = `collection #${collectionId}`;912 const burnResult = await this.helper.executeExtrinsic(913 signer,914 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],915 true, `Unable to burn token from for ${label}`916 );917 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);918 return burnedTokens.success && burnedTokens.tokens.length > 0;919 }920921 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=1n) {922 if(typeof label === 'undefined') label = `collection #${collectionId}`;923 const approveResult = await this.helper.executeExtrinsic(924 signer, 925 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],926 true, `Unable to approve token for ${label}`927 );928929 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved', label);930 }931932 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {933 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();934 }935936 async getLastTokenId(collectionId: number): Promise<number> {937 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();938 }939940 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {941 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON()942 }943}944945class NFTnRFT extends CollectionGroup {946 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {947 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON()948 }949950 async getToken(collectionId: number, tokenId: number, blockHashAt?: string, propertyKeys?: string[]): Promise<{951 properties: IProperty[];952 owner: ICrossAccountId;953 normalizedOwner: ICrossAccountId;954 }| null> {955 let tokenData;956 if(typeof blockHashAt === 'undefined') {957 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);958 }959 else {960 if(typeof propertyKeys === 'undefined') {961 let collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();962 if(!collection) return null;963 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);964 }965 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);966 }967 tokenData = tokenData.toHuman();968 if (tokenData === null || tokenData.owner === null) return null;969 let owner = {} as any;970 for (let key of Object.keys(tokenData.owner)) {971 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];972 }973 tokenData.normalizedOwner = crossAccountIdFromLower(owner);974 return tokenData;975 }976977 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[], label?: string): Promise<boolean> {978 if(typeof label === 'undefined') label = `collection #${collectionId}`;979 const result = await this.helper.executeExtrinsic(980 signer,981 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],982 true, `Unable to set token property permissions for ${label}`983 );984985 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet', label);986 }987988 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[], label?: string): Promise<boolean> {989 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;990 const result = await this.helper.executeExtrinsic(991 signer,992 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],993 true, `Unable to set token properties for ${label}`994 );995996 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet', label);997 }998999 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[], label?: string): Promise<boolean> {1000 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;1001 const result = await this.helper.executeExtrinsic(1002 signer,1003 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1004 true, `Unable to delete token properties for ${label}`1005 );10061007 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted', label);1008 }10091010 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT', errorLabel = 'Unable to mint collection'): Promise<UniqueCollectionBase> {1011 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1012 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1013 for (let key of ['name', 'description', 'tokenPrefix']) {1014 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);1015 }1016 const creationResult = await this.helper.executeExtrinsic(1017 signer,1018 'api.tx.unique.createCollectionEx', [collectionOptions],1019 true, errorLabel1020 );1021 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1022 }10231024 getCollectionObject(collectionId: number): any {1025 return null;1026 }10271028 getTokenObject(collectionId: number, tokenId: number): any {1029 return null;1030 }1031}103210331034class NFTGroup extends NFTnRFT {1035 getCollectionObject(collectionId: number): UniqueNFTCollection {1036 return new UniqueNFTCollection(collectionId, this.helper);1037 }10381039 getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1040 return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1041 }10421043 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1044 let owner;1045 if (typeof blockHashAt === 'undefined') {1046 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1047 } else {1048 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1049 }1050 return crossAccountIdFromLower(owner.toJSON());1051 }10521053 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1054 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1055 }10561057 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1058 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1059 }10601061 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1062 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1063 }10641065 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1066 let owner;1067 if (typeof blockHashAt === 'undefined') {1068 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1069 } else {1070 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1071 }10721073 if (owner === null) return null;10741075 owner = owner.toHuman();10761077 return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1078 }10791080 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1081 let children;1082 if(typeof blockHashAt === 'undefined') {1083 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1084 } else {1085 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1086 }10871088 return children.toJSON().map((x: any) => {1089 return {collectionId: x.collection, tokenId: x.token};1090 });1091 }10921093 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, label='nest token'): Promise<boolean> {1094 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1095 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1096 if(!result) {1097 throw Error(`Unable to nest token for ${label}`);1098 }1099 return result;1100 }11011102 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId, label='unnest token'): Promise<boolean> {1103 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1104 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1105 if(!result) {1106 throw Error(`Unable to unnest token for ${label}`);1107 }1108 return result;1109 }11101111 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueNFTCollection> {1112 return await super.mintCollection(signer, collectionOptions, 'NFT', `Unable to mint NFT collection for ${label}`) as UniqueNFTCollection;1113 }11141115 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }, label?: string): Promise<UniqueNFTToken> {1116 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1117 const creationResult = await this.helper.executeExtrinsic(1118 signer,1119 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1120 nft: {1121 properties: data.properties1122 }1123 }],1124 true, `Unable to mint NFT token for ${label}`1125 );1126 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1127 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1128 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1129 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1130 }11311132 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1133 if(typeof label === 'undefined') label = `collection #${collectionId}`;1134 const creationResult = await this.helper.executeExtrinsic(1135 signer,1136 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1137 true, `Unable to mint NFT tokens for ${label}`1138 );1139 const collection = this.getCollectionObject(collectionId);1140 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1141 }11421143 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1144 if(typeof label === 'undefined') label = `collection #${collectionId}`;1145 let rawTokens = [];1146 for (let token of tokens) {1147 let raw = {NFT: {properties: token.properties}};1148 rawTokens.push(raw);1149 }1150 const creationResult = await this.helper.executeExtrinsic(1151 signer,1152 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1153 true, `Unable to mint NFT tokens for ${label}`1154 );1155 const collection = this.getCollectionObject(collectionId);1156 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1157 }11581159 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string): Promise<{ success: boolean; token: number | null; }> {1160 return await super.burnToken(signer, collectionId, tokenId, label, 1n);1161 }11621163 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {1164 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, 1n);1165 }1166}116711681169class RFTGroup extends NFTnRFT {1170 getCollectionObject(collectionId: number): UniqueRFTCollection {1171 return new UniqueRFTCollection(collectionId, this.helper);1172 }11731174 getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1175 return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1176 }11771178 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1179 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1180 }11811182 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1183 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1184 }11851186 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=100n): Promise<boolean> {1187 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1188 }11891190 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n): Promise<boolean> {1191 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1192 }11931194 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueRFTCollection> {1195 return await super.mintCollection(signer, collectionOptions, 'RFT', `Unable to mint RFT collection for ${label}`) as UniqueRFTCollection;1196 }11971198 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }, label?: string): Promise<UniqueRFTToken> {1199 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1200 const creationResult = await this.helper.executeExtrinsic(1201 signer,1202 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1203 refungible: {1204 pieces: data.pieces,1205 properties: data.properties1206 }1207 }],1208 true, `Unable to mint RFT token for ${label}`1209 );1210 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1211 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1212 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1213 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1214 }12151216 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1217 throw Error('Not implemented');1218 if(typeof label === 'undefined') label = `collection #${collectionId}`;1219 const creationResult = await this.helper.executeExtrinsic(1220 signer,1221 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1222 true, `Unable to mint RFT tokens for ${label}`1223 );1224 const collection = this.getCollectionObject(collectionId);1225 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1226 }12271228 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1229 if(typeof label === 'undefined') label = `collection #${collectionId}`;1230 let rawTokens = [];1231 for (let token of tokens) {1232 let raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1233 rawTokens.push(raw);1234 }1235 const creationResult = await this.helper.executeExtrinsic(1236 signer,1237 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1238 true, `Unable to mint RFT tokens for ${label}`1239 );1240 const collection = this.getCollectionObject(collectionId);1241 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1242 }12431244 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string, amount=100n): Promise<{ success: boolean; token: number | null; }> {1245 return await super.burnToken(signer, collectionId, tokenId, label, amount);1246 }12471248 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=100n) {1249 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, amount);1250 }12511252 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1253 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1254 }12551256 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint, label?: string): Promise<boolean> {1257 if(typeof label === 'undefined') label = `collection #${collectionId}`;1258 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1259 const repartitionResult = await this.helper.executeExtrinsic(1260 signer,1261 'api.tx.unique.repartition', [collectionId, tokenId, amount],1262 true, `Unable to repartition RFT token for ${label}`1263 );1264 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated', label);1265 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed', label);1266 }1267}126812691270class FTGroup extends CollectionGroup {1271 getCollectionObject(collectionId: number): UniqueFTCollection {1272 return new UniqueFTCollection(collectionId, this.helper);1273 }12741275 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints: number = 0, errorLabel = 'Unable to mint collection'): Promise<UniqueFTCollection> {1276 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1277 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1278 collectionOptions.mode = {fungible: decimalPoints};1279 for (let key of ['name', 'description', 'tokenPrefix']) {1280 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);1281 }1282 const creationResult = await this.helper.executeExtrinsic(1283 signer,1284 'api.tx.unique.createCollectionEx', [collectionOptions],1285 true, errorLabel1286 );1287 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1288 }12891290 async mintTokens(signer: TSigner, collectionId: number, owner: ICrossAccountId | string, amount: bigint, label?: string): Promise<boolean> {1291 if(typeof label === 'undefined') label = `collection #${collectionId}`;1292 const creationResult = await this.helper.executeExtrinsic(1293 signer,1294 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1295 fungible: {1296 value: amount1297 }1298 }],1299 true, `Unable to mint fungible tokens for ${label}`1300 );1301 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1302 }13031304 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string): Promise<boolean> {1305 if(typeof label === 'undefined') label = `collection #${collectionId}`;1306 let rawTokens = [];1307 for (let token of tokens) {1308 let raw = {Fungible: {Value: token.value}};1309 rawTokens.push(raw);1310 }1311 const creationResult = await this.helper.executeExtrinsic(1312 signer,1313 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1314 true, `Unable to mint RFT tokens for ${label}`1315 );1316 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1317 }13181319 async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1320 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1321 }13221323 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1324 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1325 }13261327 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount: bigint) {1328 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1329 }13301331 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {1332 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1333 }13341335 async burnTokens(signer: IKeyringPair, collectionId: number, amount=100n, label?: string): Promise<boolean> {1336 return (await super.burnToken(signer, collectionId, 0, label, amount)).success;1337 }13381339 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=100n, label?: string): Promise<boolean> {1340 return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, label, amount);1341 }13421343 async getTotalPieces(collectionId: number): Promise<bigint> {1344 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1345 }13461347 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {1348 return super.approveToken(signer, collectionId, 0, toAddressObj, label, amount);1349 }13501351 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1352 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1353 }1354}135513561357class ChainGroup extends HelperGroup {1358 getChainProperties(): IChainProperties {1359 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1360 return {1361 ss58Format: properties.ss58Format.toJSON(),1362 tokenDecimals: properties.tokenDecimals.toJSON(),1363 tokenSymbol: properties.tokenSymbol.toJSON()1364 };1365 }13661367 async getLatestBlockNumber(): Promise<number> {1368 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1369 }13701371 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1372 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1373 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1374 return blockHash;1375 }13761377 async getNonce(address: TSubstrateAccount): Promise<number> {1378 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1379 }1380}138113821383class BalanceGroup extends HelperGroup {1384 getOneTokenNominal(): bigint {1385 const chainProperties = this.helper.chain.getChainProperties();1386 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1387 }13881389 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {1390 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();1391 }13921393 async getEthereum(address: TEthereumAccount): Promise<bigint> {1394 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();1395 }13961397 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {1398 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true, `Unable to transfer balance from ${this.helper.getSignerAddress(signer)} to ${address}`);13991400 let transfer = {from: null, to: null, amount: 0n} as any;1401 result.result.events.forEach(({event: {data, method, section}}) => {1402 if ((section === 'balances') && (method === 'Transfer')) {1403 transfer = {1404 from: this.helper.address.normalizeSubstrate(data[0]),1405 to: this.helper.address.normalizeSubstrate(data[1]),1406 amount: BigInt(data[2])1407 };1408 }1409 });1410 let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;1411 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;1412 isSuccess = isSuccess && BigInt(amount) === transfer.amount;1413 return isSuccess;1414 }1415}141614171418class AddressGroup extends HelperGroup {1419 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {1420 return this.helper.util.normalizeSubstrateAddress(address, ss58Format);1421 }14221423 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {1424 let info = this.helper.chain.getChainProperties();1425 return encodeAddress(decodeAddress(address), info.ss58Format);1426 }14271428 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {1429 if(!toChainFormat) return evmToAddress(ethAddress);1430 let info = this.helper.chain.getChainProperties();1431 return evmToAddress(ethAddress, info.ss58Format);1432 }14331434 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {1435 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));1436 }1437}143814391440export class UniqueHelper extends ChainHelperBase {1441 chain: ChainGroup;1442 balance: BalanceGroup;1443 address: AddressGroup;1444 collection: CollectionGroup;1445 nft: NFTGroup;1446 rft: RFTGroup;1447 ft: FTGroup;14481449 constructor(logger?: ILogger) {1450 super(logger);1451 this.chain = new ChainGroup(this);1452 this.balance = new BalanceGroup(this);1453 this.address = new AddressGroup(this);1454 this.collection = new CollectionGroup(this);1455 this.nft = new NFTGroup(this);1456 this.rft = new RFTGroup(this);1457 this.ft = new FTGroup(this);1458 } 1459}146014611462class UniqueCollectionBase {1463 helper: UniqueHelper;1464 collectionId: number;14651466 constructor(collectionId: number, uniqueHelper: UniqueHelper) {1467 this.collectionId = collectionId;1468 this.helper = uniqueHelper;1469 }14701471 async getData() {1472 return await this.helper.collection.getData(this.collectionId);1473 }14741475 async getLastTokenId() {1476 return await this.helper.collection.getLastTokenId(this.collectionId);1477 }14781479 async isTokenExists(tokenId: number) {1480 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);1481 }14821483 async getAdmins() {1484 return await this.helper.collection.getAdmins(this.collectionId);1485 }14861487 async getEffectiveLimits() {1488 return await this.helper.collection.getEffectiveLimits(this.collectionId);1489 }14901491 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount, label?: string) {1492 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress, label);1493 }14941495 async confirmSponsorship(signer: TSigner, label?: string) {1496 return await this.helper.collection.confirmSponsorship(signer, this.collectionId, label);1497 }14981499 async setLimits(signer: TSigner, limits: ICollectionLimits, label?: string) {1500 return await this.helper.collection.setLimits(signer, this.collectionId, limits, label);1501 }15021503 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount, label?: string) {1504 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress, label);1505 }15061507 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {1508 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj, label);1509 }15101511 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {1512 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj, label);1513 }15141515 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {1516 return await this.helper.collection.setProperties(signer, this.collectionId, properties, label);1517 }15181519 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {1520 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys, label);1521 }15221523 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {1524 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);1525 }15261527 async setPermissions(signer: TSigner, permissions: ICollectionPermissions, label?: string) {1528 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions, label);1529 }15301531 async enableNesting(signer: TSigner, permissions: INestingPermissions, label?: string) {1532 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions, label);1533 }15341535 async disableNesting(signer: TSigner, label?: string) {1536 return await this.helper.collection.disableNesting(signer, this.collectionId, label);1537 }15381539 async burn(signer: TSigner, label?: string) {1540 return await this.helper.collection.burn(signer, this.collectionId, label);1541 }1542}154315441545class UniqueNFTCollection extends UniqueCollectionBase {1546 getTokenObject(tokenId: number) {1547 return new UniqueNFTToken(tokenId, this);1548 }15491550 async getTokensByAddress(addressObj: ICrossAccountId) {1551 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);1552 }15531554 async getToken(tokenId: number, blockHashAt?: string) {1555 return await this.helper.nft.getToken(this.collectionId, tokenId, blockHashAt);1556 }15571558 async getTokenOwner(tokenId: number, blockHashAt?: string) {1559 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);1560 }15611562 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {1563 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);1564 }15651566 async getTokenChildren(tokenId: number, blockHashAt?: string) {1567 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);1568 }15691570 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {1571 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);1572 }15731574 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1575 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);1576 }15771578 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {1579 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label);1580 }15811582 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {1583 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);1584 }15851586 async mintToken(signer: TSigner, owner: ICrossAccountId, properties?: IProperty[], label?: string) {1587 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties}, label);1588 }15891590 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string) {1591 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens, label);1592 }15931594 async burnToken(signer: TSigner, tokenId: number, label?: string) {1595 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId, label);1596 }15971598 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {1599 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);1600 }16011602 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {1603 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);1604 }16051606 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {1607 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);1608 }16091610 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken, label?: string) {1611 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj, label);1612 }16131614 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {1615 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj, label);1616 }1617}161816191620class UniqueRFTCollection extends UniqueCollectionBase {1621 getTokenObject(tokenId: number) {1622 return new UniqueRFTToken(tokenId, this);1623 }16241625 async getTokensByAddress(addressObj: ICrossAccountId) {1626 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);1627 }16281629 async getTop10TokenOwners(tokenId: number) {1630 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);1631 }16321633 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {1634 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);1635 }16361637 async getTokenTotalPieces(tokenId: number) {1638 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);1639 }16401641 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=100n) {1642 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);1643 }16441645 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {1646 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);1647 }16481649 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {1650 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label, amount);1651 }16521653 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1654 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);1655 }16561657 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint, label?: string) {1658 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount, label);1659 }16601661 async mintToken(signer: TSigner, owner: ICrossAccountId, pieces=100n, properties?: IProperty[], label?: string) {1662 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties}, label);1663 }16641665 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string) {1666 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens, label);1667 }16681669 async burnToken(signer: TSigner, tokenId: number, amount=100n, label?: string) {1670 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, label, amount);1671 }16721673 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {1674 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);1675 }16761677 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {1678 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);1679 }16801681 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {1682 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);1683 }1684}168516861687class UniqueFTCollection extends UniqueCollectionBase {1688 async mint(signer: TSigner, owner: ICrossAccountId, amount: bigint, label?: string) {1689 return await this.helper.ft.mintTokens(signer, this.collectionId, owner, amount, label);1690 }16911692 async mintWithOneOwner(signer: TSigner, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string) {1693 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, owner, tokens, label);1694 }16951696 async getBalance(addressObj: ICrossAccountId) {1697 return await this.helper.ft.getBalance(this.collectionId, addressObj);1698 }16991700 async getTop10Owners() {1701 return await this.helper.ft.getTop10Owners(this.collectionId);1702 }17031704 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount: bigint) {1705 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);1706 }17071708 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {1709 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);1710 }17111712 async burnTokens(signer: TSigner, amount: bigint, label?: string) {1713 return await this.helper.ft.burnTokens(signer, this.collectionId, amount, label);1714 }17151716 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount: bigint, label?: string) {1717 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount, label);1718 }17191720 async getTotalPieces() {1721 return await this.helper.ft.getTotalPieces(this.collectionId);1722 }17231724 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {1725 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount, label);1726 }17271728 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1729 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);1730 }1731}173217331734class UniqueTokenBase implements IToken {1735 collection: UniqueNFTCollection | UniqueRFTCollection;1736 collectionId: number;1737 tokenId: number;17381739 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {1740 this.collection = collection;1741 this.collectionId = collection.collectionId;1742 this.tokenId = tokenId;1743 }17441745 async getNextSponsored(addressObj: ICrossAccountId) {1746 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);1747 }17481749 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {1750 return await this.collection.setTokenProperties(signer, this.tokenId, properties, label);1751 }17521753 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {1754 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys, label);1755 }1756}175717581759class UniqueNFTToken extends UniqueTokenBase {1760 collection: UniqueNFTCollection;17611762 constructor(tokenId: number, collection: UniqueNFTCollection) {1763 super(tokenId, collection);1764 this.collection = collection;1765 }17661767 async getData(blockHashAt?: string) {1768 return await this.collection.getToken(this.tokenId, blockHashAt);1769 }17701771 async getOwner(blockHashAt?: string) {1772 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);1773 }17741775 async getTopmostOwner(blockHashAt?: string) {1776 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);1777 }17781779 async getChildren(blockHashAt?: string) {1780 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);1781 }17821783 async nest(signer: TSigner, toTokenObj: IToken, label?: string) {1784 return await this.collection.nestToken(signer, this.tokenId, toTokenObj, label);1785 }17861787 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {1788 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj, label);1789 }17901791 async transfer(signer: TSigner, addressObj: ICrossAccountId) {1792 return await this.collection.transferToken(signer, this.tokenId, addressObj);1793 }17941795 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1796 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);1797 }17981799 async approve(signer: TSigner, toAddressObj: ICrossAccountId, label?: string) {1800 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, label);1801 }18021803 async isApproved(toAddressObj: ICrossAccountId) {1804 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);1805 }18061807 async burn(signer: TSigner, label?: string) {1808 return await this.collection.burnToken(signer, this.tokenId, label);1809 }1810}18111812class UniqueRFTToken extends UniqueTokenBase {1813 collection: UniqueRFTCollection;18141815 constructor(tokenId: number, collection: UniqueRFTCollection) {1816 super(tokenId, collection);1817 this.collection = collection;1818 }18191820 async getTop10Owners() {1821 return await this.collection.getTop10TokenOwners(this.tokenId);1822 }18231824 async getBalance(addressObj: ICrossAccountId) {1825 return await this.collection.getTokenBalance(this.tokenId, addressObj);1826 }18271828 async getTotalPieces() {1829 return await this.collection.getTokenTotalPieces(this.tokenId);1830 }18311832 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=100n) {1833 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);1834 }18351836 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {1837 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);1838 }18391840 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {1841 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount, label);1842 }18431844 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {1845 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);1846 }18471848 async repartition(signer: TSigner, amount: bigint, label?: string) {1849 return await this.collection.repartitionToken(signer, this.tokenId, amount, label);1850 }18511852 async burn(signer: TSigner, amount=100n, label?: string) {1853 return await this.collection.burnToken(signer, this.tokenId, amount, label);1854 }1855}1/* eslint-disable @typescript-eslint/no-var-requires */2/* eslint-disable function-call-argument-newline */3/* eslint-disable no-prototype-builtins */45import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';6import {ApiInterfaceEvents} from '@polkadot/api/types';7import {IKeyringPair} from '@polkadot/types/types';8import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';91011const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {12 const address = {} as ICrossAccountId;13 if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;14 if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;15 return address;16};171819const nesting = {20 toChecksumAddress(address: string): string {21 if (typeof address === 'undefined') return '';2223 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);2425 address = address.toLowerCase().replace(/^0x/i,'');26 const addressHash = keccakAsHex(address).replace(/^0x/i,'');27 const checksumAddress = ['0x'];2829 for (let i = 0; i < address.length; i++) {30 // If ith character is 8 to f then make it uppercase31 if (parseInt(addressHash[i], 16) > 7) {32 checksumAddress.push(address[i].toUpperCase());33 } else {34 checksumAddress.push(address[i]);35 }36 }37 return checksumAddress.join('');38 },39 tokenIdToAddress(collectionId: number, tokenId: number) {40 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);41 },42};434445interface IChainEvent {46 data: any;47 method: string;48 section: string;49}5051interface ITransactionResult {52 status: 'Fail' | 'Success';53 result: {54 events: {55 event: IChainEvent56 }[];57 },58 moduleError?: string;59}6061interface ILogger {62 log: (msg: any, level?: string) => void;63 level: {64 ERROR: 'ERROR';65 WARNING: 'WARNING';66 INFO: 'INFO';67 [key: string]: string;68 }69}7071interface IUniqueHelperLog {72 executedAt: number;73 executionTime: number;74 type: 'extrinsic' | 'rpc';75 status: 'Fail' | 'Success';76 call: string;77 params: any[];78 moduleError?: string;79 events?: any;80}8182interface IApiListeners {83 connected?: (...args: any[]) => any;84 disconnected?: (...args: any[]) => any;85 error?: (...args: any[]) => any;86 ready?: (...args: any[]) => any; 87 decorated?: (...args: any[]) => any;88}8990interface ICrossAccountId {91 Substrate?: TSubstrateAccount;92 Ethereum?: TEthereumAccount;93}9495interface ICrossAccountIdLower {96 substrate?: TSubstrateAccount;97 ethereum?: TEthereumAccount;98}99100interface ICollectionLimits {101 accountTokenOwnershipLimit?: number | null;102 sponsoredDataSize?: number | null;103 sponsoredDataRateLimit?: {blocks: number} | {sponsoringDisabled: null} | null;104 tokenLimit?: number | null;105 sponsorTransferTimeout?: number | null;106 sponsorApproveTimeout?: number | null;107 ownerCanTransfer?: boolean | null;108 ownerCanDestroy?: boolean | null;109 transfersEnabled?: boolean | null;110}111112interface INestingPermissions {113 tokenOwner?: boolean;114 collectionAdmin?: boolean;115 restricted?: number[] | null;116}117118interface ICollectionPermissions {119 access?: 'Normal' | 'AllowList';120 mintMode?: boolean;121 nesting?: INestingPermissions;122}123124interface IProperty {125 key: string;126 value: string;127}128129interface ITokenPropertyPermission {130 key: string;131 permission: {132 mutable: boolean;133 tokenOwner: boolean;134 collectionAdmin: boolean;135 }136}137138interface IToken {139 collectionId: number;140 tokenId: number;141}142143interface ICollectionCreationOptions {144 name: string | number[];145 description: string | number[];146 tokenPrefix: string | number[];147 mode?: {148 nft?: null;149 refungible?: null;150 fungible?: number;151 }152 permissions?: ICollectionPermissions;153 properties?: IProperty[];154 tokenPropertyPermissions?: ITokenPropertyPermission[];155 limits?: ICollectionLimits;156 pendingSponsor?: TSubstrateAccount;157}158159interface IChainProperties {160 ss58Format: number;161 tokenDecimals: number[];162 tokenSymbol: string[]163}164165type TSubstrateAccount = string;166type TEthereumAccount = string;167type TApiAllowedListeners = 'connected' | 'disconnected' | 'error' | 'ready' | 'decorated';168type TUniqueNetworks = 'opal' | 'quartz' | 'unique';169type TSigner = IKeyringPair; // | 'string'170171class UniqueUtil {172 static transactionStatus = {173 NOT_READY: 'NotReady',174 FAIL: 'Fail',175 SUCCESS: 'Success',176 };177178 static chainLogType = {179 EXTRINSIC: 'extrinsic',180 RPC: 'rpc',181 };182183 static getNestingTokenAddress(collectionId: number, tokenId: number) {184 return nesting.tokenIdToAddress(collectionId, tokenId);185 }186187 static getDefaultLogger(): ILogger {188 return {189 log(msg: any, level = 'INFO') {190 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));191 },192 level: {193 ERROR: 'ERROR',194 WARNING: 'WARNING',195 INFO: 'INFO',196 },197 };198 }199200 static vec2str(arr: string[] | number[]) {201 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');202 }203204 static str2vec(string: string) {205 if (typeof string !== 'string') return string;206 return Array.from(string).map(x => x.charCodeAt(0));207 }208209 static fromSeed(seed: string, ss58Format = 42) {210 const keyring = new Keyring({type: 'sr25519', ss58Format});211 return keyring.addFromUri(seed);212 }213214 static normalizeSubstrateAddress(address: string, ss58Format = 42) {215 return encodeAddress(decodeAddress(address), ss58Format);216 }217218 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult, label = 'new collection') {219 if (creationResult.status !== this.transactionStatus.SUCCESS) {220 throw Error(`Unable to create collection for ${label}`);221 }222223 let collectionId = null;224 creationResult.result.events.forEach(({event: {data, method, section}}) => {225 if ((section === 'common') && (method === 'CollectionCreated')) {226 collectionId = parseInt(data[0].toString(), 10);227 }228 });229230 if (collectionId === null) {231 throw Error(`No CollectionCreated event for ${label}`);232 }233234 return collectionId;235 }236237 static extractTokensFromCreationResult(creationResult: ITransactionResult, label = 'new tokens') {238 if (creationResult.status !== this.transactionStatus.SUCCESS) {239 throw Error(`Unable to create tokens for ${label}`);240 }241 let success = false;242 const tokens = [] as any;243 creationResult.result.events.forEach(({event: {data, method, section}}) => {244 if (method === 'ExtrinsicSuccess') {245 success = true;246 } else if ((section === 'common') && (method === 'ItemCreated')) {247 tokens.push({248 collectionId: parseInt(data[0].toString(), 10),249 tokenId: parseInt(data[1].toString(), 10),250 owner: data[2].toJSON(),251 });252 }253 });254 return {success, tokens};255 }256257 static extractTokensFromBurnResult(burnResult: ITransactionResult, label = 'burned tokens') {258 if (burnResult.status !== this.transactionStatus.SUCCESS) {259 throw Error(`Unable to burn tokens for ${label}`);260 }261 let success = false;262 const tokens = [] as any;263 burnResult.result.events.forEach(({event: {data, method, section}}) => {264 if (method === 'ExtrinsicSuccess') {265 success = true;266 } else if ((section === 'common') && (method === 'ItemDestroyed')) {267 tokens.push({268 collectionId: parseInt(data[0].toString(), 10),269 tokenId: parseInt(data[1].toString(), 10),270 owner: data[2].toJSON(),271 });272 }273 });274 return {success, tokens};275 }276277 static findCollectionInEvents(events: {event: IChainEvent}[], collectionId: number, expectedSection: string, expectedMethod: string, label?: string) {278 let eventId = null;279 events.forEach(({event: {data, method, section}}) => {280 if ((section === expectedSection) && (method === expectedMethod)) {281 eventId = parseInt(data[0].toString(), 10);282 }283 });284285 if (eventId === null) {286 throw Error(`No ${expectedMethod} event for ${label}`);287 }288 return eventId === collectionId;289 }290291 static isTokenTransferSuccess(events: {event: IChainEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {292 const normalizeAddress = (address: string | ICrossAccountId) => {293 if(typeof address === 'string') return address;294 const obj = {} as any;295 Object.keys(address).forEach(k => {296 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];297 });298 if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};299 if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};300 return address;301 };302 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;303 events.forEach(({event: {data, method, section}}) => {304 if ((section === 'common') && (method === 'Transfer')) {305 const hData = (data as any).toJSON();306 transfer = {307 collectionId: hData[0],308 tokenId: hData[1],309 from: normalizeAddress(hData[2]),310 to: normalizeAddress(hData[3]),311 amount: BigInt(hData[4]),312 };313 }314 });315 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;316 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);317 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);318 isSuccess = isSuccess && amount === transfer.amount;319 return isSuccess;320 }321}322323324class ChainHelperBase {325 transactionStatus = UniqueUtil.transactionStatus;326 chainLogType = UniqueUtil.chainLogType;327 util: typeof UniqueUtil;328 logger: ILogger;329 api: ApiPromise | null;330 forcedNetwork: TUniqueNetworks | null;331 network: TUniqueNetworks | null;332 chainLog: IUniqueHelperLog[];333334 constructor(logger?: ILogger) {335 this.util = UniqueUtil;336 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();337 this.logger = logger;338 this.api = null;339 this.forcedNetwork = null;340 this.network = null;341 this.chainLog = [];342 }343344 clearChainLog(): void {345 this.chainLog = [];346 }347348 forceNetwork(value: TUniqueNetworks): void {349 this.forcedNetwork = value;350 }351352 async connect(wsEndpoint: string, listeners?: IApiListeners) {353 if (this.api !== null) throw Error('Already connected');354 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);355 this.api = api;356 this.network = network;357 }358359 async disconnect() {360 if (this.api === null) return;361 await this.api.disconnect();362 this.api = null;363 this.network = null;364 }365366 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {367 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;368 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;369 return 'opal';370 }371372 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {373 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});374 await api.isReady;375376 const network = await this.detectNetwork(api);377378 await api.disconnect();379380 return network;381 }382383 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{ 384 api: ApiPromise; 385 network: TUniqueNetworks; 386 }> {387 if(typeof network === 'undefined' || network === null) network = 'opal';388 const supportedRPC = {389 opal: {390 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,391 },392 quartz: {393 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,394 },395 unique: {396 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,397 },398 };399 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);400 const rpc = supportedRPC[network];401402 // TODO: investigate how to replace rpc in runtime403 // api._rpcCore.addUserInterfaces(rpc);404405 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});406407 await api.isReadyOrError;408409 if (typeof listeners === 'undefined') listeners = {};410 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {411 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;412 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);413 }414415 return {api, network};416 }417418 getTransactionStatus(data: {events: {event: IChainEvent}[], status: any}) {419 const {events, status} = data;420 if (status.isReady) {421 return this.transactionStatus.NOT_READY;422 }423 if (status.isBroadcast) {424 return this.transactionStatus.NOT_READY;425 }426 if (status.isInBlock || status.isFinalized) {427 const errors = events.filter(e => e.event.data.method === 'ExtrinsicFailed');428 if (errors.length > 0) {429 return this.transactionStatus.FAIL;430 }431 if (events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {432 return this.transactionStatus.SUCCESS;433 }434 }435436 return this.transactionStatus.FAIL;437 }438439 signTransaction(sender: TSigner, transaction: any, label = 'transaction', options = null) {440 const sign = (callback: any) => {441 if(options !== null) return transaction.signAndSend(sender, options, callback);442 return transaction.signAndSend(sender, callback);443 };444 return new Promise(async (resolve, reject) => {445 try {446 const unsub = await sign((result: any) => {447 const status = this.getTransactionStatus(result);448449 if (status === this.transactionStatus.SUCCESS) {450 this.logger.log(`${label} successful`);451 unsub();452 resolve({result, status});453 } else if (status === this.transactionStatus.FAIL) {454 let moduleError = null;455456 if (result.hasOwnProperty('dispatchError')) {457 const dispatchError = result['dispatchError'];458459 if (dispatchError && dispatchError.isModule) {460 const modErr = dispatchError.asModule;461 const errorMeta = dispatchError.registry.findMetaError(modErr);462463 moduleError = `${errorMeta.section}.${errorMeta.name}`;464 }465 else {466 this.logger.log(result, this.logger.level.ERROR);467 }468 }469470 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);471 unsub();472 reject({status, moduleError, result});473 }474 });475 } catch (e) {476 this.logger.log(e, this.logger.level.ERROR);477 reject(e);478 }479 });480 }481482 constructApiCall(apiCall: string, params: any[]) {483 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);484 let call = this.api as any;485 for(const part of apiCall.slice(4).split('.')) {486 call = call[part];487 }488 return call(...params);489 }490491 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=false, failureMessage='expected success') {492 if(this.api === null) throw Error('API not initialized');493 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);494495 const startTime = (new Date()).getTime();496 let result: ITransactionResult;497 let events = [];498 try {499 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), extrinsic) as ITransactionResult;500 events = result.result.events.map((x: any) => x.toHuman());501 }502 catch(e) {503 if(!(e as object).hasOwnProperty('status')) throw e;504 result = e as ITransactionResult;505 }506507 const endTime = (new Date()).getTime();508509 const log = {510 executedAt: endTime,511 executionTime: endTime - startTime,512 type: this.chainLogType.EXTRINSIC,513 status: result.status,514 call: extrinsic,515 params,516 } as IUniqueHelperLog;517518 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;519 if(events.length > 0) log.events = events;520521 this.chainLog.push(log);522523 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(failureMessage);524 return result;525 }526527 async callRpc(rpc: string, params?: any[]) {528 if(typeof params === 'undefined') params = [];529 if(this.api === null) throw Error('API not initialized');530 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);531532 const startTime = (new Date()).getTime();533 let result;534 let error = null;535 const log = {536 type: this.chainLogType.RPC,537 call: rpc,538 params,539 } as IUniqueHelperLog;540541 try {542 result = await this.constructApiCall(rpc, params);543 }544 catch(e) {545 error = e;546 }547548 const endTime = (new Date()).getTime();549550 log.executedAt = endTime;551 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';552 log.executionTime = endTime - startTime;553554 this.chainLog.push(log);555556 if(error !== null) throw error;557558 return result;559 }560561 getSignerAddress(signer: IKeyringPair | string): string {562 if(typeof signer === 'string') return signer;563 return signer.address;564 }565}566567568class HelperGroup {569 helper: UniqueHelper;570571 constructor(uniqueHelper: UniqueHelper) {572 this.helper = uniqueHelper;573 }574}575576577class CollectionGroup extends HelperGroup {578 /**579 * Get number of blocks when sponsored transaction is available.580 *581 * @param collectionId ID of collection582 * @param tokenId ID of token583 * @param addressObj 584 * @returns number of blocks or null if sponsorship hasn't been set585 */586 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {587 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();588 }589590 /**591 * Get number of collection created on current chain.592 * 593 * @returns number of created collections594 */595 async getTotalCount(): Promise<number> {596 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();597 }598599 /**600 * Get information about the collection with additional data, including the number of tokens it contains, its administrators, the normalized address of the collection's owner, and decoded name and description.601 * 602 * @param collectionId ID of collection603 * @returns collection information object604 */605 async getData(collectionId: number): Promise<{606 id: number;607 name: string;608 description: string;609 tokensCount: number;610 admins: ICrossAccountId[];611 normalizedOwner: TSubstrateAccount;612 raw: any613 } | null> {614 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);615 const humanCollection = collection.toHuman(), collectionData = {616 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],617 raw: humanCollection,618 } as any, jsonCollection = collection.toJSON();619 if (humanCollection === null) return null;620 collectionData.raw.limits = jsonCollection.limits;621 collectionData.raw.permissions = jsonCollection.permissions;622 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);623 for (const key of ['name', 'description']) {624 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);625 }626627 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode)) ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId) : 0;628 collectionData.admins = await this.getAdmins(collectionId);629630 return collectionData;631 }632633 /**634 * Get the normalized addresses of the collection's administrators.635 * 636 * @param collectionId ID of collection637 * @returns array of administrators638 */639 async getAdmins(collectionId: number): Promise<ICrossAccountId[]> {640 const normalized = [];641 for(const admin of (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman()) {642 if(admin.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(admin.Substrate)});643 else normalized.push(admin);644 }645 return normalized;646 }647648 /**649 * Get the effective limits of the collection instead of null for default values650 * 651 * @param collectionId ID of collection652 * @returns object of collection limits653 */654 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {655 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();656 }657658 /**659 * Burns the collection if the signer has sufficient permissions and collection is empty.660 * 661 * @param signer keyring of signer662 * @param collectionId ID of collection663 * @param label extra label for log664 * @returns bool true on success665 */666 async burn(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {667 if(typeof label === 'undefined') label = `collection #${collectionId}`;668 const result = await this.helper.executeExtrinsic(669 signer,670 'api.tx.unique.destroyCollection', [collectionId],671 true, `Unable to burn collection for ${label}`,672 );673674 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed', label);675 }676677 /**678 * Sets the sponsor for the collection (Requires the Substrate address).679 * 680 * @param signer keyring of signer681 * @param collectionId ID of collection682 * @param sponsorAddress Sponsor substrate address683 * @param label extra label for log684 * @returns bool true on success685 */686 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount, label?: string): Promise<boolean> {687 if(typeof label === 'undefined') label = `collection #${collectionId}`;688 const result = await this.helper.executeExtrinsic(689 signer,690 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],691 true, `Unable to set collection sponsor for ${label}`,692 );693694 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet', label);695 }696697 /**698 * Confirms consent to sponsor the collection on behalf of the signer.699 * 700 * @param signer keyring of signer701 * @param collectionId ID of collection702 * @param label extra label for log703 * @returns bool true on success704 */705 async confirmSponsorship(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {706 if(typeof label === 'undefined') label = `collection #${collectionId}`;707 const result = await this.helper.executeExtrinsic(708 signer,709 'api.tx.unique.confirmSponsorship', [collectionId],710 true, `Unable to confirm collection sponsorship for ${label}`,711 );712713 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed', label);714 }715716 /**717 * Sets the limits of the collection. At least one limit must be specified for a correct call.718 * 719 * @param signer keyring of signer720 * @param collectionId ID of collection721 * @param limits collection limits object722 * @param label extra label for log723 * @returns bool true on success724 */725 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits, label?: string): Promise<boolean> {726 if(typeof label === 'undefined') label = `collection #${collectionId}`;727 const result = await this.helper.executeExtrinsic(728 signer,729 'api.tx.unique.setCollectionLimits', [collectionId, limits],730 true, `Unable to set collection limits for ${label}`,731 );732733 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet', label);734 }735736 /**737 * Changes the owner of the collection to the new Substrate address.738 * 739 * @param signer keyring of signer740 * @param collectionId ID of collection741 * @param ownerAddress substrate address of new owner742 * @param label extra label for log743 * @returns bool true on success744 */745 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount, label?: string): Promise<boolean> {746 if(typeof label === 'undefined') label = `collection #${collectionId}`;747 const result = await this.helper.executeExtrinsic(748 signer,749 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],750 true, `Unable to change collection owner for ${label}`,751 );752753 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged', label);754 }755756 /**757 * Adds a collection administrator. 758 * 759 * @param signer keyring of signer760 * @param collectionId ID of collection761 * @param adminAddressObj Administrator address (substrate or ethereum)762 * @param label extra label for log763 * @returns bool true on success764 */765 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {766 if(typeof label === 'undefined') label = `collection #${collectionId}`;767 const result = await this.helper.executeExtrinsic(768 signer,769 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],770 true, `Unable to add collection admin for ${label}`,771 );772773 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded', label);774 }775776 /**777 * Removes a collection administrator.778 * 779 * @param signer keyring of signer780 * @param collectionId ID of collection781 * @param adminAddressObj Administrator address (substrate or ethereum)782 * @param label extra label for log783 * @returns bool true on success784 */785 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {786 if(typeof label === 'undefined') label = `collection #${collectionId}`;787 const result = await this.helper.executeExtrinsic(788 signer,789 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],790 true, `Unable to remove collection admin for ${label}`,791 );792793 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved', label);794 }795796 /**797 * Sets onchain permissions for selected collection.798 * 799 * @param signer keyring of signer800 * @param collectionId ID of collection801 * @param permissions collection permissions object802 * @param label extra label for log803 * @returns bool true on success804 */805 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions, label?: string): Promise<boolean> {806 if(typeof label === 'undefined') label = `collection #${collectionId}`;807 const result = await this.helper.executeExtrinsic(808 signer,809 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],810 true, `Unable to set collection permissions for ${label}`,811 );812813 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet', label);814 }815816 /**817 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.818 * 819 * @param signer keyring of signer820 * @param collectionId ID of collection821 * @param permissions nesting permissions object822 * @param label extra label for log823 * @returns bool true on success824 */825 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions, label?: string): Promise<boolean> {826 return await this.setPermissions(signer, collectionId, {nesting: permissions}, label);827 }828829 /**830 * Disables nesting for selected collection.831 * 832 * @param signer keyring of signer833 * @param collectionId ID of collection834 * @param label extra label for log835 * @returns bool true on success836 */837 async disableNesting(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {838 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}}, label);839 }840841 /**842 * Sets onchain properties to the collection.843 * 844 * @param signer keyring of signer845 * @param collectionId ID of collection846 * @param properties array of property objects847 * @param label extra label for log848 * @returns bool true on success849 */850 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[], label?: string): Promise<boolean> {851 if(typeof label === 'undefined') label = `collection #${collectionId}`;852 const result = await this.helper.executeExtrinsic(853 signer,854 'api.tx.unique.setCollectionProperties', [collectionId, properties],855 true, `Unable to set collection properties for ${label}`,856 );857858 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet', label);859 }860861 /**862 * Deletes onchain properties from the collection.863 * 864 * @param signer keyring of signer865 * @param collectionId ID of collection866 * @param propertyKeys array of property keys to delete867 * @param label 868 * @returns 869 */870 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[], label?: string): Promise<boolean> {871 if(typeof label === 'undefined') label = `collection #${collectionId}`;872 const result = await this.helper.executeExtrinsic(873 signer,874 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],875 true, `Unable to delete collection properties for ${label}`,876 );877878 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted', label);879 }880881 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {882 const result = await this.helper.executeExtrinsic(883 signer,884 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],885 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,886 );887888 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);889 }890891 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {892 const result = await this.helper.executeExtrinsic(893 signer,894 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],895 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,896 );897 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);898 }899900 async burnToken(signer: TSigner, collectionId: number, tokenId: number, label?: string, amount=1n): Promise<{901 success: boolean,902 token: number | null903 }> {904 if(typeof label === 'undefined') label = `collection #${collectionId}`;905 const burnResult = await this.helper.executeExtrinsic(906 signer,907 'api.tx.unique.burnItem', [collectionId, tokenId, amount],908 true, `Unable to burn token for ${label}`,909 );910 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);911 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');912 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};913 }914915 async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, label?: string, amount=1n): Promise<boolean> {916 if(typeof label === 'undefined') label = `collection #${collectionId}`;917 const burnResult = await this.helper.executeExtrinsic(918 signer,919 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],920 true, `Unable to burn token from for ${label}`,921 );922 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);923 return burnedTokens.success && burnedTokens.tokens.length > 0;924 }925926 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=1n) {927 if(typeof label === 'undefined') label = `collection #${collectionId}`;928 const approveResult = await this.helper.executeExtrinsic(929 signer, 930 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],931 true, `Unable to approve token for ${label}`,932 );933934 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved', label);935 }936937 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {938 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();939 }940941 async getLastTokenId(collectionId: number): Promise<number> {942 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();943 }944945 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {946 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();947 }948}949950class NFTnRFT extends CollectionGroup {951 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {952 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();953 }954955 async getToken(collectionId: number, tokenId: number, blockHashAt?: string, propertyKeys?: string[]): Promise<{956 properties: IProperty[];957 owner: ICrossAccountId;958 normalizedOwner: ICrossAccountId;959 }| null> {960 let tokenData;961 if(typeof blockHashAt === 'undefined') {962 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);963 }964 else {965 if(typeof propertyKeys === 'undefined') {966 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();967 if(!collection) return null;968 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);969 }970 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);971 }972 tokenData = tokenData.toHuman();973 if (tokenData === null || tokenData.owner === null) return null;974 const owner = {} as any;975 for (const key of Object.keys(tokenData.owner)) {976 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];977 }978 tokenData.normalizedOwner = crossAccountIdFromLower(owner);979 return tokenData;980 }981982 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[], label?: string): Promise<boolean> {983 if(typeof label === 'undefined') label = `collection #${collectionId}`;984 const result = await this.helper.executeExtrinsic(985 signer,986 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],987 true, `Unable to set token property permissions for ${label}`,988 );989990 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet', label);991 }992993 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[], label?: string): Promise<boolean> {994 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;995 const result = await this.helper.executeExtrinsic(996 signer,997 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],998 true, `Unable to set token properties for ${label}`,999 );10001001 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet', label);1002 }10031004 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[], label?: string): Promise<boolean> {1005 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;1006 const result = await this.helper.executeExtrinsic(1007 signer,1008 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1009 true, `Unable to delete token properties for ${label}`,1010 );10111012 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted', label);1013 }10141015 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT', errorLabel = 'Unable to mint collection'): Promise<UniqueCollectionBase> {1016 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1017 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1018 for (const key of ['name', 'description', 'tokenPrefix']) {1019 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);1020 }1021 const creationResult = await this.helper.executeExtrinsic(1022 signer,1023 'api.tx.unique.createCollectionEx', [collectionOptions],1024 true, errorLabel,1025 );1026 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1027 }10281029 getCollectionObject(collectionId: number): any {1030 return null;1031 }10321033 getTokenObject(collectionId: number, tokenId: number): any {1034 return null;1035 }1036}103710381039class NFTGroup extends NFTnRFT {1040 getCollectionObject(collectionId: number): UniqueNFTCollection {1041 return new UniqueNFTCollection(collectionId, this.helper);1042 }10431044 getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1045 return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1046 }10471048 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1049 let owner;1050 if (typeof blockHashAt === 'undefined') {1051 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1052 } else {1053 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1054 }1055 return crossAccountIdFromLower(owner.toJSON());1056 }10571058 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1059 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1060 }10611062 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1063 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1064 }10651066 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1067 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1068 }10691070 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1071 let owner;1072 if (typeof blockHashAt === 'undefined') {1073 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1074 } else {1075 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1076 }10771078 if (owner === null) return null;10791080 owner = owner.toHuman();10811082 return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1083 }10841085 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1086 let children;1087 if(typeof blockHashAt === 'undefined') {1088 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1089 } else {1090 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1091 }10921093 return children.toJSON().map((x: any) => {1094 return {collectionId: x.collection, tokenId: x.token};1095 });1096 }10971098 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, label='nest token'): Promise<boolean> {1099 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1100 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1101 if(!result) {1102 throw Error(`Unable to nest token for ${label}`);1103 }1104 return result;1105 }11061107 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId, label='unnest token'): Promise<boolean> {1108 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1109 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1110 if(!result) {1111 throw Error(`Unable to unnest token for ${label}`);1112 }1113 return result;1114 }11151116 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueNFTCollection> {1117 return await super.mintCollection(signer, collectionOptions, 'NFT', `Unable to mint NFT collection for ${label}`) as UniqueNFTCollection;1118 }11191120 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }, label?: string): Promise<UniqueNFTToken> {1121 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1122 const creationResult = await this.helper.executeExtrinsic(1123 signer,1124 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1125 nft: {1126 properties: data.properties,1127 },1128 }],1129 true, `Unable to mint NFT token for ${label}`,1130 );1131 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1132 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1133 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1134 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1135 }11361137 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1138 if(typeof label === 'undefined') label = `collection #${collectionId}`;1139 const creationResult = await this.helper.executeExtrinsic(1140 signer,1141 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1142 true, `Unable to mint NFT tokens for ${label}`,1143 );1144 const collection = this.getCollectionObject(collectionId);1145 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1146 }11471148 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1149 if(typeof label === 'undefined') label = `collection #${collectionId}`;1150 const rawTokens = [];1151 for (const token of tokens) {1152 const raw = {NFT: {properties: token.properties}};1153 rawTokens.push(raw);1154 }1155 const creationResult = await this.helper.executeExtrinsic(1156 signer,1157 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1158 true, `Unable to mint NFT tokens for ${label}`,1159 );1160 const collection = this.getCollectionObject(collectionId);1161 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1162 }11631164 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string): Promise<{ success: boolean; token: number | null; }> {1165 return await super.burnToken(signer, collectionId, tokenId, label, 1n);1166 }11671168 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {1169 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, 1n);1170 }1171}117211731174class RFTGroup extends NFTnRFT {1175 getCollectionObject(collectionId: number): UniqueRFTCollection {1176 return new UniqueRFTCollection(collectionId, this.helper);1177 }11781179 getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1180 return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1181 }11821183 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1184 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1185 }11861187 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1188 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1189 }11901191 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=100n): Promise<boolean> {1192 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1193 }11941195 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n): Promise<boolean> {1196 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1197 }11981199 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueRFTCollection> {1200 return await super.mintCollection(signer, collectionOptions, 'RFT', `Unable to mint RFT collection for ${label}`) as UniqueRFTCollection;1201 }12021203 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }, label?: string): Promise<UniqueRFTToken> {1204 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1205 const creationResult = await this.helper.executeExtrinsic(1206 signer,1207 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1208 refungible: {1209 pieces: data.pieces,1210 properties: data.properties,1211 },1212 }],1213 true, `Unable to mint RFT token for ${label}`,1214 );1215 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1216 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1217 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1218 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1219 }12201221 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1222 throw Error('Not implemented');1223 if(typeof label === 'undefined') label = `collection #${collectionId}`;1224 const creationResult = await this.helper.executeExtrinsic(1225 signer,1226 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1227 true, `Unable to mint RFT tokens for ${label}`,1228 );1229 const collection = this.getCollectionObject(collectionId);1230 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1231 }12321233 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1234 if(typeof label === 'undefined') label = `collection #${collectionId}`;1235 const rawTokens = [];1236 for (const token of tokens) {1237 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1238 rawTokens.push(raw);1239 }1240 const creationResult = await this.helper.executeExtrinsic(1241 signer,1242 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1243 true, `Unable to mint RFT tokens for ${label}`,1244 );1245 const collection = this.getCollectionObject(collectionId);1246 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1247 }12481249 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string, amount=100n): Promise<{ success: boolean; token: number | null; }> {1250 return await super.burnToken(signer, collectionId, tokenId, label, amount);1251 }12521253 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=100n) {1254 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, amount);1255 }12561257 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1258 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1259 }12601261 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint, label?: string): Promise<boolean> {1262 if(typeof label === 'undefined') label = `collection #${collectionId}`;1263 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1264 const repartitionResult = await this.helper.executeExtrinsic(1265 signer,1266 'api.tx.unique.repartition', [collectionId, tokenId, amount],1267 true, `Unable to repartition RFT token for ${label}`,1268 );1269 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated', label);1270 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed', label);1271 }1272}127312741275class FTGroup extends CollectionGroup {1276 getCollectionObject(collectionId: number): UniqueFTCollection {1277 return new UniqueFTCollection(collectionId, this.helper);1278 }12791280 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0, errorLabel = 'Unable to mint collection'): Promise<UniqueFTCollection> {1281 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1282 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1283 collectionOptions.mode = {fungible: decimalPoints};1284 for (const key of ['name', 'description', 'tokenPrefix']) {1285 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);1286 }1287 const creationResult = await this.helper.executeExtrinsic(1288 signer,1289 'api.tx.unique.createCollectionEx', [collectionOptions],1290 true, errorLabel,1291 );1292 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1293 }12941295 async mintTokens(signer: TSigner, collectionId: number, owner: ICrossAccountId | string, amount: bigint, label?: string): Promise<boolean> {1296 if(typeof label === 'undefined') label = `collection #${collectionId}`;1297 const creationResult = await this.helper.executeExtrinsic(1298 signer,1299 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1300 fungible: {1301 value: amount,1302 },1303 }],1304 true, `Unable to mint fungible tokens for ${label}`,1305 );1306 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1307 }13081309 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string): Promise<boolean> {1310 if(typeof label === 'undefined') label = `collection #${collectionId}`;1311 const rawTokens = [];1312 for (const token of tokens) {1313 const raw = {Fungible: {Value: token.value}};1314 rawTokens.push(raw);1315 }1316 const creationResult = await this.helper.executeExtrinsic(1317 signer,1318 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1319 true, `Unable to mint RFT tokens for ${label}`,1320 );1321 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1322 }13231324 async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1325 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1326 }13271328 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1329 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1330 }13311332 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount: bigint) {1333 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1334 }13351336 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {1337 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1338 }13391340 async burnTokens(signer: IKeyringPair, collectionId: number, amount=100n, label?: string): Promise<boolean> {1341 return (await super.burnToken(signer, collectionId, 0, label, amount)).success;1342 }13431344 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=100n, label?: string): Promise<boolean> {1345 return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, label, amount);1346 }13471348 async getTotalPieces(collectionId: number): Promise<bigint> {1349 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1350 }13511352 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {1353 return super.approveToken(signer, collectionId, 0, toAddressObj, label, amount);1354 }13551356 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1357 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1358 }1359}136013611362class ChainGroup extends HelperGroup {1363 getChainProperties(): IChainProperties {1364 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1365 return {1366 ss58Format: properties.ss58Format.toJSON(),1367 tokenDecimals: properties.tokenDecimals.toJSON(),1368 tokenSymbol: properties.tokenSymbol.toJSON(),1369 };1370 }13711372 async getLatestBlockNumber(): Promise<number> {1373 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1374 }13751376 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1377 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1378 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1379 return blockHash;1380 }13811382 async getNonce(address: TSubstrateAccount): Promise<number> {1383 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1384 }1385}138613871388class BalanceGroup extends HelperGroup {1389 getOneTokenNominal(): bigint {1390 const chainProperties = this.helper.chain.getChainProperties();1391 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1392 }13931394 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {1395 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();1396 }13971398 async getEthereum(address: TEthereumAccount): Promise<bigint> {1399 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();1400 }14011402 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {1403 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true, `Unable to transfer balance from ${this.helper.getSignerAddress(signer)} to ${address}`);14041405 let transfer = {from: null, to: null, amount: 0n} as any;1406 result.result.events.forEach(({event: {data, method, section}}) => {1407 if ((section === 'balances') && (method === 'Transfer')) {1408 transfer = {1409 from: this.helper.address.normalizeSubstrate(data[0]),1410 to: this.helper.address.normalizeSubstrate(data[1]),1411 amount: BigInt(data[2]),1412 };1413 }1414 });1415 let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;1416 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;1417 isSuccess = isSuccess && BigInt(amount) === transfer.amount;1418 return isSuccess;1419 }1420}142114221423class AddressGroup extends HelperGroup {1424 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {1425 return this.helper.util.normalizeSubstrateAddress(address, ss58Format);1426 }14271428 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {1429 const info = this.helper.chain.getChainProperties();1430 return encodeAddress(decodeAddress(address), info.ss58Format);1431 }14321433 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {1434 if(!toChainFormat) return evmToAddress(ethAddress);1435 const info = this.helper.chain.getChainProperties();1436 return evmToAddress(ethAddress, info.ss58Format);1437 }14381439 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {1440 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));1441 }1442}144314441445export class UniqueHelper extends ChainHelperBase {1446 chain: ChainGroup;1447 balance: BalanceGroup;1448 address: AddressGroup;1449 collection: CollectionGroup;1450 nft: NFTGroup;1451 rft: RFTGroup;1452 ft: FTGroup;14531454 constructor(logger?: ILogger) {1455 super(logger);1456 this.chain = new ChainGroup(this);1457 this.balance = new BalanceGroup(this);1458 this.address = new AddressGroup(this);1459 this.collection = new CollectionGroup(this);1460 this.nft = new NFTGroup(this);1461 this.rft = new RFTGroup(this);1462 this.ft = new FTGroup(this);1463 } 1464}146514661467class UniqueCollectionBase {1468 helper: UniqueHelper;1469 collectionId: number;14701471 constructor(collectionId: number, uniqueHelper: UniqueHelper) {1472 this.collectionId = collectionId;1473 this.helper = uniqueHelper;1474 }14751476 async getData() {1477 return await this.helper.collection.getData(this.collectionId);1478 }14791480 async getLastTokenId() {1481 return await this.helper.collection.getLastTokenId(this.collectionId);1482 }14831484 async isTokenExists(tokenId: number) {1485 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);1486 }14871488 async getAdmins() {1489 return await this.helper.collection.getAdmins(this.collectionId);1490 }14911492 async getEffectiveLimits() {1493 return await this.helper.collection.getEffectiveLimits(this.collectionId);1494 }14951496 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount, label?: string) {1497 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress, label);1498 }14991500 async confirmSponsorship(signer: TSigner, label?: string) {1501 return await this.helper.collection.confirmSponsorship(signer, this.collectionId, label);1502 }15031504 async setLimits(signer: TSigner, limits: ICollectionLimits, label?: string) {1505 return await this.helper.collection.setLimits(signer, this.collectionId, limits, label);1506 }15071508 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount, label?: string) {1509 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress, label);1510 }15111512 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {1513 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj, label);1514 }15151516 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {1517 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj, label);1518 }15191520 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {1521 return await this.helper.collection.setProperties(signer, this.collectionId, properties, label);1522 }15231524 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {1525 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys, label);1526 }15271528 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {1529 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);1530 }15311532 async setPermissions(signer: TSigner, permissions: ICollectionPermissions, label?: string) {1533 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions, label);1534 }15351536 async enableNesting(signer: TSigner, permissions: INestingPermissions, label?: string) {1537 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions, label);1538 }15391540 async disableNesting(signer: TSigner, label?: string) {1541 return await this.helper.collection.disableNesting(signer, this.collectionId, label);1542 }15431544 async burn(signer: TSigner, label?: string) {1545 return await this.helper.collection.burn(signer, this.collectionId, label);1546 }1547}154815491550class UniqueNFTCollection extends UniqueCollectionBase {1551 getTokenObject(tokenId: number) {1552 return new UniqueNFTToken(tokenId, this);1553 }15541555 async getTokensByAddress(addressObj: ICrossAccountId) {1556 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);1557 }15581559 async getToken(tokenId: number, blockHashAt?: string) {1560 return await this.helper.nft.getToken(this.collectionId, tokenId, blockHashAt);1561 }15621563 async getTokenOwner(tokenId: number, blockHashAt?: string) {1564 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);1565 }15661567 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {1568 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);1569 }15701571 async getTokenChildren(tokenId: number, blockHashAt?: string) {1572 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);1573 }15741575 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {1576 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);1577 }15781579 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1580 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);1581 }15821583 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {1584 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label);1585 }15861587 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {1588 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);1589 }15901591 async mintToken(signer: TSigner, owner: ICrossAccountId, properties?: IProperty[], label?: string) {1592 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties}, label);1593 }15941595 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string) {1596 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens, label);1597 }15981599 async burnToken(signer: TSigner, tokenId: number, label?: string) {1600 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId, label);1601 }16021603 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {1604 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);1605 }16061607 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {1608 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);1609 }16101611 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {1612 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);1613 }16141615 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken, label?: string) {1616 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj, label);1617 }16181619 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {1620 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj, label);1621 }1622}162316241625class UniqueRFTCollection extends UniqueCollectionBase {1626 getTokenObject(tokenId: number) {1627 return new UniqueRFTToken(tokenId, this);1628 }16291630 async getTokensByAddress(addressObj: ICrossAccountId) {1631 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);1632 }16331634 async getTop10TokenOwners(tokenId: number) {1635 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);1636 }16371638 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {1639 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);1640 }16411642 async getTokenTotalPieces(tokenId: number) {1643 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);1644 }16451646 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=100n) {1647 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);1648 }16491650 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {1651 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);1652 }16531654 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {1655 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label, amount);1656 }16571658 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1659 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);1660 }16611662 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint, label?: string) {1663 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount, label);1664 }16651666 async mintToken(signer: TSigner, owner: ICrossAccountId, pieces=100n, properties?: IProperty[], label?: string) {1667 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties}, label);1668 }16691670 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string) {1671 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens, label);1672 }16731674 async burnToken(signer: TSigner, tokenId: number, amount=100n, label?: string) {1675 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, label, amount);1676 }16771678 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {1679 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);1680 }16811682 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {1683 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);1684 }16851686 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {1687 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);1688 }1689}169016911692class UniqueFTCollection extends UniqueCollectionBase {1693 async mint(signer: TSigner, owner: ICrossAccountId, amount: bigint, label?: string) {1694 return await this.helper.ft.mintTokens(signer, this.collectionId, owner, amount, label);1695 }16961697 async mintWithOneOwner(signer: TSigner, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string) {1698 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, owner, tokens, label);1699 }17001701 async getBalance(addressObj: ICrossAccountId) {1702 return await this.helper.ft.getBalance(this.collectionId, addressObj);1703 }17041705 async getTop10Owners() {1706 return await this.helper.ft.getTop10Owners(this.collectionId);1707 }17081709 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount: bigint) {1710 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);1711 }17121713 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {1714 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);1715 }17161717 async burnTokens(signer: TSigner, amount: bigint, label?: string) {1718 return await this.helper.ft.burnTokens(signer, this.collectionId, amount, label);1719 }17201721 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount: bigint, label?: string) {1722 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount, label);1723 }17241725 async getTotalPieces() {1726 return await this.helper.ft.getTotalPieces(this.collectionId);1727 }17281729 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {1730 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount, label);1731 }17321733 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1734 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);1735 }1736}173717381739class UniqueTokenBase implements IToken {1740 collection: UniqueNFTCollection | UniqueRFTCollection;1741 collectionId: number;1742 tokenId: number;17431744 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {1745 this.collection = collection;1746 this.collectionId = collection.collectionId;1747 this.tokenId = tokenId;1748 }17491750 async getNextSponsored(addressObj: ICrossAccountId) {1751 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);1752 }17531754 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {1755 return await this.collection.setTokenProperties(signer, this.tokenId, properties, label);1756 }17571758 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {1759 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys, label);1760 }1761}176217631764class UniqueNFTToken extends UniqueTokenBase {1765 collection: UniqueNFTCollection;17661767 constructor(tokenId: number, collection: UniqueNFTCollection) {1768 super(tokenId, collection);1769 this.collection = collection;1770 }17711772 async getData(blockHashAt?: string) {1773 return await this.collection.getToken(this.tokenId, blockHashAt);1774 }17751776 async getOwner(blockHashAt?: string) {1777 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);1778 }17791780 async getTopmostOwner(blockHashAt?: string) {1781 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);1782 }17831784 async getChildren(blockHashAt?: string) {1785 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);1786 }17871788 async nest(signer: TSigner, toTokenObj: IToken, label?: string) {1789 return await this.collection.nestToken(signer, this.tokenId, toTokenObj, label);1790 }17911792 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {1793 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj, label);1794 }17951796 async transfer(signer: TSigner, addressObj: ICrossAccountId) {1797 return await this.collection.transferToken(signer, this.tokenId, addressObj);1798 }17991800 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1801 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);1802 }18031804 async approve(signer: TSigner, toAddressObj: ICrossAccountId, label?: string) {1805 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, label);1806 }18071808 async isApproved(toAddressObj: ICrossAccountId) {1809 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);1810 }18111812 async burn(signer: TSigner, label?: string) {1813 return await this.collection.burnToken(signer, this.tokenId, label);1814 }1815}18161817class UniqueRFTToken extends UniqueTokenBase {1818 collection: UniqueRFTCollection;18191820 constructor(tokenId: number, collection: UniqueRFTCollection) {1821 super(tokenId, collection);1822 this.collection = collection;1823 }18241825 async getTop10Owners() {1826 return await this.collection.getTop10TokenOwners(this.tokenId);1827 }18281829 async getBalance(addressObj: ICrossAccountId) {1830 return await this.collection.getTokenBalance(this.tokenId, addressObj);1831 }18321833 async getTotalPieces() {1834 return await this.collection.getTokenTotalPieces(this.tokenId);1835 }18361837 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=100n) {1838 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);1839 }18401841 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {1842 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);1843 }18441845 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {1846 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount, label);1847 }18481849 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {1850 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);1851 }18521853 async repartition(signer: TSigner, amount: bigint, label?: string) {1854 return await this.collection.repartitionToken(signer, this.tokenId, amount, label);1855 }18561857 async burn(signer: TSigner, amount=100n, label?: string) {1858 return await this.collection.burnToken(signer, this.tokenId, amount, label);1859 }1860}