difftreelog
Merge branch 'develop' into tests/eth-playgrounds
in: master
3 files changed
tests/src/util/playgrounds/index.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/index.ts
+++ b/tests/src/util/playgrounds/index.ts
@@ -23,4 +23,4 @@
await helper.disconnect();
silentConsole.disable();
}
-};
\ No newline at end of file
+};
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -149,7 +149,6 @@
let accountsCreated = false;
// checkBalances retry up to 5 blocks
for (let index = 0; index < 5; index++) {
- console.log(await this.helper.chain.getLatestBlockNumber());
accountsCreated = await checkBalances();
if(accountsCreated) break;
await this.waitNewBlocks(1);
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IChainEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {15 const address = {} as ICrossAccountId;16 if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;17 if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;18 return address;19};202122const nesting = {23 toChecksumAddress(address: string): string {24 if (typeof address === 'undefined') return '';2526 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);2728 address = address.toLowerCase().replace(/^0x/i,'');29 const addressHash = keccakAsHex(address).replace(/^0x/i,'');30 const checksumAddress = ['0x'];3132 for (let i = 0; i < address.length; i++) {33 // If ith character is 8 to f then make it uppercase34 if (parseInt(addressHash[i], 16) > 7) {35 checksumAddress.push(address[i].toUpperCase());36 } else {37 checksumAddress.push(address[i]);38 }39 }40 return checksumAddress.join('');41 },42 tokenIdToAddress(collectionId: number, tokenId: number) {43 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);44 },45};4647class UniqueUtil {48 static transactionStatus = {49 NOT_READY: 'NotReady',50 FAIL: 'Fail',51 SUCCESS: 'Success',52 };5354 static chainLogType = {55 EXTRINSIC: 'extrinsic',56 RPC: 'rpc',57 };5859 static getNestingTokenAddress(collectionId: number, tokenId: number) {60 return nesting.tokenIdToAddress(collectionId, tokenId);61 }6263 static getDefaultLogger(): ILogger {64 return {65 log(msg: any, level = 'INFO') {66 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));67 },68 level: {69 ERROR: 'ERROR',70 WARNING: 'WARNING',71 INFO: 'INFO',72 },73 };74 }7576 static vec2str(arr: string[] | number[]) {77 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');78 }7980 static str2vec(string: string) {81 if (typeof string !== 'string') return string;82 return Array.from(string).map(x => x.charCodeAt(0));83 }8485 static fromSeed(seed: string, ss58Format = 42) {86 const keyring = new Keyring({type: 'sr25519', ss58Format});87 return keyring.addFromUri(seed);88 }8990 static normalizeSubstrateAddress(address: string, ss58Format = 42) {91 return encodeAddress(decodeAddress(address), ss58Format);92 }9394 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult, label = 'new collection') {95 if (creationResult.status !== this.transactionStatus.SUCCESS) {96 throw Error(`Unable to create collection for ${label}`);97 }9899 let collectionId = null;100 creationResult.result.events.forEach(({event: {data, method, section}}) => {101 if ((section === 'common') && (method === 'CollectionCreated')) {102 collectionId = parseInt(data[0].toString(), 10);103 }104 });105106 if (collectionId === null) {107 throw Error(`No CollectionCreated event for ${label}`);108 }109110 return collectionId;111 }112113 static extractTokensFromCreationResult(creationResult: ITransactionResult, label = 'new tokens') {114 if (creationResult.status !== this.transactionStatus.SUCCESS) {115 throw Error(`Unable to create tokens for ${label}`);116 }117 let success = false;118 const tokens = [] as any;119 creationResult.result.events.forEach(({event: {data, method, section}}) => {120 if (method === 'ExtrinsicSuccess') {121 success = true;122 } else if ((section === 'common') && (method === 'ItemCreated')) {123 tokens.push({124 collectionId: parseInt(data[0].toString(), 10),125 tokenId: parseInt(data[1].toString(), 10),126 owner: data[2].toJSON(),127 });128 }129 });130 return {success, tokens};131 }132133 static extractTokensFromBurnResult(burnResult: ITransactionResult, label = 'burned tokens') {134 if (burnResult.status !== this.transactionStatus.SUCCESS) {135 throw Error(`Unable to burn tokens for ${label}`);136 }137 let success = false;138 const tokens = [] as any;139 burnResult.result.events.forEach(({event: {data, method, section}}) => {140 if (method === 'ExtrinsicSuccess') {141 success = true;142 } else if ((section === 'common') && (method === 'ItemDestroyed')) {143 tokens.push({144 collectionId: parseInt(data[0].toString(), 10),145 tokenId: parseInt(data[1].toString(), 10),146 owner: data[2].toJSON(),147 });148 }149 });150 return {success, tokens};151 }152153 static findCollectionInEvents(events: {event: IChainEvent}[], collectionId: number, expectedSection: string, expectedMethod: string, label?: string) {154 let eventId = null;155 events.forEach(({event: {data, method, section}}) => {156 if ((section === expectedSection) && (method === expectedMethod)) {157 eventId = parseInt(data[0].toString(), 10);158 }159 });160161 if (eventId === null) {162 throw Error(`No ${expectedMethod} event for ${label}`);163 }164 return eventId === collectionId;165 }166167 static isTokenTransferSuccess(events: {event: IChainEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {168 const normalizeAddress = (address: string | ICrossAccountId) => {169 if(typeof address === 'string') return address;170 const obj = {} as any;171 Object.keys(address).forEach(k => {172 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];173 });174 if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};175 if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};176 return address;177 };178 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;179 events.forEach(({event: {data, method, section}}) => {180 if ((section === 'common') && (method === 'Transfer')) {181 const hData = (data as any).toJSON();182 transfer = {183 collectionId: hData[0],184 tokenId: hData[1],185 from: normalizeAddress(hData[2]),186 to: normalizeAddress(hData[3]),187 amount: BigInt(hData[4]),188 };189 }190 });191 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;192 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);193 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);194 isSuccess = isSuccess && amount === transfer.amount;195 return isSuccess;196 }197}198199200class ChainHelperBase {201 transactionStatus = UniqueUtil.transactionStatus;202 chainLogType = UniqueUtil.chainLogType;203 util: typeof UniqueUtil;204 logger: ILogger;205 api: ApiPromise | null;206 forcedNetwork: TUniqueNetworks | null;207 network: TUniqueNetworks | null;208 chainLog: IUniqueHelperLog[];209210 constructor(logger?: ILogger) {211 this.util = UniqueUtil;212 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();213 this.logger = logger;214 this.api = null;215 this.forcedNetwork = null;216 this.network = null;217 this.chainLog = [];218 }219220 clearChainLog(): void {221 this.chainLog = [];222 }223224 forceNetwork(value: TUniqueNetworks): void {225 this.forcedNetwork = value;226 }227228 async connect(wsEndpoint: string, listeners?: IApiListeners) {229 if (this.api !== null) throw Error('Already connected');230 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);231 this.api = api;232 this.network = network;233 }234235 async disconnect() {236 if (this.api === null) return;237 await this.api.disconnect();238 this.api = null;239 this.network = null;240 }241242 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {243 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;244 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;245 return 'opal';246 }247248 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {249 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});250 await api.isReady;251252 const network = await this.detectNetwork(api);253254 await api.disconnect();255256 return network;257 }258259 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{ 260 api: ApiPromise; 261 network: TUniqueNetworks; 262 }> {263 if(typeof network === 'undefined' || network === null) network = 'opal';264 const supportedRPC = {265 opal: {266 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,267 },268 quartz: {269 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,270 },271 unique: {272 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,273 },274 };275 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);276 const rpc = supportedRPC[network];277278 // TODO: investigate how to replace rpc in runtime279 // api._rpcCore.addUserInterfaces(rpc);280281 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});282283 await api.isReadyOrError;284285 if (typeof listeners === 'undefined') listeners = {};286 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {287 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;288 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);289 }290291 return {api, network};292 }293294 getTransactionStatus(data: {events: {event: IChainEvent}[], status: any}) {295 const {events, status} = data;296 if (status.isReady) {297 return this.transactionStatus.NOT_READY;298 }299 if (status.isBroadcast) {300 return this.transactionStatus.NOT_READY;301 }302 if (status.isInBlock || status.isFinalized) {303 const errors = events.filter(e => e.event.data.method === 'ExtrinsicFailed');304 if (errors.length > 0) {305 return this.transactionStatus.FAIL;306 }307 if (events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {308 return this.transactionStatus.SUCCESS;309 }310 }311312 return this.transactionStatus.FAIL;313 }314315 signTransaction(sender: TSigner, transaction: any, label = 'transaction', options: any = null) {316 const sign = (callback: any) => {317 if(options !== null) return transaction.signAndSend(sender, options, callback);318 return transaction.signAndSend(sender, callback);319 };320 // eslint-disable-next-line no-async-promise-executor321 return new Promise(async (resolve, reject) => {322 try {323 const unsub = await sign((result: any) => {324 const status = this.getTransactionStatus(result);325326 if (status === this.transactionStatus.SUCCESS) {327 this.logger.log(`${label} successful`);328 unsub();329 resolve({result, status});330 } else if (status === this.transactionStatus.FAIL) {331 let moduleError = null;332333 if (result.hasOwnProperty('dispatchError')) {334 const dispatchError = result['dispatchError'];335336 if (dispatchError && dispatchError.isModule) {337 const modErr = dispatchError.asModule;338 const errorMeta = dispatchError.registry.findMetaError(modErr);339340 moduleError = `${errorMeta.section}.${errorMeta.name}`;341 }342 else {343 this.logger.log(result, this.logger.level.ERROR);344 }345 }346347 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);348 unsub();349 reject({status, moduleError, result});350 }351 });352 } catch (e) {353 this.logger.log(e, this.logger.level.ERROR);354 reject(e);355 }356 });357 }358359 constructApiCall(apiCall: string, params: any[]) {360 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);361 let call = this.api as any;362 for(const part of apiCall.slice(4).split('.')) {363 call = call[part];364 }365 return call(...params);366 }367368 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=false, failureMessage='expected success') {369 if(this.api === null) throw Error('API not initialized');370 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);371372 const startTime = (new Date()).getTime();373 let result: ITransactionResult;374 let events = [];375 try {376 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), extrinsic) as ITransactionResult;377 events = result.result.events.map((x: any) => x.toHuman());378 }379 catch(e) {380 if(!(e as object).hasOwnProperty('status')) throw e;381 result = e as ITransactionResult;382 }383384 const endTime = (new Date()).getTime();385386 const log = {387 executedAt: endTime,388 executionTime: endTime - startTime,389 type: this.chainLogType.EXTRINSIC,390 status: result.status,391 call: extrinsic,392 signer: this.getSignerAddress(sender),393 params,394 } as IUniqueHelperLog;395396 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;397 if(events.length > 0) log.events = events;398399 this.chainLog.push(log);400401 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(failureMessage);402 return result;403 }404405 async callRpc(rpc: string, params?: any[]) {406 if(typeof params === 'undefined') params = [];407 if(this.api === null) throw Error('API not initialized');408 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);409410 const startTime = (new Date()).getTime();411 let result;412 let error = null;413 const log = {414 type: this.chainLogType.RPC,415 call: rpc,416 params,417 } as IUniqueHelperLog;418419 try {420 result = await this.constructApiCall(rpc, params);421 }422 catch(e) {423 error = e;424 }425426 const endTime = (new Date()).getTime();427428 log.executedAt = endTime;429 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';430 log.executionTime = endTime - startTime;431432 this.chainLog.push(log);433434 if(error !== null) throw error;435436 return result;437 }438439 getSignerAddress(signer: IKeyringPair | string): string {440 if(typeof signer === 'string') return signer;441 return signer.address;442 }443}444445446class HelperGroup {447 helper: UniqueHelper;448449 constructor(uniqueHelper: UniqueHelper) {450 this.helper = uniqueHelper;451 }452}453454455class CollectionGroup extends HelperGroup {456 /**457 * Get number of blocks when sponsored transaction is available.458 *459 * @param collectionId ID of collection460 * @param tokenId ID of token461 * @param addressObj address for which the sponsorship is checked462 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});463 * @returns number of blocks or null if sponsorship hasn't been set464 */465 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {466 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();467 }468469 /**470 * Get the number of created collections.471 * 472 * @returns number of created collections473 */474 async getTotalCount(): Promise<number> {475 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();476 }477478 /**479 * 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.480 * 481 * @param collectionId ID of collection482 * @example await getData(2)483 * @returns collection information object484 */485 async getData(collectionId: number): Promise<{486 id: number;487 name: string;488 description: string;489 tokensCount: number;490 admins: ICrossAccountId[];491 normalizedOwner: TSubstrateAccount;492 raw: any493 } | null> {494 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);495 const humanCollection = collection.toHuman(), collectionData = {496 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],497 raw: humanCollection,498 } as any, jsonCollection = collection.toJSON();499 if (humanCollection === null) return null;500 collectionData.raw.limits = jsonCollection.limits;501 collectionData.raw.permissions = jsonCollection.permissions;502 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);503 for (const key of ['name', 'description']) {504 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);505 }506507 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode)) ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId) : 0;508 collectionData.admins = await this.getAdmins(collectionId);509510 return collectionData;511 }512513 /**514 * Get the normalized addresses of the collection's administrators.515 * 516 * @param collectionId ID of collection517 * @example await getAdmins(1)518 * @returns array of administrators519 */520 async getAdmins(collectionId: number): Promise<ICrossAccountId[]> {521 const normalized = [];522 for(const admin of (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman()) {523 if(admin.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(admin.Substrate)});524 else normalized.push(admin);525 }526 return normalized;527 }528529 /**530 * Get the normalized addresses added to the collection allow-list.531 * @param collectionId ID of collection532 * @example await getAllowList(1)533 * @returns array of allow-listed addresses534 */535 async getAllowList(collectionId: number): Promise<ICrossAccountId[]> {536 const normalized = [];537 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();538 for (const address of allowListed) {539 if (address.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(address.Substrate)});540 else normalized.push(address);541 }542 return normalized;543 }544545 /**546 * Get the effective limits of the collection instead of null for default values547 * 548 * @param collectionId ID of collection549 * @example await getEffectiveLimits(2)550 * @returns object of collection limits551 */552 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {553 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();554 }555556 /**557 * Burns the collection if the signer has sufficient permissions and collection is empty.558 * 559 * @param signer keyring of signer560 * @param collectionId ID of collection561 * @param label extra label for log562 * @example await helper.collection.burn(aliceKeyring, 3);563 * @returns ```true``` if extrinsic success, otherwise ```false```564 */565 async burn(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {566 if(typeof label === 'undefined') label = `collection #${collectionId}`;567 const result = await this.helper.executeExtrinsic(568 signer,569 'api.tx.unique.destroyCollection', [collectionId],570 true, `Unable to burn collection for ${label}`,571 );572573 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed', label);574 }575576 /**577 * Sets the sponsor for the collection (Requires the Substrate address).578 * 579 * @param signer keyring of signer580 * @param collectionId ID of collection581 * @param sponsorAddress Sponsor substrate address582 * @param label extra label for log583 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")584 * @returns ```true``` if extrinsic success, otherwise ```false```585 */586 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount, label?: string): Promise<boolean> {587 if(typeof label === 'undefined') label = `collection #${collectionId}`;588 const result = await this.helper.executeExtrinsic(589 signer,590 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],591 true, `Unable to set collection sponsor for ${label}`,592 );593594 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet', label);595 }596597 /**598 * Confirms consent to sponsor the collection on behalf of the signer.599 * 600 * @param signer keyring of signer601 * @param collectionId ID of collection602 * @param label extra label for log603 * @example confirmSponsorship(aliceKeyring, 10)604 * @returns ```true``` if extrinsic success, otherwise ```false```605 */606 async confirmSponsorship(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {607 if(typeof label === 'undefined') label = `collection #${collectionId}`;608 const result = await this.helper.executeExtrinsic(609 signer,610 'api.tx.unique.confirmSponsorship', [collectionId],611 true, `Unable to confirm collection sponsorship for ${label}`,612 );613614 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed', label);615 }616617 /**618 * Sets the limits of the collection. At least one limit must be specified for a correct call.619 * 620 * @param signer keyring of signer621 * @param collectionId ID of collection622 * @param limits collection limits object623 * @param label extra label for log624 * @example625 * await setLimits(626 * aliceKeyring,627 * 10,628 * {629 * sponsorTransferTimeout: 0,630 * ownerCanDestroy: false631 * }632 * )633 * @returns ```true``` if extrinsic success, otherwise ```false```634 */635 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits, label?: string): Promise<boolean> {636 if(typeof label === 'undefined') label = `collection #${collectionId}`;637 const result = await this.helper.executeExtrinsic(638 signer,639 'api.tx.unique.setCollectionLimits', [collectionId, limits],640 true, `Unable to set collection limits for ${label}`,641 );642643 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet', label);644 }645646 /**647 * Changes the owner of the collection to the new Substrate address.648 * 649 * @param signer keyring of signer650 * @param collectionId ID of collection651 * @param ownerAddress substrate address of new owner652 * @param label extra label for log653 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")654 * @returns ```true``` if extrinsic success, otherwise ```false```655 */656 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount, label?: string): Promise<boolean> {657 if(typeof label === 'undefined') label = `collection #${collectionId}`;658 const result = await this.helper.executeExtrinsic(659 signer,660 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],661 true, `Unable to change collection owner for ${label}`,662 );663664 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged', label);665 }666667 /**668 * Adds a collection administrator. 669 * 670 * @param signer keyring of signer671 * @param collectionId ID of collection672 * @param adminAddressObj Administrator address (substrate or ethereum)673 * @param label extra label for log674 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})675 * @returns ```true``` if extrinsic success, otherwise ```false```676 */677 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {678 if(typeof label === 'undefined') label = `collection #${collectionId}`;679 const result = await this.helper.executeExtrinsic(680 signer,681 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],682 true, `Unable to add collection admin for ${label}`,683 );684685 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded', label);686 }687688 /**689 * Adds an address to allow list 690 * @param signer keyring of signer691 * @param collectionId ID of collection692 * @param addressObj address to add to the allow list693 * @param label extra label for log694 * @returns ```true``` if extrinsic success, otherwise ```false```695 */696 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId, label?: string): Promise<boolean> {697 if(typeof label === 'undefined') label = `collection #${collectionId}`;698 const result = await this.helper.executeExtrinsic(699 signer,700 'api.tx.unique.addToAllowList', [collectionId, addressObj],701 true, `Unable to add address to allow list for ${label}`,702 );703704 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');705 }706707 /**708 * Removes a collection administrator.709 * 710 * @param signer keyring of signer711 * @param collectionId ID of collection712 * @param adminAddressObj Administrator address (substrate or ethereum)713 * @param label extra label for log714 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})715 * @returns ```true``` if extrinsic success, otherwise ```false```716 */717 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {718 if(typeof label === 'undefined') label = `collection #${collectionId}`;719 const result = await this.helper.executeExtrinsic(720 signer,721 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],722 true, `Unable to remove collection admin for ${label}`,723 );724725 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved', label);726 }727728 /**729 * Sets onchain permissions for selected collection.730 * 731 * @param signer keyring of signer732 * @param collectionId ID of collection733 * @param permissions collection permissions object734 * @param label extra label for log735 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});736 * @returns ```true``` if extrinsic success, otherwise ```false```737 */738 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions, label?: string): Promise<boolean> {739 if(typeof label === 'undefined') label = `collection #${collectionId}`;740 const result = await this.helper.executeExtrinsic(741 signer,742 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],743 true, `Unable to set collection permissions for ${label}`,744 );745746 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet', label);747 }748749 /**750 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.751 * 752 * @param signer keyring of signer753 * @param collectionId ID of collection754 * @param permissions nesting permissions object755 * @param label extra label for log756 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});757 * @returns ```true``` if extrinsic success, otherwise ```false```758 */759 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions, label?: string): Promise<boolean> {760 return await this.setPermissions(signer, collectionId, {nesting: permissions}, label);761 }762763 /**764 * Disables nesting for selected collection.765 * 766 * @param signer keyring of signer767 * @param collectionId ID of collection768 * @param label extra label for log769 * @example disableNesting(aliceKeyring, 10);770 * @returns ```true``` if extrinsic success, otherwise ```false```771 */772 async disableNesting(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {773 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}}, label);774 }775776 /**777 * Sets onchain properties to the collection.778 * 779 * @param signer keyring of signer780 * @param collectionId ID of collection781 * @param properties array of property objects782 * @param label extra label for log783 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);784 * @returns ```true``` if extrinsic success, otherwise ```false```785 */786 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[], label?: string): Promise<boolean> {787 if(typeof label === 'undefined') label = `collection #${collectionId}`;788 const result = await this.helper.executeExtrinsic(789 signer,790 'api.tx.unique.setCollectionProperties', [collectionId, properties],791 true, `Unable to set collection properties for ${label}`,792 );793794 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet', label);795 }796797 /**798 * Deletes onchain properties from the collection.799 * 800 * @param signer keyring of signer801 * @param collectionId ID of collection802 * @param propertyKeys array of property keys to delete803 * @param label804 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);805 * @returns ```true``` if extrinsic success, otherwise ```false```806 */807 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[], label?: string): Promise<boolean> {808 if(typeof label === 'undefined') label = `collection #${collectionId}`;809 const result = await this.helper.executeExtrinsic(810 signer,811 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],812 true, `Unable to delete collection properties for ${label}`,813 );814815 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted', label);816 }817818 /**819 * Changes the owner of the token.820 * 821 * @param signer keyring of signer822 * @param collectionId ID of collection823 * @param tokenId ID of token824 * @param addressObj address of a new owner825 * @param amount amount of tokens to be transfered. For NFT must be set to 1n826 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})827 * @returns true if the token success, otherwise false828 */829 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {830 const result = await this.helper.executeExtrinsic(831 signer,832 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],833 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,834 );835836 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);837 }838839 /**840 * 841 * Change ownership of a token(s) on behalf of the owner. 842 * 843 * @param signer keyring of signer844 * @param collectionId ID of collection845 * @param tokenId ID of token846 * @param fromAddressObj address on behalf of which the token will be sent847 * @param toAddressObj new token owner848 * @param amount amount of tokens to be transfered. For NFT must be set to 1n849 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})850 * @returns true if the token success, otherwise false851 */852 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {853 const result = await this.helper.executeExtrinsic(854 signer,855 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],856 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,857 );858 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);859 }860861 /**862 * 863 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.864 * 865 * @param signer keyring of signer866 * @param collectionId ID of collection867 * @param tokenId ID of token868 * @param label 869 * @param amount amount of tokens to be burned. For NFT must be set to 1n870 * @example burnToken(aliceKeyring, 10, 5);871 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```872 */873 async burnToken(signer: TSigner, collectionId: number, tokenId: number, label?: string, amount=1n): Promise<{874 success: boolean,875 token: number | null876 }> {877 if(typeof label === 'undefined') label = `collection #${collectionId}`;878 const burnResult = await this.helper.executeExtrinsic(879 signer,880 'api.tx.unique.burnItem', [collectionId, tokenId, amount],881 true, `Unable to burn token for ${label}`,882 );883 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);884 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');885 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};886 }887888 /**889 * Destroys a concrete instance of NFT on behalf of the owner890 * 891 * @param signer keyring of signer892 * @param collectionId ID of collection893 * @param fromAddressObj address on behalf of which the token will be burnt894 * @param tokenId ID of token895 * @param label 896 * @param amount amount of tokens to be burned. For NFT must be set to 1n897 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})898 * @returns ```true``` if extrinsic success, otherwise ```false```899 */900 async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, label?: string, amount=1n): Promise<boolean> {901 if(typeof label === 'undefined') label = `collection #${collectionId}`;902 const burnResult = await this.helper.executeExtrinsic(903 signer,904 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],905 true, `Unable to burn token from for ${label}`,906 );907 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);908 return burnedTokens.success && burnedTokens.tokens.length > 0;909 }910911 /**912 * Set, change, or remove approved address to transfer the ownership of the NFT.913 * 914 * @param signer keyring of signer915 * @param collectionId ID of collection916 * @param tokenId ID of token917 * @param toAddressObj 918 * @param label 919 * @param amount amount of token to be approved. For NFT must be set to 1n920 * @returns ```true``` if extrinsic success, otherwise ```false```921 */922 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=1n) {923 if(typeof label === 'undefined') label = `collection #${collectionId}`;924 const approveResult = await this.helper.executeExtrinsic(925 signer, 926 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],927 true, `Unable to approve token for ${label}`,928 );929930 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved', label);931 }932933 /**934 * Get the amount of token pieces approved to transfer935 * @param collectionId ID of collection936 * @param tokenId ID of token937 * @param toAccountObj 938 * @param fromAccountObj939 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})940 * @returns number of approved to transfer pieces941 */942 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {943 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();944 }945946 /**947 * Get the last created token id948 * @param collectionId ID of collection949 * @example getLastTokenId(10);950 * @returns id of the last created token951 */952 async getLastTokenId(collectionId: number): Promise<number> {953 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();954 }955956 /**957 * Check if token exists958 * @param collectionId ID of collection959 * @param tokenId ID of token960 * @example isTokenExists(10, 20);961 * @returns true if the token exists, otherwise false962 */963 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {964 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();965 }966}967968class NFTnRFT extends CollectionGroup {969 /**970 * Get tokens owned by account971 * 972 * @param collectionId ID of collection973 * @param addressObj tokens owner974 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})975 * @returns array of token ids owned by account976 */977 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {978 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();979 }980981 /**982 * Get token data983 * @param collectionId ID of collection984 * @param tokenId ID of token985 * @param blockHashAt 986 * @param propertyKeys987 * @example getToken(10, 5);988 * @returns human readable token data 989 */990 async getToken(collectionId: number, tokenId: number, blockHashAt?: string, propertyKeys?: string[]): Promise<{991 properties: IProperty[];992 owner: ICrossAccountId;993 normalizedOwner: ICrossAccountId;994 }| null> {995 let tokenData;996 if(typeof blockHashAt === 'undefined') {997 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);998 }999 else {1000 if(typeof propertyKeys === 'undefined') {1001 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1002 if(!collection) return null;1003 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1004 }1005 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1006 }1007 tokenData = tokenData.toHuman();1008 if (tokenData === null || tokenData.owner === null) return null;1009 const owner = {} as any;1010 for (const key of Object.keys(tokenData.owner)) {1011 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];1012 }1013 tokenData.normalizedOwner = crossAccountIdFromLower(owner);1014 return tokenData;1015 }10161017 /**1018 * Set permissions to change token properties1019 * @param signer keyring of signer1020 * @param collectionId ID of collection1021 * @param permissions permissions to change a property by the collection owner or admin1022 * @param label 1023 * @example setTokenPropertyPermissions(1024 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1025 * )1026 * @returns true if extrinsic success otherwise false1027 */1028 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[], label?: string): Promise<boolean> {1029 if(typeof label === 'undefined') label = `collection #${collectionId}`;1030 const result = await this.helper.executeExtrinsic(1031 signer,1032 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1033 true, `Unable to set token property permissions for ${label}`,1034 );10351036 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet', label);1037 }10381039 /**1040 * Set token properties1041 * @param signer keyring of signer1042 * @param collectionId ID of collection1043 * @param tokenId ID of token1044 * @param properties 1045 * @param label 1046 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1047 * @returns ```true``` if extrinsic success, otherwise ```false```1048 */1049 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[], label?: string): Promise<boolean> {1050 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;1051 const result = await this.helper.executeExtrinsic(1052 signer,1053 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1054 true, `Unable to set token properties for ${label}`,1055 );10561057 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet', label);1058 }10591060 /**1061 * Delete the provided properties of a token1062 * @param signer keyring of signer1063 * @param collectionId ID of collection1064 * @param tokenId ID of token1065 * @param propertyKeys property keys to be deleted 1066 * @param label 1067 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1068 * @returns ```true``` if extrinsic success, otherwise ```false```1069 */1070 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[], label?: string): Promise<boolean> {1071 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;1072 const result = await this.helper.executeExtrinsic(1073 signer,1074 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1075 true, `Unable to delete token properties for ${label}`,1076 );10771078 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted', label);1079 }10801081 /**1082 * Mint new collection1083 * @param signer keyring of signer1084 * @param collectionOptions basic collection options and properties 1085 * @param mode NFT or RFT type of a collection1086 * @param errorLabel 1087 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1088 * @returns object of the created collection1089 */1090 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT', errorLabel = 'Unable to mint collection'): Promise<UniqueCollectionBase> {1091 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1092 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1093 for (const key of ['name', 'description', 'tokenPrefix']) {1094 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);1095 }1096 const creationResult = await this.helper.executeExtrinsic(1097 signer,1098 'api.tx.unique.createCollectionEx', [collectionOptions],1099 true, errorLabel,1100 );1101 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1102 }11031104 getCollectionObject(_collectionId: number): any {1105 return null;1106 }11071108 getTokenObject(_collectionId: number, _tokenId: number): any {1109 return null;1110 }1111}111211131114class NFTGroup extends NFTnRFT {1115 /**1116 * Get collection object1117 * @param collectionId ID of collection1118 * @example getCollectionObject(2);1119 * @returns instance of UniqueNFTCollection1120 */1121 getCollectionObject(collectionId: number): UniqueNFTCollection {1122 return new UniqueNFTCollection(collectionId, this.helper);1123 }11241125 /**1126 * Get token object1127 * @param collectionId ID of collection1128 * @param tokenId ID of token1129 * @example getTokenObject(10, 5);1130 * @returns instance of UniqueNFTToken1131 */1132 getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1133 return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1134 }11351136 /**1137 * Get token's owner1138 * @param collectionId ID of collection1139 * @param tokenId ID of token1140 * @param blockHashAt 1141 * @example getTokenOwner(10, 5);1142 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1143 */1144 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1145 let owner;1146 if (typeof blockHashAt === 'undefined') {1147 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1148 } else {1149 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1150 }1151 return crossAccountIdFromLower(owner.toJSON());1152 }11531154 /**1155 * Is token approved to transfer1156 * @param collectionId ID of collection1157 * @param tokenId ID of token1158 * @param toAccountObj address to be approved1159 * @returns ```true``` if extrinsic success, otherwise ```false```1160 */1161 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1162 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1163 }11641165 /**1166 * Changes the owner of the token.1167 * 1168 * @param signer keyring of signer1169 * @param collectionId ID of collection1170 * @param tokenId ID of token1171 * @param addressObj address of a new owner1172 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1173 * @returns ```true``` if extrinsic success, otherwise ```false```1174 */1175 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1176 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1177 }11781179 /**1180 * 1181 * Change ownership of a NFT on behalf of the owner. 1182 * 1183 * @param signer keyring of signer1184 * @param collectionId ID of collection1185 * @param tokenId ID of token1186 * @param fromAddressObj address on behalf of which the token will be sent1187 * @param toAddressObj new token owner1188 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1189 * @returns ```true``` if extrinsic success, otherwise ```false```1190 */1191 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1192 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1193 }11941195 /**1196 * Recursively find the address that owns the token1197 * @param collectionId ID of collection1198 * @param tokenId ID of token1199 * @param blockHashAt 1200 * @example getTokenTopmostOwner(10, 5);1201 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1202 */1203 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1204 let owner;1205 if (typeof blockHashAt === 'undefined') {1206 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1207 } else {1208 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1209 }12101211 if (owner === null) return null;12121213 owner = owner.toHuman();12141215 return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1216 }12171218 /**1219 * Get tokens nested in the provided token1220 * @param collectionId ID of collection1221 * @param tokenId ID of token1222 * @param blockHashAt 1223 * @example getTokenChildren(10, 5);1224 * @returns tokens whose depth of nesting is <= 5 1225 */1226 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1227 let children;1228 if(typeof blockHashAt === 'undefined') {1229 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1230 } else {1231 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1232 }12331234 return children.toJSON().map((x: any) => {1235 return {collectionId: x.collection, tokenId: x.token};1236 });1237 }12381239 /**1240 * Nest one token into another1241 * @param signer keyring of signer1242 * @param tokenObj token to be nested1243 * @param rootTokenObj token to be parent1244 * @param label 1245 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1246 * @returns ```true``` if extrinsic success, otherwise ```false```1247 */1248 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, label='nest token'): Promise<boolean> {1249 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1250 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1251 if(!result) {1252 throw Error(`Unable to nest token for ${label}`);1253 }1254 return result;1255 }12561257 /**1258 * Remove token from nested state1259 * @param signer keyring of signer1260 * @param tokenObj token to unnest1261 * @param rootTokenObj parent of a token1262 * @param toAddressObj address of a new token owner 1263 * @param label 1264 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1265 * @returns ```true``` if extrinsic success, otherwise ```false```1266 */1267 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId, label='unnest token'): Promise<boolean> {1268 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1269 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1270 if(!result) {1271 throw Error(`Unable to unnest token for ${label}`);1272 }1273 return result;1274 }12751276 /**1277 * Mint new collection1278 * @param signer keyring of signer1279 * @param collectionOptions Collection options1280 * @param label 1281 * @example 1282 * mintCollection(aliceKeyring, {1283 * name: 'New',1284 * description: 'New collection',1285 * tokenPrefix: 'NEW',1286 * })1287 * @returns object of the created collection1288 */1289 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueNFTCollection> {1290 return await super.mintCollection(signer, collectionOptions, 'NFT', `Unable to mint NFT collection for ${label}`) as UniqueNFTCollection;1291 }12921293 /**1294 * Mint new token1295 * @param signer keyring of signer1296 * @param data token data1297 * @param label 1298 * @returns created token object1299 */1300 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }, label?: string): Promise<UniqueNFTToken> {1301 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1302 const creationResult = await this.helper.executeExtrinsic(1303 signer,1304 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1305 nft: {1306 properties: data.properties,1307 },1308 }],1309 true, `Unable to mint NFT token for ${label}`,1310 );1311 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1312 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1313 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1314 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1315 }13161317 /**1318 * Mint multiple NFT tokens1319 * @param signer keyring of signer1320 * @param collectionId ID of collection1321 * @param tokens array of tokens with owner and properties1322 * @param label 1323 * @example 1324 * mintMultipleTokens(aliceKeyring, 10, [{1325 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1326 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1327 * },{1328 * owner: {Ethereum: "0x9F0583DbB855d..."},1329 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1330 * }]);1331 * @returns ```true``` if extrinsic success, otherwise ```false```1332 */1333 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1334 if(typeof label === 'undefined') label = `collection #${collectionId}`;1335 const creationResult = await this.helper.executeExtrinsic(1336 signer,1337 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1338 true, `Unable to mint NFT tokens for ${label}`,1339 );1340 const collection = this.getCollectionObject(collectionId);1341 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1342 }13431344 /**1345 * Mint multiple NFT tokens with one owner1346 * @param signer keyring of signer1347 * @param collectionId ID of collection1348 * @param owner tokens owner1349 * @param tokens array of tokens with owner and properties1350 * @param label 1351 * @example1352 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1353 * properties: [{1354 * key: "gender",1355 * value: "female",1356 * },{1357 * key: "age",1358 * value: "33",1359 * }],1360 * }]);1361 * @returns array of newly created tokens1362 */1363 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1364 if(typeof label === 'undefined') label = `collection #${collectionId}`;1365 const rawTokens = [];1366 for (const token of tokens) {1367 const raw = {NFT: {properties: token.properties}};1368 rawTokens.push(raw);1369 }1370 const creationResult = await this.helper.executeExtrinsic(1371 signer,1372 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1373 true, `Unable to mint NFT tokens for ${label}`,1374 );1375 const collection = this.getCollectionObject(collectionId);1376 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1377 }13781379 /**1380 * Destroys a concrete instance of NFT.1381 * @param signer keyring of signer1382 * @param collectionId ID of collection1383 * @param tokenId ID of token1384 * @param label 1385 * @example burnToken(aliceKeyring, 10, 5);1386 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1387 */1388 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string): Promise<{ success: boolean; token: number | null; }> {1389 return await super.burnToken(signer, collectionId, tokenId, label, 1n);1390 }13911392 /**1393 * Set, change, or remove approved address to transfer the ownership of the NFT.1394 * 1395 * @param signer keyring of signer1396 * @param collectionId ID of collection1397 * @param tokenId ID of token1398 * @param toAddressObj address to approve1399 * @param label 1400 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1401 * @returns ```true``` if extrinsic success, otherwise ```false```1402 */1403 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {1404 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, 1n);1405 }1406}140714081409class RFTGroup extends NFTnRFT {1410 /**1411 * Get collection object1412 * @param collectionId ID of collection1413 * @example getCollectionObject(2);1414 * @returns instance of UniqueRFTCollection1415 */1416 getCollectionObject(collectionId: number): UniqueRFTCollection {1417 return new UniqueRFTCollection(collectionId, this.helper);1418 }14191420 /**1421 * Get token object1422 * @param collectionId ID of collection1423 * @param tokenId ID of token1424 * @example getTokenObject(10, 5);1425 * @returns instance of UniqueNFTToken1426 */1427 getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1428 return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1429 }14301431 /**1432 * Get top 10 token owners with the largest number of pieces 1433 * @param collectionId ID of collection1434 * @param tokenId ID of token1435 * @example getTokenTop10Owners(10, 5);1436 * @returns array of top 10 owners1437 */1438 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1439 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1440 }14411442 /**1443 * Get number of pieces owned by address1444 * @param collectionId ID of collection1445 * @param tokenId ID of token1446 * @param addressObj address token owner1447 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1448 * @returns number of pieces ownerd by address1449 */1450 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1451 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1452 }14531454 /**1455 * Transfer pieces of token to another address1456 * @param signer keyring of signer1457 * @param collectionId ID of collection1458 * @param tokenId ID of token1459 * @param addressObj address of a new owner1460 * @param amount number of pieces to be transfered1461 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1462 * @returns ```true``` if extrinsic success, otherwise ```false```1463 */1464 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=100n): Promise<boolean> {1465 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1466 }14671468 /**1469 * Change ownership of some pieces of RFT on behalf of the owner. 1470 * @param signer keyring of signer1471 * @param collectionId ID of collection1472 * @param tokenId ID of token1473 * @param fromAddressObj address on behalf of which the token will be sent1474 * @param toAddressObj new token owner1475 * @param amount number of pieces to be transfered1476 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1477 * @returns ```true``` if extrinsic success, otherwise ```false```1478 */1479 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n): Promise<boolean> {1480 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1481 }14821483 /**1484 * Mint new collection1485 * @param signer keyring of signer1486 * @param collectionOptions Collection options1487 * @param label 1488 * @example1489 * mintCollection(aliceKeyring, {1490 * name: 'New',1491 * description: 'New collection',1492 * tokenPrefix: 'NEW',1493 * })1494 * @returns object of the created collection1495 */1496 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueRFTCollection> {1497 return await super.mintCollection(signer, collectionOptions, 'RFT', `Unable to mint RFT collection for ${label}`) as UniqueRFTCollection;1498 }14991500 /**1501 * Mint new token1502 * @param signer keyring of signer1503 * @param data token data1504 * @param label 1505 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1506 * @returns created token object1507 */1508 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }, label?: string): Promise<UniqueRFTToken> {1509 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1510 const creationResult = await this.helper.executeExtrinsic(1511 signer,1512 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1513 refungible: {1514 pieces: data.pieces,1515 properties: data.properties,1516 },1517 }],1518 true, `Unable to mint RFT token for ${label}`,1519 );1520 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1521 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1522 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1523 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1524 }15251526 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1527 throw Error('Not implemented');1528 if(typeof label === 'undefined') label = `collection #${collectionId}`;1529 const creationResult = await this.helper.executeExtrinsic(1530 signer,1531 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1532 true, `Unable to mint RFT tokens for ${label}`,1533 );1534 const collection = this.getCollectionObject(collectionId);1535 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1536 }15371538 /**1539 * Mint multiple RFT tokens with one owner1540 * @param signer keyring of signer1541 * @param collectionId ID of collection1542 * @param owner tokens owner1543 * @param tokens array of tokens with properties and pieces1544 * @param label 1545 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1546 * @returns array of newly created RFT tokens1547 */1548 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1549 if(typeof label === 'undefined') label = `collection #${collectionId}`;1550 const rawTokens = [];1551 for (const token of tokens) {1552 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1553 rawTokens.push(raw);1554 }1555 const creationResult = await this.helper.executeExtrinsic(1556 signer,1557 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1558 true, `Unable to mint RFT tokens for ${label}`,1559 );1560 const collection = this.getCollectionObject(collectionId);1561 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1562 }15631564 /**1565 * Destroys a concrete instance of RFT.1566 * @param signer keyring of signer1567 * @param collectionId ID of collection1568 * @param tokenId ID of token1569 * @param label 1570 * @param amount number of pieces to be burnt1571 * @example burnToken(aliceKeyring, 10, 5);1572 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1573 */1574 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string, amount=100n): Promise<{ success: boolean; token: number | null; }> {1575 return await super.burnToken(signer, collectionId, tokenId, label, amount);1576 }15771578 /**1579 * Set, change, or remove approved address to transfer the ownership of the RFT.1580 * 1581 * @param signer keyring of signer1582 * @param collectionId ID of collection1583 * @param tokenId ID of token1584 * @param toAddressObj address to approve1585 * @param label 1586 * @param amount number of pieces to be approved1587 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1588 * @returns true if the token success, otherwise false1589 */1590 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=100n) {1591 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, amount);1592 }15931594 /**1595 * Get total number of pieces1596 * @param collectionId ID of collection1597 * @param tokenId ID of token1598 * @example getTokenTotalPieces(10, 5);1599 * @returns number of pieces1600 */1601 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1602 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1603 }16041605 /**1606 * Change number of token pieces. Signer must be the owner of all token pieces.1607 * @param signer keyring of signer1608 * @param collectionId ID of collection1609 * @param tokenId ID of token1610 * @param amount new number of pieces1611 * @param label 1612 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1613 * @returns true if the repartion was success, otherwise false1614 */1615 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint, label?: string): Promise<boolean> {1616 if(typeof label === 'undefined') label = `collection #${collectionId}`;1617 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1618 const repartitionResult = await this.helper.executeExtrinsic(1619 signer,1620 'api.tx.unique.repartition', [collectionId, tokenId, amount],1621 true, `Unable to repartition RFT token for ${label}`,1622 );1623 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated', label);1624 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed', label);1625 }1626}162716281629class FTGroup extends CollectionGroup {1630 /**1631 * Get collection object1632 * @param collectionId ID of collection1633 * @example getCollectionObject(2);1634 * @returns instance of UniqueFTCollection1635 */1636 getCollectionObject(collectionId: number): UniqueFTCollection {1637 return new UniqueFTCollection(collectionId, this.helper);1638 }16391640 /**1641 * Mint new fungible collection1642 * @param signer keyring of signer1643 * @param collectionOptions Collection options1644 * @param decimalPoints number of token decimals 1645 * @param errorLabel 1646 * @example1647 * mintCollection(aliceKeyring, {1648 * name: 'New',1649 * description: 'New collection',1650 * tokenPrefix: 'NEW',1651 * }, 18)1652 * @returns newly created fungible collection1653 */1654 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0, errorLabel = 'Unable to mint collection'): Promise<UniqueFTCollection> {1655 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1656 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1657 collectionOptions.mode = {fungible: decimalPoints};1658 for (const key of ['name', 'description', 'tokenPrefix']) {1659 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);1660 }1661 const creationResult = await this.helper.executeExtrinsic(1662 signer,1663 'api.tx.unique.createCollectionEx', [collectionOptions],1664 true, errorLabel,1665 );1666 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1667 }16681669 /**1670 * Mint tokens1671 * @param signer keyring of signer1672 * @param collectionId ID of collection1673 * @param owner address owner of new tokens1674 * @param amount amount of tokens to be meanted1675 * @param label 1676 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1677 * @returns ```true``` if extrinsic success, otherwise ```false``` 1678 */1679 async mintTokens(signer: TSigner, collectionId: number, owner: ICrossAccountId | string, amount: bigint, label?: string): Promise<boolean> {1680 if(typeof label === 'undefined') label = `collection #${collectionId}`;1681 const creationResult = await this.helper.executeExtrinsic(1682 signer,1683 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1684 fungible: {1685 value: amount,1686 },1687 }],1688 true, `Unable to mint fungible tokens for ${label}`,1689 );1690 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1691 }16921693 /**1694 * Mint multiple Fungible tokens with one owner1695 * @param signer keyring of signer1696 * @param collectionId ID of collection1697 * @param owner tokens owner1698 * @param tokens array of tokens with properties and pieces1699 * @param label 1700 * @returns ```true``` if extrinsic success, otherwise ```false``` 1701 */1702 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string): Promise<boolean> {1703 if(typeof label === 'undefined') label = `collection #${collectionId}`;1704 const rawTokens = [];1705 for (const token of tokens) {1706 const raw = {Fungible: {Value: token.value}};1707 rawTokens.push(raw);1708 }1709 const creationResult = await this.helper.executeExtrinsic(1710 signer,1711 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1712 true, `Unable to mint RFT tokens for ${label}`,1713 );1714 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1715 }17161717 /**1718 * Get the top 10 owners with the largest balance for the Fungible collection 1719 * @param collectionId ID of collection1720 * @example getTop10Owners(10);1721 * @returns array of ```ICrossAccountId```1722 */1723 async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1724 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1725 }17261727 /**1728 * Get account balance1729 * @param collectionId ID of collection1730 * @param addressObj address of owner1731 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1732 * @returns amount of fungible tokens owned by address1733 */1734 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1735 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1736 }17371738 /**1739 * Transfer tokens to address1740 * @param signer keyring of signer1741 * @param collectionId ID of collection1742 * @param toAddressObj address recepient1743 * @param amount amount of tokens to be sent1744 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1745 * @returns ```true``` if extrinsic success, otherwise ```false``` 1746 */1747 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount: bigint) {1748 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1749 }17501751 /**1752 * Transfer some tokens on behalf of the owner.1753 * @param signer keyring of signer1754 * @param collectionId ID of collection1755 * @param fromAddressObj address on behalf of which tokens will be sent1756 * @param toAddressObj address where token to be sent1757 * @param amount number of tokens to be sent1758 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1759 * @returns ```true``` if extrinsic success, otherwise ```false``` 1760 */1761 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {1762 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1763 }17641765 /**1766 * Destroy some amount of tokens1767 * @param signer keyring of signer1768 * @param collectionId ID of collection1769 * @param amount amount of tokens to be destroyed1770 * @param label 1771 * @example burnTokens(aliceKeyring, 10, 1000n);1772 * @returns ```true``` if extrinsic success, otherwise ```false``` 1773 */1774 async burnTokens(signer: IKeyringPair, collectionId: number, amount=100n, label?: string): Promise<boolean> {1775 return (await super.burnToken(signer, collectionId, 0, label, amount)).success;1776 }17771778 /**1779 * Burn some tokens on behalf of the owner.1780 * @param signer keyring of signer1781 * @param collectionId ID of collection1782 * @param fromAddressObj address on behalf of which tokens will be burnt1783 * @param amount amount of tokens to be burnt1784 * @param label 1785 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1786 * @returns ```true``` if extrinsic success, otherwise ```false``` 1787 */1788 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=100n, label?: string): Promise<boolean> {1789 return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, label, amount);1790 }17911792 /**1793 * Get total collection supply1794 * @param collectionId 1795 * @returns 1796 */1797 async getTotalPieces(collectionId: number): Promise<bigint> {1798 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1799 }18001801 /**1802 * Set, change, or remove approved address to transfer tokens.1803 * 1804 * @param signer keyring of signer1805 * @param collectionId ID of collection1806 * @param toAddressObj address to be approved1807 * @param amount amount of tokens to be approved1808 * @param label 1809 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1810 * @returns ```true``` if extrinsic success, otherwise ```false``` 1811 */1812 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {1813 return super.approveToken(signer, collectionId, 0, toAddressObj, label, amount);1814 }18151816 /**1817 * Get amount of fungible tokens approved to transfer1818 * @param collectionId ID of collection1819 * @param fromAddressObj owner of tokens1820 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1821 * @returns number of tokens approved for the transfer1822 */1823 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1824 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1825 }1826}182718281829class ChainGroup extends HelperGroup {1830 /**1831 * Get system properties of a chain1832 * @example getChainProperties();1833 * @returns ss58Format, token decimals, and token symbol1834 */1835 getChainProperties(): IChainProperties {1836 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1837 return {1838 ss58Format: properties.ss58Format.toJSON(),1839 tokenDecimals: properties.tokenDecimals.toJSON(),1840 tokenSymbol: properties.tokenSymbol.toJSON(),1841 };1842 }18431844 /**1845 * Get chain header1846 * @example getLatestBlockNumber();1847 * @returns the number of the last block1848 */1849 async getLatestBlockNumber(): Promise<number> {1850 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1851 }18521853 /**1854 * Get block hash by block number1855 * @param blockNumber number of block1856 * @example getBlockHashByNumber(12345);1857 * @returns hash of a block1858 */1859 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1860 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1861 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1862 return blockHash;1863 }18641865 /**1866 * Get account nonce1867 * @param address substrate address1868 * @example getNonce("5GrwvaEF5zXb26Fz...");1869 * @returns number, account's nonce1870 */1871 async getNonce(address: TSubstrateAccount): Promise<number> {1872 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1873 }1874}187518761877class BalanceGroup extends HelperGroup {1878 /**1879 * Representation of the native token in the smallest unit1880 * @example getOneTokenNominal()1881 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.1882 */1883 getOneTokenNominal(): bigint {1884 const chainProperties = this.helper.chain.getChainProperties();1885 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1886 }18871888 /**1889 * Get substrate address balance1890 * @param address substrate address1891 * @example getSubstrate("5GrwvaEF5zXb26Fz...")1892 * @returns amount of tokens on address1893 */1894 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {1895 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();1896 }18971898 /**1899 * Get ethereum address balance1900 * @param address ethereum address1901 * @example getEthereum("0x9F0583DbB855d...")1902 * @returns amount of tokens on address1903 */1904 async getEthereum(address: TEthereumAccount): Promise<bigint> {1905 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();1906 }19071908 /**1909 * Transfer tokens to substrate address1910 * @param signer keyring of signer1911 * @param address substrate address of a recepient1912 * @param amount amount of tokens to be transfered1913 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);1914 * @returns ```true``` if extrinsic success, otherwise ```false```1915 */1916 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {1917 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}`);19181919 let transfer = {from: null, to: null, amount: 0n} as any;1920 result.result.events.forEach(({event: {data, method, section}}) => {1921 if ((section === 'balances') && (method === 'Transfer')) {1922 transfer = {1923 from: this.helper.address.normalizeSubstrate(data[0]),1924 to: this.helper.address.normalizeSubstrate(data[1]),1925 amount: BigInt(data[2]),1926 };1927 }1928 });1929 let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;1930 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;1931 isSuccess = isSuccess && BigInt(amount) === transfer.amount;1932 return isSuccess;1933 }1934}193519361937class AddressGroup extends HelperGroup {1938 /**1939 * Normalizes the address to the specified ss58 format, by default ```42```.1940 * @param address substrate address1941 * @param ss58Format format for address conversion, by default ```42```1942 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY1943 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation1944 */1945 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {1946 return this.helper.util.normalizeSubstrateAddress(address, ss58Format);1947 }19481949 /**1950 * Get address in the connected chain format1951 * @param address substrate address1952 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network1953 * @returns address in chain format1954 */1955 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {1956 const info = this.helper.chain.getChainProperties();1957 return encodeAddress(decodeAddress(address), info.ss58Format);1958 }19591960 /**1961 * Get substrate mirror of an ethereum address1962 * @param ethAddress ethereum address1963 * @param toChainFormat false for normalized account1964 * @example ethToSubstrate('0x9F0583DbB855d...')1965 * @returns substrate mirror of a provided ethereum address1966 */1967 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {1968 if(!toChainFormat) return evmToAddress(ethAddress);1969 const info = this.helper.chain.getChainProperties();1970 return evmToAddress(ethAddress, info.ss58Format);1971 }19721973 /**1974 * Get ethereum mirror of a substrate address1975 * @param subAddress substrate account1976 * @example substrateToEth("5DnSF6RRjwteE3BrC...")1977 * @returns ethereum mirror of a provided substrate address1978 */1979 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {1980 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));1981 }1982}198319841985export class UniqueHelper extends ChainHelperBase {1986 chain: ChainGroup;1987 balance: BalanceGroup;1988 address: AddressGroup;1989 collection: CollectionGroup;1990 nft: NFTGroup;1991 rft: RFTGroup;1992 ft: FTGroup;19931994 constructor(logger?: ILogger) {1995 super(logger);1996 this.chain = new ChainGroup(this);1997 this.balance = new BalanceGroup(this);1998 this.address = new AddressGroup(this);1999 this.collection = new CollectionGroup(this);2000 this.nft = new NFTGroup(this);2001 this.rft = new RFTGroup(this);2002 this.ft = new FTGroup(this);2003 } 2004}200520062007class UniqueCollectionBase {2008 helper: UniqueHelper;2009 collectionId: number;20102011 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2012 this.collectionId = collectionId;2013 this.helper = uniqueHelper;2014 }20152016 async getData() {2017 return await this.helper.collection.getData(this.collectionId);2018 }20192020 async getLastTokenId() {2021 return await this.helper.collection.getLastTokenId(this.collectionId);2022 }20232024 async isTokenExists(tokenId: number) {2025 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2026 }20272028 async getAdmins() {2029 return await this.helper.collection.getAdmins(this.collectionId);2030 }20312032 async getAllowList() {2033 return await this.helper.collection.getAllowList(this.collectionId);2034 }20352036 async getEffectiveLimits() {2037 return await this.helper.collection.getEffectiveLimits(this.collectionId);2038 }20392040 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount, label?: string) {2041 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress, label);2042 }20432044 async confirmSponsorship(signer: TSigner, label?: string) {2045 return await this.helper.collection.confirmSponsorship(signer, this.collectionId, label);2046 }20472048 async setLimits(signer: TSigner, limits: ICollectionLimits, label?: string) {2049 return await this.helper.collection.setLimits(signer, this.collectionId, limits, label);2050 }20512052 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount, label?: string) {2053 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress, label);2054 }20552056 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {2057 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj, label);2058 }20592060 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId, label?: string) {2061 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj, label);2062 }20632064 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {2065 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj, label);2066 }20672068 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {2069 return await this.helper.collection.setProperties(signer, this.collectionId, properties, label);2070 }20712072 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {2073 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys, label);2074 }20752076 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2077 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2078 }20792080 async setPermissions(signer: TSigner, permissions: ICollectionPermissions, label?: string) {2081 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions, label);2082 }20832084 async enableNesting(signer: TSigner, permissions: INestingPermissions, label?: string) {2085 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions, label);2086 }20872088 async disableNesting(signer: TSigner, label?: string) {2089 return await this.helper.collection.disableNesting(signer, this.collectionId, label);2090 }20912092 async burn(signer: TSigner, label?: string) {2093 return await this.helper.collection.burn(signer, this.collectionId, label);2094 }2095}209620972098class UniqueNFTCollection extends UniqueCollectionBase {2099 getTokenObject(tokenId: number) {2100 return new UniqueNFTToken(tokenId, this);2101 }21022103 async getTokensByAddress(addressObj: ICrossAccountId) {2104 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2105 }21062107 async getToken(tokenId: number, blockHashAt?: string) {2108 return await this.helper.nft.getToken(this.collectionId, tokenId, blockHashAt);2109 }21102111 async getTokenOwner(tokenId: number, blockHashAt?: string) {2112 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2113 }21142115 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2116 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2117 }21182119 async getTokenChildren(tokenId: number, blockHashAt?: string) {2120 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2121 }21222123 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2124 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2125 }21262127 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2128 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2129 }21302131 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {2132 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label);2133 }21342135 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2136 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2137 }21382139 async mintToken(signer: TSigner, owner: ICrossAccountId, properties?: IProperty[], label?: string) {2140 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties}, label);2141 }21422143 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string) {2144 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens, label);2145 }21462147 async burnToken(signer: TSigner, tokenId: number, label?: string) {2148 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId, label);2149 }21502151 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {2152 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);2153 }21542155 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {2156 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);2157 }21582159 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {2160 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);2161 }21622163 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken, label?: string) {2164 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj, label);2165 }21662167 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {2168 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj, label);2169 }2170}217121722173class UniqueRFTCollection extends UniqueCollectionBase {2174 getTokenObject(tokenId: number) {2175 return new UniqueRFTToken(tokenId, this);2176 }21772178 async getTokensByAddress(addressObj: ICrossAccountId) {2179 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2180 }21812182 async getTop10TokenOwners(tokenId: number) {2183 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2184 }21852186 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2187 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2188 }21892190 async getTokenTotalPieces(tokenId: number) {2191 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2192 }21932194 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=100n) {2195 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2196 }21972198 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {2199 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2200 }22012202 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2203 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label, amount);2204 }22052206 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2207 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2208 }22092210 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint, label?: string) {2211 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount, label);2212 }22132214 async mintToken(signer: TSigner, owner: ICrossAccountId, pieces=100n, properties?: IProperty[], label?: string) {2215 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties}, label);2216 }22172218 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string) {2219 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens, label);2220 }22212222 async burnToken(signer: TSigner, tokenId: number, amount=100n, label?: string) {2223 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, label, amount);2224 }22252226 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {2227 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);2228 }22292230 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {2231 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);2232 }22332234 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {2235 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);2236 }2237}223822392240class UniqueFTCollection extends UniqueCollectionBase {2241 async mint(signer: TSigner, owner: ICrossAccountId, amount: bigint, label?: string) {2242 return await this.helper.ft.mintTokens(signer, this.collectionId, owner, amount, label);2243 }22442245 async mintWithOneOwner(signer: TSigner, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string) {2246 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, owner, tokens, label);2247 }22482249 async getBalance(addressObj: ICrossAccountId) {2250 return await this.helper.ft.getBalance(this.collectionId, addressObj);2251 }22522253 async getTop10Owners() {2254 return await this.helper.ft.getTop10Owners(this.collectionId);2255 }22562257 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount: bigint) {2258 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2259 }22602261 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {2262 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2263 }22642265 async burnTokens(signer: TSigner, amount: bigint, label?: string) {2266 return await this.helper.ft.burnTokens(signer, this.collectionId, amount, label);2267 }22682269 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount: bigint, label?: string) {2270 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount, label);2271 }22722273 async getTotalPieces() {2274 return await this.helper.ft.getTotalPieces(this.collectionId);2275 }22762277 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2278 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount, label);2279 }22802281 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2282 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2283 }2284}228522862287class UniqueTokenBase implements IToken {2288 collection: UniqueNFTCollection | UniqueRFTCollection;2289 collectionId: number;2290 tokenId: number;22912292 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2293 this.collection = collection;2294 this.collectionId = collection.collectionId;2295 this.tokenId = tokenId;2296 }22972298 async getNextSponsored(addressObj: ICrossAccountId) {2299 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2300 }23012302 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {2303 return await this.collection.setTokenProperties(signer, this.tokenId, properties, label);2304 }23052306 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {2307 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys, label);2308 }2309}231023112312class UniqueNFTToken extends UniqueTokenBase {2313 collection: UniqueNFTCollection;23142315 constructor(tokenId: number, collection: UniqueNFTCollection) {2316 super(tokenId, collection);2317 this.collection = collection;2318 }23192320 async getData(blockHashAt?: string) {2321 return await this.collection.getToken(this.tokenId, blockHashAt);2322 }23232324 async getOwner(blockHashAt?: string) {2325 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2326 }23272328 async getTopmostOwner(blockHashAt?: string) {2329 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2330 }23312332 async getChildren(blockHashAt?: string) {2333 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2334 }23352336 async nest(signer: TSigner, toTokenObj: IToken, label?: string) {2337 return await this.collection.nestToken(signer, this.tokenId, toTokenObj, label);2338 }23392340 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {2341 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj, label);2342 }23432344 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2345 return await this.collection.transferToken(signer, this.tokenId, addressObj);2346 }23472348 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2349 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2350 }23512352 async approve(signer: TSigner, toAddressObj: ICrossAccountId, label?: string) {2353 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, label);2354 }23552356 async isApproved(toAddressObj: ICrossAccountId) {2357 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2358 }23592360 async burn(signer: TSigner, label?: string) {2361 return await this.collection.burnToken(signer, this.tokenId, label);2362 }2363}23642365class UniqueRFTToken extends UniqueTokenBase {2366 collection: UniqueRFTCollection;23672368 constructor(tokenId: number, collection: UniqueRFTCollection) {2369 super(tokenId, collection);2370 this.collection = collection;2371 }23722373 async getTop10Owners() {2374 return await this.collection.getTop10TokenOwners(this.tokenId);2375 }23762377 async getBalance(addressObj: ICrossAccountId) {2378 return await this.collection.getTokenBalance(this.tokenId, addressObj);2379 }23802381 async getTotalPieces() {2382 return await this.collection.getTokenTotalPieces(this.tokenId);2383 }23842385 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=100n) {2386 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2387 }23882389 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {2390 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2391 }23922393 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2394 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount, label);2395 }23962397 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2398 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2399 }24002401 async repartition(signer: TSigner, amount: bigint, label?: string) {2402 return await this.collection.repartitionToken(signer, this.tokenId, amount, label);2403 }24042405 async burn(signer: TSigner, amount=100n, label?: string) {2406 return await this.collection.burnToken(signer, this.tokenId, amount, label);2407 }2408}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IChainEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {15 const address = {} as ICrossAccountId;16 if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;17 if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;18 return address;19};202122const nesting = {23 toChecksumAddress(address: string): string {24 if (typeof address === 'undefined') return '';2526 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);2728 address = address.toLowerCase().replace(/^0x/i,'');29 const addressHash = keccakAsHex(address).replace(/^0x/i,'');30 const checksumAddress = ['0x'];3132 for (let i = 0; i < address.length; i++) {33 // If ith character is 8 to f then make it uppercase34 if (parseInt(addressHash[i], 16) > 7) {35 checksumAddress.push(address[i].toUpperCase());36 } else {37 checksumAddress.push(address[i]);38 }39 }40 return checksumAddress.join('');41 },42 tokenIdToAddress(collectionId: number, tokenId: number) {43 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);44 },45};4647class UniqueUtil {48 static transactionStatus = {49 NOT_READY: 'NotReady',50 FAIL: 'Fail',51 SUCCESS: 'Success',52 };5354 static chainLogType = {55 EXTRINSIC: 'extrinsic',56 RPC: 'rpc',57 };5859 static getNestingTokenAddress(collectionId: number, tokenId: number) {60 return nesting.tokenIdToAddress(collectionId, tokenId);61 }6263 static getDefaultLogger(): ILogger {64 return {65 log(msg: any, level = 'INFO') {66 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));67 },68 level: {69 ERROR: 'ERROR',70 WARNING: 'WARNING',71 INFO: 'INFO',72 },73 };74 }7576 static vec2str(arr: string[] | number[]) {77 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');78 }7980 static str2vec(string: string) {81 if (typeof string !== 'string') return string;82 return Array.from(string).map(x => x.charCodeAt(0));83 }8485 static fromSeed(seed: string, ss58Format = 42) {86 const keyring = new Keyring({type: 'sr25519', ss58Format});87 return keyring.addFromUri(seed);88 }8990 static normalizeSubstrateAddress(address: string, ss58Format = 42) {91 return encodeAddress(decodeAddress(address), ss58Format);92 }9394 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult) {95 if (creationResult.status !== this.transactionStatus.SUCCESS) {96 throw Error('Unable to create collection!');97 }9899 let collectionId = null;100 creationResult.result.events.forEach(({event: {data, method, section}}) => {101 if ((section === 'common') && (method === 'CollectionCreated')) {102 collectionId = parseInt(data[0].toString(), 10);103 }104 });105106 if (collectionId === null) {107 throw Error('No CollectionCreated event was found!');108 }109110 return collectionId;111 }112113 static extractTokensFromCreationResult(creationResult: ITransactionResult) {114 if (creationResult.status !== this.transactionStatus.SUCCESS) {115 throw Error('Unable to create tokens!');116 }117 let success = false;118 const tokens = [] as any;119 creationResult.result.events.forEach(({event: {data, method, section}}) => {120 if (method === 'ExtrinsicSuccess') {121 success = true;122 } else if ((section === 'common') && (method === 'ItemCreated')) {123 tokens.push({124 collectionId: parseInt(data[0].toString(), 10),125 tokenId: parseInt(data[1].toString(), 10),126 owner: data[2].toJSON(),127 });128 }129 });130 return {success, tokens};131 }132133 static extractTokensFromBurnResult(burnResult: ITransactionResult) {134 if (burnResult.status !== this.transactionStatus.SUCCESS) {135 throw Error('Unable to burn tokens!');136 }137 let success = false;138 const tokens = [] as any;139 burnResult.result.events.forEach(({event: {data, method, section}}) => {140 if (method === 'ExtrinsicSuccess') {141 success = true;142 } else if ((section === 'common') && (method === 'ItemDestroyed')) {143 tokens.push({144 collectionId: parseInt(data[0].toString(), 10),145 tokenId: parseInt(data[1].toString(), 10),146 owner: data[2].toJSON(),147 });148 }149 });150 return {success, tokens};151 }152153 static findCollectionInEvents(events: {event: IChainEvent}[], collectionId: number, expectedSection: string, expectedMethod: string) {154 let eventId = null;155 events.forEach(({event: {data, method, section}}) => {156 if ((section === expectedSection) && (method === expectedMethod)) {157 eventId = parseInt(data[0].toString(), 10);158 }159 });160161 if (eventId === null) {162 throw Error(`No ${expectedMethod} event was found!`);163 }164 return eventId === collectionId;165 }166167 static isTokenTransferSuccess(events: {event: IChainEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {168 const normalizeAddress = (address: string | ICrossAccountId) => {169 if(typeof address === 'string') return address;170 const obj = {} as any;171 Object.keys(address).forEach(k => {172 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];173 });174 if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};175 if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};176 return address;177 };178 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;179 events.forEach(({event: {data, method, section}}) => {180 if ((section === 'common') && (method === 'Transfer')) {181 const hData = (data as any).toJSON();182 transfer = {183 collectionId: hData[0],184 tokenId: hData[1],185 from: normalizeAddress(hData[2]),186 to: normalizeAddress(hData[3]),187 amount: BigInt(hData[4]),188 };189 }190 });191 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;192 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);193 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);194 isSuccess = isSuccess && amount === transfer.amount;195 return isSuccess;196 }197}198199200class ChainHelperBase {201 transactionStatus = UniqueUtil.transactionStatus;202 chainLogType = UniqueUtil.chainLogType;203 util: typeof UniqueUtil;204 logger: ILogger;205 api: ApiPromise | null;206 forcedNetwork: TUniqueNetworks | null;207 network: TUniqueNetworks | null;208 chainLog: IUniqueHelperLog[];209210 constructor(logger?: ILogger) {211 this.util = UniqueUtil;212 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();213 this.logger = logger;214 this.api = null;215 this.forcedNetwork = null;216 this.network = null;217 this.chainLog = [];218 }219220 clearChainLog(): void {221 this.chainLog = [];222 }223224 forceNetwork(value: TUniqueNetworks): void {225 this.forcedNetwork = value;226 }227228 async connect(wsEndpoint: string, listeners?: IApiListeners) {229 if (this.api !== null) throw Error('Already connected');230 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);231 this.api = api;232 this.network = network;233 }234235 async disconnect() {236 if (this.api === null) return;237 await this.api.disconnect();238 this.api = null;239 this.network = null;240 }241242 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {243 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;244 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;245 return 'opal';246 }247248 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {249 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});250 await api.isReady;251252 const network = await this.detectNetwork(api);253254 await api.disconnect();255256 return network;257 }258259 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{ 260 api: ApiPromise; 261 network: TUniqueNetworks; 262 }> {263 if(typeof network === 'undefined' || network === null) network = 'opal';264 const supportedRPC = {265 opal: {266 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,267 },268 quartz: {269 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,270 },271 unique: {272 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,273 },274 };275 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);276 const rpc = supportedRPC[network];277278 // TODO: investigate how to replace rpc in runtime279 // api._rpcCore.addUserInterfaces(rpc);280281 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});282283 await api.isReadyOrError;284285 if (typeof listeners === 'undefined') listeners = {};286 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {287 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;288 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);289 }290291 return {api, network};292 }293294 getTransactionStatus(data: {events: {event: IChainEvent}[], status: any}) {295 const {events, status} = data;296 if (status.isReady) {297 return this.transactionStatus.NOT_READY;298 }299 if (status.isBroadcast) {300 return this.transactionStatus.NOT_READY;301 }302 if (status.isInBlock || status.isFinalized) {303 const errors = events.filter(e => e.event.data.method === 'ExtrinsicFailed');304 if (errors.length > 0) {305 return this.transactionStatus.FAIL;306 }307 if (events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {308 return this.transactionStatus.SUCCESS;309 }310 }311312 return this.transactionStatus.FAIL;313 }314315 signTransaction(sender: TSigner, transaction: any, label = 'transaction', options: any = null) {316 const sign = (callback: any) => {317 if(options !== null) return transaction.signAndSend(sender, options, callback);318 return transaction.signAndSend(sender, callback);319 };320 // eslint-disable-next-line no-async-promise-executor321 return new Promise(async (resolve, reject) => {322 try {323 const unsub = await sign((result: any) => {324 const status = this.getTransactionStatus(result);325326 if (status === this.transactionStatus.SUCCESS) {327 this.logger.log(`${label} successful`);328 unsub();329 resolve({result, status});330 } else if (status === this.transactionStatus.FAIL) {331 let moduleError = null;332333 if (result.hasOwnProperty('dispatchError')) {334 const dispatchError = result['dispatchError'];335336 if (dispatchError && dispatchError.isModule) {337 const modErr = dispatchError.asModule;338 const errorMeta = dispatchError.registry.findMetaError(modErr);339340 moduleError = `${errorMeta.section}.${errorMeta.name}`;341 }342 else {343 this.logger.log(result, this.logger.level.ERROR);344 }345 }346347 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);348 unsub();349 reject({status, moduleError, result});350 }351 });352 } catch (e) {353 this.logger.log(e, this.logger.level.ERROR);354 reject(e);355 }356 });357 }358359 constructApiCall(apiCall: string, params: any[]) {360 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);361 let call = this.api as any;362 for(const part of apiCall.slice(4).split('.')) {363 call = call[part];364 }365 return call(...params);366 }367368 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=false/*, failureMessage='expected success'*/) {369 if(this.api === null) throw Error('API not initialized');370 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);371372 const startTime = (new Date()).getTime();373 let result: ITransactionResult;374 let events = [];375 try {376 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), extrinsic) as ITransactionResult;377 events = result.result.events.map((x: any) => x.toHuman());378 }379 catch(e) {380 if(!(e as object).hasOwnProperty('status')) throw e;381 result = e as ITransactionResult;382 }383384 const endTime = (new Date()).getTime();385386 const log = {387 executedAt: endTime,388 executionTime: endTime - startTime,389 type: this.chainLogType.EXTRINSIC,390 status: result.status,391 call: extrinsic,392 signer: this.getSignerAddress(sender),393 params,394 } as IUniqueHelperLog;395396 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;397 if(events.length > 0) log.events = events;398399 this.chainLog.push(log);400401 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);402 return result;403 }404405 async callRpc(rpc: string, params?: any[]) {406 if(typeof params === 'undefined') params = [];407 if(this.api === null) throw Error('API not initialized');408 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);409410 const startTime = (new Date()).getTime();411 let result;412 let error = null;413 const log = {414 type: this.chainLogType.RPC,415 call: rpc,416 params,417 } as IUniqueHelperLog;418419 try {420 result = await this.constructApiCall(rpc, params);421 }422 catch(e) {423 error = e;424 }425426 const endTime = (new Date()).getTime();427428 log.executedAt = endTime;429 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';430 log.executionTime = endTime - startTime;431432 this.chainLog.push(log);433434 if(error !== null) throw error;435436 return result;437 }438439 getSignerAddress(signer: IKeyringPair | string): string {440 if(typeof signer === 'string') return signer;441 return signer.address;442 }443}444445446class HelperGroup {447 helper: UniqueHelper;448449 constructor(uniqueHelper: UniqueHelper) {450 this.helper = uniqueHelper;451 }452}453454455class CollectionGroup extends HelperGroup {456 /**457 * Get number of blocks when sponsored transaction is available.458 *459 * @param collectionId ID of collection460 * @param tokenId ID of token461 * @param addressObj address for which the sponsorship is checked462 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});463 * @returns number of blocks or null if sponsorship hasn't been set464 */465 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {466 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();467 }468469 /**470 * Get the number of created collections.471 * 472 * @returns number of created collections473 */474 async getTotalCount(): Promise<number> {475 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();476 }477478 /**479 * 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.480 * 481 * @param collectionId ID of collection482 * @example await getData(2)483 * @returns collection information object484 */485 async getData(collectionId: number): Promise<{486 id: number;487 name: string;488 description: string;489 tokensCount: number;490 admins: ICrossAccountId[];491 normalizedOwner: TSubstrateAccount;492 raw: any493 } | null> {494 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);495 const humanCollection = collection.toHuman(), collectionData = {496 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],497 raw: humanCollection,498 } as any, jsonCollection = collection.toJSON();499 if (humanCollection === null) return null;500 collectionData.raw.limits = jsonCollection.limits;501 collectionData.raw.permissions = jsonCollection.permissions;502 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);503 for (const key of ['name', 'description']) {504 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);505 }506507 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode)) ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId) : 0;508 collectionData.admins = await this.getAdmins(collectionId);509510 return collectionData;511 }512513 /**514 * Get the normalized addresses of the collection's administrators.515 * 516 * @param collectionId ID of collection517 * @example await getAdmins(1)518 * @returns array of administrators519 */520 async getAdmins(collectionId: number): Promise<ICrossAccountId[]> {521 const normalized = [];522 for(const admin of (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman()) {523 if(admin.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(admin.Substrate)});524 else normalized.push(admin);525 }526 return normalized;527 }528529 /**530 * Get the normalized addresses added to the collection allow-list.531 * @param collectionId ID of collection532 * @example await getAllowList(1)533 * @returns array of allow-listed addresses534 */535 async getAllowList(collectionId: number): Promise<ICrossAccountId[]> {536 const normalized = [];537 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();538 for (const address of allowListed) {539 if (address.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(address.Substrate)});540 else normalized.push(address);541 }542 return normalized;543 }544545 /**546 * Get the effective limits of the collection instead of null for default values547 * 548 * @param collectionId ID of collection549 * @example await getEffectiveLimits(2)550 * @returns object of collection limits551 */552 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {553 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();554 }555556 /**557 * Burns the collection if the signer has sufficient permissions and collection is empty.558 * 559 * @param signer keyring of signer560 * @param collectionId ID of collection561 * @example await helper.collection.burn(aliceKeyring, 3);562 * @returns ```true``` if extrinsic success, otherwise ```false```563 */564 async burn(signer: TSigner, collectionId: number): Promise<boolean> {565 const result = await this.helper.executeExtrinsic(566 signer,567 'api.tx.unique.destroyCollection', [collectionId],568 true,569 );570571 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');572 }573574 /**575 * Sets the sponsor for the collection (Requires the Substrate address).576 * 577 * @param signer keyring of signer578 * @param collectionId ID of collection579 * @param sponsorAddress Sponsor substrate address580 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")581 * @returns ```true``` if extrinsic success, otherwise ```false```582 */583 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {584 const result = await this.helper.executeExtrinsic(585 signer,586 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],587 true,588 );589590 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');591 }592593 /**594 * Confirms consent to sponsor the collection on behalf of the signer.595 * 596 * @param signer keyring of signer597 * @param collectionId ID of collection598 * @example confirmSponsorship(aliceKeyring, 10)599 * @returns ```true``` if extrinsic success, otherwise ```false```600 */601 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {602 const result = await this.helper.executeExtrinsic(603 signer,604 'api.tx.unique.confirmSponsorship', [collectionId],605 true,606 );607608 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');609 }610611 /**612 * Sets the limits of the collection. At least one limit must be specified for a correct call.613 * 614 * @param signer keyring of signer615 * @param collectionId ID of collection616 * @param limits collection limits object617 * @example618 * await setLimits(619 * aliceKeyring,620 * 10,621 * {622 * sponsorTransferTimeout: 0,623 * ownerCanDestroy: false624 * }625 * )626 * @returns ```true``` if extrinsic success, otherwise ```false```627 */628 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {629 const result = await this.helper.executeExtrinsic(630 signer,631 'api.tx.unique.setCollectionLimits', [collectionId, limits],632 true,633 );634635 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');636 }637638 /**639 * Changes the owner of the collection to the new Substrate address.640 * 641 * @param signer keyring of signer642 * @param collectionId ID of collection643 * @param ownerAddress substrate address of new owner644 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")645 * @returns ```true``` if extrinsic success, otherwise ```false```646 */647 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {648 const result = await this.helper.executeExtrinsic(649 signer,650 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],651 true,652 );653654 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');655 }656657 /**658 * Adds a collection administrator. 659 * 660 * @param signer keyring of signer661 * @param collectionId ID of collection662 * @param adminAddressObj Administrator address (substrate or ethereum)663 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})664 * @returns ```true``` if extrinsic success, otherwise ```false```665 */666 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {667 const result = await this.helper.executeExtrinsic(668 signer,669 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],670 true,671 );672673 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');674 }675676 /**677 * Removes a collection administrator.678 * 679 * @param signer keyring of signer680 * @param collectionId ID of collection681 * @param adminAddressObj Administrator address (substrate or ethereum)682 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})683 * @returns ```true``` if extrinsic success, otherwise ```false```684 */685 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {686 const result = await this.helper.executeExtrinsic(687 signer,688 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],689 true,690 );691692 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');693 }694695 /**696 * Adds an address to allow list 697 * @param signer keyring of signer698 * @param collectionId ID of collection699 * @param addressObj address to add to the allow list700 * @returns ```true``` if extrinsic success, otherwise ```false```701 */702 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {703 const result = await this.helper.executeExtrinsic(704 signer,705 'api.tx.unique.addToAllowList', [collectionId, addressObj],706 true,707 );708709 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');710 }711712 /**713 * Removes an address from allow list 714 * 715 * @param signer keyring of signer716 * @param collectionId ID of collection717 * @param addressObj address to remove from the allow list718 * @returns ```true``` if extrinsic success, otherwise ```false```719 */720 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {721 const result = await this.helper.executeExtrinsic(722 signer,723 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],724 true,725 );726727 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');728 }729730 /**731 * Sets onchain permissions for selected collection.732 * 733 * @param signer keyring of signer734 * @param collectionId ID of collection735 * @param permissions collection permissions object736 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});737 * @returns ```true``` if extrinsic success, otherwise ```false```738 */739 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {740 const result = await this.helper.executeExtrinsic(741 signer,742 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],743 true,744 );745746 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');747 }748749 /**750 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.751 * 752 * @param signer keyring of signer753 * @param collectionId ID of collection754 * @param permissions nesting permissions object755 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});756 * @returns ```true``` if extrinsic success, otherwise ```false```757 */758 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {759 return await this.setPermissions(signer, collectionId, {nesting: permissions});760 }761762 /**763 * Disables nesting for selected collection.764 * 765 * @param signer keyring of signer766 * @param collectionId ID of collection767 * @example disableNesting(aliceKeyring, 10);768 * @returns ```true``` if extrinsic success, otherwise ```false```769 */770 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {771 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});772 }773774 /**775 * Sets onchain properties to the collection.776 * 777 * @param signer keyring of signer778 * @param collectionId ID of collection779 * @param properties array of property objects780 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);781 * @returns ```true``` if extrinsic success, otherwise ```false```782 */783 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {784 const result = await this.helper.executeExtrinsic(785 signer,786 'api.tx.unique.setCollectionProperties', [collectionId, properties],787 true,788 );789790 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');791 }792793 /**794 * Deletes onchain properties from the collection.795 * 796 * @param signer keyring of signer797 * @param collectionId ID of collection798 * @param propertyKeys array of property keys to delete799 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);800 * @returns ```true``` if extrinsic success, otherwise ```false```801 */802 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {803 const result = await this.helper.executeExtrinsic(804 signer,805 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],806 true,807 );808809 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');810 }811812 /**813 * Changes the owner of the token.814 * 815 * @param signer keyring of signer816 * @param collectionId ID of collection817 * @param tokenId ID of token818 * @param addressObj address of a new owner819 * @param amount amount of tokens to be transfered. For NFT must be set to 1n820 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})821 * @returns true if the token success, otherwise false822 */823 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {824 const result = await this.helper.executeExtrinsic(825 signer,826 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],827 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,828 );829830 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);831 }832833 /**834 * 835 * Change ownership of a token(s) on behalf of the owner. 836 * 837 * @param signer keyring of signer838 * @param collectionId ID of collection839 * @param tokenId ID of token840 * @param fromAddressObj address on behalf of which the token will be sent841 * @param toAddressObj new token owner842 * @param amount amount of tokens to be transfered. For NFT must be set to 1n843 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})844 * @returns true if the token success, otherwise false845 */846 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {847 const result = await this.helper.executeExtrinsic(848 signer,849 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],850 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,851 );852 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);853 }854855 /**856 * 857 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.858 * 859 * @param signer keyring of signer860 * @param collectionId ID of collection861 * @param tokenId ID of token862 * @param amount amount of tokens to be burned. For NFT must be set to 1n863 * @example burnToken(aliceKeyring, 10, 5);864 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```865 */866 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<{867 success: boolean,868 token: number | null869 }> {870 const burnResult = await this.helper.executeExtrinsic(871 signer,872 'api.tx.unique.burnItem', [collectionId, tokenId, amount],873 true, // `Unable to burn token for ${label}`,874 );875 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);876 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');877 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};878 }879880 /**881 * Destroys a concrete instance of NFT on behalf of the owner882 * 883 * @param signer keyring of signer884 * @param collectionId ID of collection885 * @param fromAddressObj address on behalf of which the token will be burnt886 * @param tokenId ID of token887 * @param amount amount of tokens to be burned. For NFT must be set to 1n888 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})889 * @returns ```true``` if extrinsic success, otherwise ```false```890 */891 async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, amount=1n): Promise<boolean> {892 const burnResult = await this.helper.executeExtrinsic(893 signer,894 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],895 true, // `Unable to burn token from for ${label}`,896 );897 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);898 return burnedTokens.success && burnedTokens.tokens.length > 0;899 }900901 /**902 * Set, change, or remove approved address to transfer the ownership of the NFT.903 * 904 * @param signer keyring of signer905 * @param collectionId ID of collection906 * @param tokenId ID of token907 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens908 * @param amount amount of token to be approved. For NFT must be set to 1n909 * @returns ```true``` if extrinsic success, otherwise ```false```910 */911 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {912 const approveResult = await this.helper.executeExtrinsic(913 signer, 914 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],915 true, // `Unable to approve token for ${label}`,916 );917918 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');919 }920921 /**922 * Get the amount of token pieces approved to transfer or burn. Normally 0.923 * 924 * @param collectionId ID of collection925 * @param tokenId ID of token926 * @param toAccountObj address which is approved to use token pieces927 * @param fromAccountObj address which may have allowed the use of its owned tokens928 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})929 * @returns number of approved to transfer pieces930 */931 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {932 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();933 }934935 /**936 * Get the last created token ID in a collection937 * 938 * @param collectionId ID of collection939 * @example getLastTokenId(10);940 * @returns id of the last created token941 */942 async getLastTokenId(collectionId: number): Promise<number> {943 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();944 }945946 /**947 * Check if token exists948 * 949 * @param collectionId ID of collection950 * @param tokenId ID of token951 * @example isTokenExists(10, 20);952 * @returns true if the token exists, otherwise false953 */954 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {955 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();956 }957}958959class NFTnRFT extends CollectionGroup {960 /**961 * Get tokens owned by account962 * 963 * @param collectionId ID of collection964 * @param addressObj tokens owner965 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})966 * @returns array of token ids owned by account967 */968 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {969 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();970 }971972 /**973 * Get token data974 * 975 * @param collectionId ID of collection976 * @param tokenId ID of token977 * @param propertyKeys optionally filter the token properties to only these keys978 * @param blockHashAt optionally query the data at some block with this hash979 * @example getToken(10, 5);980 * @returns human readable token data 981 */982 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{983 properties: IProperty[];984 owner: ICrossAccountId;985 normalizedOwner: ICrossAccountId;986 }| null> {987 let tokenData;988 if(typeof blockHashAt === 'undefined') {989 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);990 }991 else {992 if(propertyKeys.length == 0) {993 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();994 if(!collection) return null;995 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);996 }997 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);998 }999 tokenData = tokenData.toHuman();1000 if (tokenData === null || tokenData.owner === null) return null;1001 const owner = {} as any;1002 for (const key of Object.keys(tokenData.owner)) {1003 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];1004 }1005 tokenData.normalizedOwner = crossAccountIdFromLower(owner);1006 return tokenData;1007 }10081009 /**1010 * Set permissions to change token properties1011 * 1012 * @param signer keyring of signer1013 * @param collectionId ID of collection1014 * @param permissions permissions to change a property by the collection owner or admin1015 * @example setTokenPropertyPermissions(1016 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1017 * )1018 * @returns true if extrinsic success otherwise false1019 */1020 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1021 const result = await this.helper.executeExtrinsic(1022 signer,1023 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1024 true,1025 );10261027 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1028 }10291030 /**1031 * Set token properties1032 * 1033 * @param signer keyring of signer1034 * @param collectionId ID of collection1035 * @param tokenId ID of token1036 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1037 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1038 * @returns ```true``` if extrinsic success, otherwise ```false```1039 */1040 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1041 const result = await this.helper.executeExtrinsic(1042 signer,1043 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1044 true,1045 );10461047 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1048 }10491050 /**1051 * Delete the provided properties of a token1052 * @param signer keyring of signer1053 * @param collectionId ID of collection1054 * @param tokenId ID of token1055 * @param propertyKeys property keys to be deleted 1056 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1057 * @returns ```true``` if extrinsic success, otherwise ```false```1058 */1059 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1060 const result = await this.helper.executeExtrinsic(1061 signer,1062 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1063 true,1064 );10651066 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1067 }10681069 /**1070 * Mint new collection1071 * 1072 * @param signer keyring of signer1073 * @param collectionOptions basic collection options and properties 1074 * @param mode NFT or RFT type of a collection1075 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1076 * @returns object of the created collection1077 */1078 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueCollectionBase> {1079 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1080 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1081 for (const key of ['name', 'description', 'tokenPrefix']) {1082 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);1083 }1084 const creationResult = await this.helper.executeExtrinsic(1085 signer,1086 'api.tx.unique.createCollectionEx', [collectionOptions],1087 true, // errorLabel,1088 );1089 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1090 }10911092 getCollectionObject(_collectionId: number): any {1093 return null;1094 }10951096 getTokenObject(_collectionId: number, _tokenId: number): any {1097 return null;1098 }1099}110011011102class NFTGroup extends NFTnRFT {1103 /**1104 * Get collection object1105 * @param collectionId ID of collection1106 * @example getCollectionObject(2);1107 * @returns instance of UniqueNFTCollection1108 */1109 getCollectionObject(collectionId: number): UniqueNFTCollection {1110 return new UniqueNFTCollection(collectionId, this.helper);1111 }11121113 /**1114 * Get token object1115 * @param collectionId ID of collection1116 * @param tokenId ID of token1117 * @example getTokenObject(10, 5);1118 * @returns instance of UniqueNFTToken1119 */1120 getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1121 return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1122 }11231124 /**1125 * Get token's owner1126 * @param collectionId ID of collection1127 * @param tokenId ID of token1128 * @param blockHashAt optionally query the data at the block with this hash1129 * @example getTokenOwner(10, 5);1130 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1131 */1132 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1133 let owner;1134 if (typeof blockHashAt === 'undefined') {1135 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1136 } else {1137 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1138 }1139 return crossAccountIdFromLower(owner.toJSON());1140 }11411142 /**1143 * Is token approved to transfer1144 * @param collectionId ID of collection1145 * @param tokenId ID of token1146 * @param toAccountObj address to be approved1147 * @returns ```true``` if extrinsic success, otherwise ```false```1148 */1149 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1150 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1151 }11521153 /**1154 * Changes the owner of the token.1155 * 1156 * @param signer keyring of signer1157 * @param collectionId ID of collection1158 * @param tokenId ID of token1159 * @param addressObj address of a new owner1160 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1161 * @returns ```true``` if extrinsic success, otherwise ```false```1162 */1163 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1164 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1165 }11661167 /**1168 * 1169 * Change ownership of a NFT on behalf of the owner. 1170 * 1171 * @param signer keyring of signer1172 * @param collectionId ID of collection1173 * @param tokenId ID of token1174 * @param fromAddressObj address on behalf of which the token will be sent1175 * @param toAddressObj new token owner1176 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1177 * @returns ```true``` if extrinsic success, otherwise ```false```1178 */1179 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1180 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1181 }11821183 /**1184 * Recursively find the address that owns the token1185 * @param collectionId ID of collection1186 * @param tokenId ID of token1187 * @param blockHashAt 1188 * @example getTokenTopmostOwner(10, 5);1189 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1190 */1191 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1192 let owner;1193 if (typeof blockHashAt === 'undefined') {1194 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1195 } else {1196 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1197 }11981199 if (owner === null) return null;12001201 owner = owner.toHuman();12021203 return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1204 }12051206 /**1207 * Get tokens nested in the provided token1208 * @param collectionId ID of collection1209 * @param tokenId ID of token1210 * @param blockHashAt optionally query the data at the block with this hash1211 * @example getTokenChildren(10, 5);1212 * @returns tokens whose depth of nesting is <= 5 1213 */1214 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1215 let children;1216 if(typeof blockHashAt === 'undefined') {1217 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1218 } else {1219 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1220 }12211222 return children.toJSON().map((x: any) => {1223 return {collectionId: x.collection, tokenId: x.token};1224 });1225 }12261227 /**1228 * Nest one token into another1229 * @param signer keyring of signer1230 * @param tokenObj token to be nested1231 * @param rootTokenObj token to be parent1232 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1233 * @returns ```true``` if extrinsic success, otherwise ```false```1234 */1235 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1236 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1237 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1238 if(!result) {1239 throw Error('Unable to nest token!');1240 }1241 return result;1242 }12431244 /**1245 * Remove token from nested state1246 * @param signer keyring of signer1247 * @param tokenObj token to unnest1248 * @param rootTokenObj parent of a token1249 * @param toAddressObj address of a new token owner 1250 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1251 * @returns ```true``` if extrinsic success, otherwise ```false```1252 */1253 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1254 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1255 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1256 if(!result) {1257 throw Error('Unable to unnest token!');1258 }1259 return result;1260 }12611262 /**1263 * Mint new collection1264 * @param signer keyring of signer1265 * @param collectionOptions Collection options1266 * @example 1267 * mintCollection(aliceKeyring, {1268 * name: 'New',1269 * description: 'New collection',1270 * tokenPrefix: 'NEW',1271 * })1272 * @returns object of the created collection1273 */1274 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueNFTCollection> {1275 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1276 }12771278 /**1279 * Mint new token1280 * @param signer keyring of signer1281 * @param data token data1282 * @returns created token object1283 */1284 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFTToken> {1285 const creationResult = await this.helper.executeExtrinsic(1286 signer,1287 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1288 nft: {1289 properties: data.properties,1290 },1291 }],1292 true,1293 );1294 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1295 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1296 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1297 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1298 }12991300 /**1301 * Mint multiple NFT tokens1302 * @param signer keyring of signer1303 * @param collectionId ID of collection1304 * @param tokens array of tokens with owner and properties1305 * @example 1306 * mintMultipleTokens(aliceKeyring, 10, [{1307 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1308 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1309 * },{1310 * owner: {Ethereum: "0x9F0583DbB855d..."},1311 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1312 * }]);1313 * @returns ```true``` if extrinsic success, otherwise ```false```1314 */1315 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1316 const creationResult = await this.helper.executeExtrinsic(1317 signer,1318 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1319 true,1320 );1321 const collection = this.getCollectionObject(collectionId);1322 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1323 }13241325 /**1326 * Mint multiple NFT tokens with one owner1327 * @param signer keyring of signer1328 * @param collectionId ID of collection1329 * @param owner tokens owner1330 * @param tokens array of tokens with owner and properties1331 * @example1332 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1333 * properties: [{1334 * key: "gender",1335 * value: "female",1336 * },{1337 * key: "age",1338 * value: "33",1339 * }],1340 * }]);1341 * @returns array of newly created tokens1342 */1343 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1344 const rawTokens = [];1345 for (const token of tokens) {1346 const raw = {NFT: {properties: token.properties}};1347 rawTokens.push(raw);1348 }1349 const creationResult = await this.helper.executeExtrinsic(1350 signer,1351 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1352 true,1353 );1354 const collection = this.getCollectionObject(collectionId);1355 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1356 }13571358 /**1359 * Destroys a concrete instance of NFT.1360 * @param signer keyring of signer1361 * @param collectionId ID of collection1362 * @param tokenId ID of token1363 * @example burnToken(aliceKeyring, 10, 5);1364 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1365 */1366 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number): Promise<{ success: boolean; token: number | null; }> {1367 return await super.burnToken(signer, collectionId, tokenId, 1n);1368 }13691370 /**1371 * Set, change, or remove approved address to transfer the ownership of the NFT.1372 * 1373 * @param signer keyring of signer1374 * @param collectionId ID of collection1375 * @param tokenId ID of token1376 * @param toAddressObj address to approve1377 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1378 * @returns ```true``` if extrinsic success, otherwise ```false```1379 */1380 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1381 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1382 }1383}138413851386class RFTGroup extends NFTnRFT {1387 /**1388 * Get collection object1389 * @param collectionId ID of collection1390 * @example getCollectionObject(2);1391 * @returns instance of UniqueRFTCollection1392 */1393 getCollectionObject(collectionId: number): UniqueRFTCollection {1394 return new UniqueRFTCollection(collectionId, this.helper);1395 }13961397 /**1398 * Get token object1399 * @param collectionId ID of collection1400 * @param tokenId ID of token1401 * @example getTokenObject(10, 5);1402 * @returns instance of UniqueNFTToken1403 */1404 getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1405 return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1406 }14071408 /**1409 * Get top 10 token owners with the largest number of pieces 1410 * @param collectionId ID of collection1411 * @param tokenId ID of token1412 * @example getTokenTop10Owners(10, 5);1413 * @returns array of top 10 owners1414 */1415 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1416 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1417 }14181419 /**1420 * Get number of pieces owned by address1421 * @param collectionId ID of collection1422 * @param tokenId ID of token1423 * @param addressObj address token owner1424 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1425 * @returns number of pieces ownerd by address1426 */1427 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1428 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1429 }14301431 /**1432 * Transfer pieces of token to another address1433 * @param signer keyring of signer1434 * @param collectionId ID of collection1435 * @param tokenId ID of token1436 * @param addressObj address of a new owner1437 * @param amount number of pieces to be transfered1438 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1439 * @returns ```true``` if extrinsic success, otherwise ```false```1440 */1441 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1442 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1443 }14441445 /**1446 * Change ownership of some pieces of RFT on behalf of the owner. 1447 * @param signer keyring of signer1448 * @param collectionId ID of collection1449 * @param tokenId ID of token1450 * @param fromAddressObj address on behalf of which the token will be sent1451 * @param toAddressObj new token owner1452 * @param amount number of pieces to be transfered1453 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1454 * @returns ```true``` if extrinsic success, otherwise ```false```1455 */1456 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1457 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1458 }14591460 /**1461 * Mint new collection1462 * @param signer keyring of signer1463 * @param collectionOptions Collection options1464 * @example1465 * mintCollection(aliceKeyring, {1466 * name: 'New',1467 * description: 'New collection',1468 * tokenPrefix: 'NEW',1469 * })1470 * @returns object of the created collection1471 */1472 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueRFTCollection> {1473 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1474 }14751476 /**1477 * Mint new token1478 * @param signer keyring of signer1479 * @param data token data1480 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1481 * @returns created token object1482 */1483 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFTToken> {1484 const creationResult = await this.helper.executeExtrinsic(1485 signer,1486 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1487 refungible: {1488 pieces: data.pieces,1489 properties: data.properties,1490 },1491 }],1492 true,1493 );1494 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1495 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1496 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1497 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1498 }14991500 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1501 throw Error('Not implemented');1502 const creationResult = await this.helper.executeExtrinsic(1503 signer,1504 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1505 true, // `Unable to mint RFT tokens for ${label}`,1506 );1507 const collection = this.getCollectionObject(collectionId);1508 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1509 }15101511 /**1512 * Mint multiple RFT tokens with one owner1513 * @param signer keyring of signer1514 * @param collectionId ID of collection1515 * @param owner tokens owner1516 * @param tokens array of tokens with properties and pieces1517 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1518 * @returns array of newly created RFT tokens1519 */1520 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1521 const rawTokens = [];1522 for (const token of tokens) {1523 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1524 rawTokens.push(raw);1525 }1526 const creationResult = await this.helper.executeExtrinsic(1527 signer,1528 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1529 true,1530 );1531 const collection = this.getCollectionObject(collectionId);1532 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1533 }15341535 /**1536 * Destroys a concrete instance of RFT.1537 * @param signer keyring of signer1538 * @param collectionId ID of collection1539 * @param tokenId ID of token1540 * @param amount number of pieces to be burnt1541 * @example burnToken(aliceKeyring, 10, 5);1542 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1543 */1544 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<{ success: boolean; token: number | null; }> {1545 return await super.burnToken(signer, collectionId, tokenId, amount);1546 }15471548 /**1549 * Set, change, or remove approved address to transfer the ownership of the RFT.1550 * 1551 * @param signer keyring of signer1552 * @param collectionId ID of collection1553 * @param tokenId ID of token1554 * @param toAddressObj address to approve1555 * @param amount number of pieces to be approved1556 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1557 * @returns true if the token success, otherwise false1558 */1559 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1560 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1561 }15621563 /**1564 * Get total number of pieces1565 * @param collectionId ID of collection1566 * @param tokenId ID of token1567 * @example getTokenTotalPieces(10, 5);1568 * @returns number of pieces1569 */1570 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1571 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1572 }15731574 /**1575 * Change number of token pieces. Signer must be the owner of all token pieces.1576 * @param signer keyring of signer1577 * @param collectionId ID of collection1578 * @param tokenId ID of token1579 * @param amount new number of pieces1580 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1581 * @returns true if the repartion was success, otherwise false1582 */1583 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1584 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1585 const repartitionResult = await this.helper.executeExtrinsic(1586 signer,1587 'api.tx.unique.repartition', [collectionId, tokenId, amount],1588 true,1589 );1590 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1591 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1592 }1593}159415951596class FTGroup extends CollectionGroup {1597 /**1598 * Get collection object1599 * @param collectionId ID of collection1600 * @example getCollectionObject(2);1601 * @returns instance of UniqueFTCollection1602 */1603 getCollectionObject(collectionId: number): UniqueFTCollection {1604 return new UniqueFTCollection(collectionId, this.helper);1605 }16061607 /**1608 * Mint new fungible collection1609 * @param signer keyring of signer1610 * @param collectionOptions Collection options1611 * @param decimalPoints number of token decimals 1612 * @example1613 * mintCollection(aliceKeyring, {1614 * name: 'New',1615 * description: 'New collection',1616 * tokenPrefix: 'NEW',1617 * }, 18)1618 * @returns newly created fungible collection1619 */1620 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0): Promise<UniqueFTCollection> {1621 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1622 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1623 collectionOptions.mode = {fungible: decimalPoints};1624 for (const key of ['name', 'description', 'tokenPrefix']) {1625 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);1626 }1627 const creationResult = await this.helper.executeExtrinsic(1628 signer,1629 'api.tx.unique.createCollectionEx', [collectionOptions],1630 true,1631 );1632 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1633 }16341635 /**1636 * Mint tokens1637 * @param signer keyring of signer1638 * @param collectionId ID of collection1639 * @param owner address owner of new tokens1640 * @param amount amount of tokens to be meanted1641 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1642 * @returns ```true``` if extrinsic success, otherwise ```false``` 1643 */1644 async mintTokens(signer: TSigner, collectionId: number, owner: ICrossAccountId | string, amount: bigint): Promise<boolean> {1645 const creationResult = await this.helper.executeExtrinsic(1646 signer,1647 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1648 fungible: {1649 value: amount,1650 },1651 }],1652 true, // `Unable to mint fungible tokens for ${label}`,1653 );1654 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1655 }16561657 /**1658 * Mint multiple Fungible tokens with one owner1659 * @param signer keyring of signer1660 * @param collectionId ID of collection1661 * @param owner tokens owner1662 * @param tokens array of tokens with properties and pieces1663 * @returns ```true``` if extrinsic success, otherwise ```false``` 1664 */1665 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {value: bigint}[]): Promise<boolean> {1666 const rawTokens = [];1667 for (const token of tokens) {1668 const raw = {Fungible: {Value: token.value}};1669 rawTokens.push(raw);1670 }1671 const creationResult = await this.helper.executeExtrinsic(1672 signer,1673 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1674 true,1675 );1676 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1677 }16781679 /**1680 * Get the top 10 owners with the largest balance for the Fungible collection 1681 * @param collectionId ID of collection1682 * @example getTop10Owners(10);1683 * @returns array of ```ICrossAccountId```1684 */1685 async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1686 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1687 }16881689 /**1690 * Get account balance1691 * @param collectionId ID of collection1692 * @param addressObj address of owner1693 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1694 * @returns amount of fungible tokens owned by address1695 */1696 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1697 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1698 }16991700 /**1701 * Transfer tokens to address1702 * @param signer keyring of signer1703 * @param collectionId ID of collection1704 * @param toAddressObj address recipient1705 * @param amount amount of tokens to be sent1706 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1707 * @returns ```true``` if extrinsic success, otherwise ```false``` 1708 */1709 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1710 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1711 }17121713 /**1714 * Transfer some tokens on behalf of the owner.1715 * @param signer keyring of signer1716 * @param collectionId ID of collection1717 * @param fromAddressObj address on behalf of which tokens will be sent1718 * @param toAddressObj address where token to be sent1719 * @param amount number of tokens to be sent1720 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1721 * @returns ```true``` if extrinsic success, otherwise ```false``` 1722 */1723 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1724 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1725 }17261727 /**1728 * Destroy some amount of tokens1729 * @param signer keyring of signer1730 * @param collectionId ID of collection1731 * @param amount amount of tokens to be destroyed1732 * @example burnTokens(aliceKeyring, 10, 1000n);1733 * @returns ```true``` if extrinsic success, otherwise ```false``` 1734 */1735 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1736 return (await super.burnToken(signer, collectionId, 0, amount)).success;1737 }17381739 /**1740 * Burn some tokens on behalf of the owner.1741 * @param signer keyring of signer1742 * @param collectionId ID of collection1743 * @param fromAddressObj address on behalf of which tokens will be burnt1744 * @param amount amount of tokens to be burnt1745 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1746 * @returns ```true``` if extrinsic success, otherwise ```false``` 1747 */1748 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1749 return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, amount);1750 }17511752 /**1753 * Get total collection supply1754 * @param collectionId 1755 * @returns 1756 */1757 async getTotalPieces(collectionId: number): Promise<bigint> {1758 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1759 }17601761 /**1762 * Set, change, or remove approved address to transfer tokens.1763 * 1764 * @param signer keyring of signer1765 * @param collectionId ID of collection1766 * @param toAddressObj address to be approved1767 * @param amount amount of tokens to be approved1768 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1769 * @returns ```true``` if extrinsic success, otherwise ```false``` 1770 */1771 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1772 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1773 }17741775 /**1776 * Get amount of fungible tokens approved to transfer1777 * @param collectionId ID of collection1778 * @param fromAddressObj owner of tokens1779 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1780 * @returns number of tokens approved for the transfer1781 */1782 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1783 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1784 }1785}178617871788class ChainGroup extends HelperGroup {1789 /**1790 * Get system properties of a chain1791 * @example getChainProperties();1792 * @returns ss58Format, token decimals, and token symbol1793 */1794 getChainProperties(): IChainProperties {1795 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1796 return {1797 ss58Format: properties.ss58Format.toJSON(),1798 tokenDecimals: properties.tokenDecimals.toJSON(),1799 tokenSymbol: properties.tokenSymbol.toJSON(),1800 };1801 }18021803 /**1804 * Get chain header1805 * @example getLatestBlockNumber();1806 * @returns the number of the last block1807 */1808 async getLatestBlockNumber(): Promise<number> {1809 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1810 }18111812 /**1813 * Get block hash by block number1814 * @param blockNumber number of block1815 * @example getBlockHashByNumber(12345);1816 * @returns hash of a block1817 */1818 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1819 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1820 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1821 return blockHash;1822 }18231824 /**1825 * Get account nonce1826 * @param address substrate address1827 * @example getNonce("5GrwvaEF5zXb26Fz...");1828 * @returns number, account's nonce1829 */1830 async getNonce(address: TSubstrateAccount): Promise<number> {1831 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1832 }1833}183418351836class BalanceGroup extends HelperGroup {1837 /**1838 * Representation of the native token in the smallest unit1839 * @example getOneTokenNominal()1840 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.1841 */1842 getOneTokenNominal(): bigint {1843 const chainProperties = this.helper.chain.getChainProperties();1844 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1845 }18461847 /**1848 * Get substrate address balance1849 * @param address substrate address1850 * @example getSubstrate("5GrwvaEF5zXb26Fz...")1851 * @returns amount of tokens on address1852 */1853 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {1854 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();1855 }18561857 /**1858 * Get ethereum address balance1859 * @param address ethereum address1860 * @example getEthereum("0x9F0583DbB855d...")1861 * @returns amount of tokens on address1862 */1863 async getEthereum(address: TEthereumAccount): Promise<bigint> {1864 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();1865 }18661867 /**1868 * Transfer tokens to substrate address1869 * @param signer keyring of signer1870 * @param address substrate address of a recipient1871 * @param amount amount of tokens to be transfered1872 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);1873 * @returns ```true``` if extrinsic success, otherwise ```false```1874 */1875 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {1876 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}`*/);18771878 let transfer = {from: null, to: null, amount: 0n} as any;1879 result.result.events.forEach(({event: {data, method, section}}) => {1880 if ((section === 'balances') && (method === 'Transfer')) {1881 transfer = {1882 from: this.helper.address.normalizeSubstrate(data[0]),1883 to: this.helper.address.normalizeSubstrate(data[1]),1884 amount: BigInt(data[2]),1885 };1886 }1887 });1888 let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;1889 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;1890 isSuccess = isSuccess && BigInt(amount) === transfer.amount;1891 return isSuccess;1892 }1893}189418951896class AddressGroup extends HelperGroup {1897 /**1898 * Normalizes the address to the specified ss58 format, by default ```42```.1899 * @param address substrate address1900 * @param ss58Format format for address conversion, by default ```42```1901 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY1902 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation1903 */1904 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {1905 return this.helper.util.normalizeSubstrateAddress(address, ss58Format);1906 }19071908 /**1909 * Get address in the connected chain format1910 * @param address substrate address1911 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network1912 * @returns address in chain format1913 */1914 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {1915 const info = this.helper.chain.getChainProperties();1916 return encodeAddress(decodeAddress(address), info.ss58Format);1917 }19181919 /**1920 * Get substrate mirror of an ethereum address1921 * @param ethAddress ethereum address1922 * @param toChainFormat false for normalized account1923 * @example ethToSubstrate('0x9F0583DbB855d...')1924 * @returns substrate mirror of a provided ethereum address1925 */1926 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {1927 if(!toChainFormat) return evmToAddress(ethAddress);1928 const info = this.helper.chain.getChainProperties();1929 return evmToAddress(ethAddress, info.ss58Format);1930 }19311932 /**1933 * Get ethereum mirror of a substrate address1934 * @param subAddress substrate account1935 * @example substrateToEth("5DnSF6RRjwteE3BrC...")1936 * @returns ethereum mirror of a provided substrate address1937 */1938 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {1939 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));1940 }1941}194219431944export class UniqueHelper extends ChainHelperBase {1945 chain: ChainGroup;1946 balance: BalanceGroup;1947 address: AddressGroup;1948 collection: CollectionGroup;1949 nft: NFTGroup;1950 rft: RFTGroup;1951 ft: FTGroup;19521953 constructor(logger?: ILogger) {1954 super(logger);1955 this.chain = new ChainGroup(this);1956 this.balance = new BalanceGroup(this);1957 this.address = new AddressGroup(this);1958 this.collection = new CollectionGroup(this);1959 this.nft = new NFTGroup(this);1960 this.rft = new RFTGroup(this);1961 this.ft = new FTGroup(this);1962 } 1963}196419651966class UniqueCollectionBase {1967 helper: UniqueHelper;1968 collectionId: number;19691970 constructor(collectionId: number, uniqueHelper: UniqueHelper) {1971 this.collectionId = collectionId;1972 this.helper = uniqueHelper;1973 }19741975 async getData() {1976 return await this.helper.collection.getData(this.collectionId);1977 }19781979 async getLastTokenId() {1980 return await this.helper.collection.getLastTokenId(this.collectionId);1981 }19821983 async isTokenExists(tokenId: number) {1984 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);1985 }19861987 async getAdmins() {1988 return await this.helper.collection.getAdmins(this.collectionId);1989 }19901991 async getAllowList() {1992 return await this.helper.collection.getAllowList(this.collectionId);1993 }19941995 async getEffectiveLimits() {1996 return await this.helper.collection.getEffectiveLimits(this.collectionId);1997 }19981999 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2000 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2001 }20022003 async confirmSponsorship(signer: TSigner) {2004 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2005 }20062007 async setLimits(signer: TSigner, limits: ICollectionLimits) {2008 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2009 }20102011 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2012 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2013 }20142015 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2016 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2017 }20182019 async enableAllowList(signer: TSigner, value = true/*: 'Normal' | 'AllowList' = 'AllowList'*/) {2020 return await this.setPermissions(signer, value ? {access: 'AllowList', mintMode: true} : {access: 'Normal'});2021 }20222023 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2024 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2025 }20262027 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2028 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2029 }20302031 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2032 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2033 }20342035 async setProperties(signer: TSigner, properties: IProperty[]) {2036 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2037 }20382039 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2040 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2041 }20422043 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2044 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2045 }20462047 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2048 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2049 }20502051 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2052 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2053 }20542055 async disableNesting(signer: TSigner) {2056 return await this.helper.collection.disableNesting(signer, this.collectionId);2057 }20582059 async burn(signer: TSigner) {2060 return await this.helper.collection.burn(signer, this.collectionId);2061 }2062}206320642065class UniqueNFTCollection extends UniqueCollectionBase {2066 getTokenObject(tokenId: number) {2067 return new UniqueNFTToken(tokenId, this);2068 }20692070 async getTokensByAddress(addressObj: ICrossAccountId) {2071 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2072 }20732074 async getToken(tokenId: number, blockHashAt?: string) {2075 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2076 }20772078 async getTokenOwner(tokenId: number, blockHashAt?: string) {2079 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2080 }20812082 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2083 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2084 }20852086 async getTokenChildren(tokenId: number, blockHashAt?: string) {2087 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2088 }20892090 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2091 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2092 }20932094 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2095 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2096 }20972098 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2099 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2100 }21012102 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2103 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2104 }21052106 async mintToken(signer: TSigner, owner: ICrossAccountId, properties?: IProperty[]) {2107 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2108 }21092110 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2111 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2112 }21132114 async burnToken(signer: TSigner, tokenId: number) {2115 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2116 }21172118 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2119 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2120 }21212122 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2123 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2124 }21252126 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2127 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2128 }21292130 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2131 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2132 }21332134 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2135 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2136 }2137}213821392140class UniqueRFTCollection extends UniqueCollectionBase {2141 getTokenObject(tokenId: number) {2142 return new UniqueRFTToken(tokenId, this);2143 }21442145 async getTokensByAddress(addressObj: ICrossAccountId) {2146 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2147 }21482149 async getTop10TokenOwners(tokenId: number) {2150 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2151 }21522153 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2154 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2155 }21562157 async getTokenTotalPieces(tokenId: number) {2158 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2159 }21602161 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2162 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2163 }21642165 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2166 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2167 }21682169 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2170 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2171 }21722173 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2174 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2175 }21762177 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2178 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2179 }21802181 async mintToken(signer: TSigner, owner: ICrossAccountId, pieces=100n, properties?: IProperty[]) {2182 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2183 }21842185 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]) {2186 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2187 }21882189 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2190 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2191 }21922193 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2194 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2195 }21962197 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2198 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2199 }22002201 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2202 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2203 }2204}220522062207class UniqueFTCollection extends UniqueCollectionBase {2208 async mint(signer: TSigner, owner: ICrossAccountId, amount: bigint) {2209 return await this.helper.ft.mintTokens(signer, this.collectionId, owner, amount);2210 }22112212 async mintWithOneOwner(signer: TSigner, owner: ICrossAccountId, tokens: {value: bigint}[]) {2213 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, owner, tokens);2214 }22152216 async getBalance(addressObj: ICrossAccountId) {2217 return await this.helper.ft.getBalance(this.collectionId, addressObj);2218 }22192220 async getTop10Owners() {2221 return await this.helper.ft.getTop10Owners(this.collectionId);2222 }22232224 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2225 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2226 }22272228 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2229 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2230 }22312232 async burnTokens(signer: TSigner, amount=1n) {2233 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2234 }22352236 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2237 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2238 }22392240 async getTotalPieces() {2241 return await this.helper.ft.getTotalPieces(this.collectionId);2242 }22432244 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2245 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2246 }22472248 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2249 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2250 }2251}225222532254class UniqueTokenBase implements IToken {2255 collection: UniqueNFTCollection | UniqueRFTCollection;2256 collectionId: number;2257 tokenId: number;22582259 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2260 this.collection = collection;2261 this.collectionId = collection.collectionId;2262 this.tokenId = tokenId;2263 }22642265 async getNextSponsored(addressObj: ICrossAccountId) {2266 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2267 }22682269 async setProperties(signer: TSigner, properties: IProperty[]) {2270 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2271 }22722273 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2274 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2275 }2276}227722782279class UniqueNFTToken extends UniqueTokenBase {2280 collection: UniqueNFTCollection;22812282 constructor(tokenId: number, collection: UniqueNFTCollection) {2283 super(tokenId, collection);2284 this.collection = collection;2285 }22862287 async getData(blockHashAt?: string) {2288 return await this.collection.getToken(this.tokenId, blockHashAt);2289 }22902291 async getOwner(blockHashAt?: string) {2292 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2293 }22942295 async getTopmostOwner(blockHashAt?: string) {2296 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2297 }22982299 async getChildren(blockHashAt?: string) {2300 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2301 }23022303 async nest(signer: TSigner, toTokenObj: IToken) {2304 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2305 }23062307 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2308 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2309 }23102311 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2312 return await this.collection.transferToken(signer, this.tokenId, addressObj);2313 }23142315 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2316 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2317 }23182319 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2320 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2321 }23222323 async isApproved(toAddressObj: ICrossAccountId) {2324 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2325 }23262327 async burn(signer: TSigner) {2328 return await this.collection.burnToken(signer, this.tokenId);2329 }2330}23312332class UniqueRFTToken extends UniqueTokenBase {2333 collection: UniqueRFTCollection;23342335 constructor(tokenId: number, collection: UniqueRFTCollection) {2336 super(tokenId, collection);2337 this.collection = collection;2338 }23392340 async getTop10Owners() {2341 return await this.collection.getTop10TokenOwners(this.tokenId);2342 }23432344 async getBalance(addressObj: ICrossAccountId) {2345 return await this.collection.getTokenBalance(this.tokenId, addressObj);2346 }23472348 async getTotalPieces() {2349 return await this.collection.getTokenTotalPieces(this.tokenId);2350 }23512352 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2353 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2354 }23552356 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2357 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2358 }23592360 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2361 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2362 }23632364 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2365 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2366 }23672368 async repartition(signer: TSigner, amount: bigint) {2369 return await this.collection.repartitionToken(signer, this.tokenId, amount);2370 }23712372 async burn(signer: TSigner, amount=1n) {2373 return await this.collection.burnToken(signer, this.tokenId, amount);2374 }2375}