difftreelog
feat add nested ops - scheduled and sudo
in: master
5 files changed
tests/src/eth/util/playgrounds/index.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/index.ts
+++ b/tests/src/eth/util/playgrounds/index.ts
@@ -39,7 +39,6 @@
}
finally {
await helper.disconnect();
- await helper.disconnectWeb3();
silentConsole.disable();
}
};
tests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -321,6 +321,7 @@
}
}
+export type EthUniqueHelperConstructor = new (...args: any[]) => EthUniqueHelper;
export class EthUniqueHelper extends DevUniqueHelper {
web3: Web3 | null = null;
@@ -331,8 +332,10 @@
ethNativeContract: NativeContractGroup;
ethContract: ContractGroup;
- constructor(logger: { log: (msg: any, level: any) => void, level: any }) {
- super(logger);
+ constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {
+ options.helperBase = options.helperBase ?? EthUniqueHelper;
+
+ super(logger, options);
this.eth = new EthGroup(this);
this.ethAddress = new EthAddressGroup(this);
this.ethNativeContract = new NativeContractGroup(this);
@@ -350,10 +353,23 @@
this.web3 = new Web3(this.web3Provider);
}
- async disconnectWeb3() {
+ async disconnect() {
if(this.web3 === null) return;
this.web3Provider?.connection.close();
+
+ await super.disconnect();
+ }
+
+ clearApi() {
this.web3 = null;
}
+
+ clone(helperCls: EthUniqueHelperConstructor, options?: { [key: string]: any; }): EthUniqueHelper {
+ const newHelper = super.clone(helperCls, options) as EthUniqueHelper;
+ newHelper.web3 = this.web3;
+ newHelper.web3Provider = this.web3Provider;
+
+ return newHelper;
+ }
}
\ No newline at end of file
tests/src/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -164,6 +164,14 @@
amount: bigint,
}
+export interface ISchedulerOptions {
+ priority?: number,
+ periodic?: {
+ period: number,
+ repetitions: number,
+ },
+}
+
export type TSubstrateAccount = string;
export type TEthereumAccount = string;
export type TApiAllowedListeners = 'connected' | 'disconnected' | 'error' | 'ready' | 'decorated';
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -7,6 +7,9 @@
import * as defs from '../../interfaces/definitions';
import {IKeyringPair} from '@polkadot/types/types';
import {ICrossAccountId} from './types';
+import type {EventRecord} from '@polkadot/types/interfaces';
+import {VoidFn} from '@polkadot/api/types';
+import {FrameSystemEventRecord} from '@polkadot/types/lookup';
export class SilentLogger {
@@ -63,8 +66,10 @@
wait: WaitGroup;
admin: AdminGroup;
- constructor(logger: { log: (msg: any, level: any) => void, level: any }) {
- super(logger);
+ constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {
+ options.helperBase = options.helperBase ?? DevUniqueHelper;
+
+ super(logger, options);
this.arrange = new ArrangeGroup(this);
this.wait = new WaitGroup(this);
this.admin = new AdminGroup(this);
@@ -108,9 +113,9 @@
}
class ArrangeGroup {
- helper: UniqueHelper;
+ helper: DevUniqueHelper;
- constructor(helper: UniqueHelper) {
+ constructor(helper: DevUniqueHelper) {
this.helper = helper;
}
@@ -245,14 +250,14 @@
}
class WaitGroup {
- helper: UniqueHelper;
+ helper: DevUniqueHelper;
- constructor(helper: UniqueHelper) {
+ constructor(helper: DevUniqueHelper) {
this.helper = helper;
}
/**
- * Wait for specified bnumber of blocks
+ * Wait for specified number of blocks
* @param blocksCount number of blocks to wait
* @returns
*/
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, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314export class CrossAccountId implements ICrossAccountId {15 Substrate?: TSubstrateAccount;16 Ethereum?: TEthereumAccount;1718 constructor(account: ICrossAccountId) {19 if (account.Substrate) this.Substrate = account.Substrate;20 if (account.Ethereum) this.Ethereum = account.Ethereum;21 }2223 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {24 switch (domain) {25 case 'Substrate': return new CrossAccountId({Substrate: account.address});26 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();27 }28 }2930 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {31 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});32 }3334 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {35 return encodeAddress(decodeAddress(address), ss58Format);36 }3738 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {39 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});40 }41 42 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {43 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);44 return this;45 }4647 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {48 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));49 }5051 toEthereum(): CrossAccountId {52 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});53 return this;54 }5556 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {57 return evmToAddress(address, ss58Format);58 }5960 toSubstrate(ss58Format?: number): CrossAccountId {61 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});62 return this;63 }64 65 toLowerCase(): CrossAccountId {66 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();67 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();68 return this;69 }70}7172const nesting = {73 toChecksumAddress(address: string): string {74 if (typeof address === 'undefined') return '';7576 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);7778 address = address.toLowerCase().replace(/^0x/i,'');79 const addressHash = keccakAsHex(address).replace(/^0x/i,'');80 const checksumAddress = ['0x'];8182 for (let i = 0; i < address.length; i++) {83 // If ith character is 8 to f then make it uppercase84 if (parseInt(addressHash[i], 16) > 7) {85 checksumAddress.push(address[i].toUpperCase());86 } else {87 checksumAddress.push(address[i]);88 }89 }90 return checksumAddress.join('');91 },92 tokenIdToAddress(collectionId: number, tokenId: number) {93 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);94 },95};9697class UniqueUtil {98 static transactionStatus = {99 NOT_READY: 'NotReady',100 FAIL: 'Fail',101 SUCCESS: 'Success',102 };103104 static chainLogType = {105 EXTRINSIC: 'extrinsic',106 RPC: 'rpc',107 };108109 static getTokenAccount(token: IToken): CrossAccountId {110 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});111 }112113 static getTokenAddress(token: IToken): string {114 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);115 }116117 static getDefaultLogger(): ILogger {118 return {119 log(msg: any, level = 'INFO') {120 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));121 },122 level: {123 ERROR: 'ERROR',124 WARNING: 'WARNING',125 INFO: 'INFO',126 },127 };128 }129130 static vec2str(arr: string[] | number[]) {131 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');132 }133134 static str2vec(string: string) {135 if (typeof string !== 'string') return string;136 return Array.from(string).map(x => x.charCodeAt(0));137 }138139 static fromSeed(seed: string, ss58Format = 42) {140 const keyring = new Keyring({type: 'sr25519', ss58Format});141 return keyring.addFromUri(seed);142 }143144 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {145 if (creationResult.status !== this.transactionStatus.SUCCESS) {146 throw Error('Unable to create collection!');147 }148149 let collectionId = null;150 creationResult.result.events.forEach(({event: {data, method, section}}) => {151 if ((section === 'common') && (method === 'CollectionCreated')) {152 collectionId = parseInt(data[0].toString(), 10);153 }154 });155156 if (collectionId === null) {157 throw Error('No CollectionCreated event was found!');158 }159160 return collectionId;161 }162163 static extractTokensFromCreationResult(creationResult: ITransactionResult): {164 success: boolean, 165 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],166 } {167 if (creationResult.status !== this.transactionStatus.SUCCESS) {168 throw Error('Unable to create tokens!');169 }170 let success = false;171 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];172 creationResult.result.events.forEach(({event: {data, method, section}}) => {173 if (method === 'ExtrinsicSuccess') {174 success = true;175 } else if ((section === 'common') && (method === 'ItemCreated')) {176 tokens.push({177 collectionId: parseInt(data[0].toString(), 10),178 tokenId: parseInt(data[1].toString(), 10),179 owner: data[2].toHuman(),180 amount: data[3].toBigInt(),181 });182 }183 });184 return {success, tokens};185 }186187 static extractTokensFromBurnResult(burnResult: ITransactionResult): {188 success: boolean, 189 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],190 } {191 if (burnResult.status !== this.transactionStatus.SUCCESS) {192 throw Error('Unable to burn tokens!');193 }194 let success = false;195 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];196 burnResult.result.events.forEach(({event: {data, method, section}}) => {197 if (method === 'ExtrinsicSuccess') {198 success = true;199 } else if ((section === 'common') && (method === 'ItemDestroyed')) {200 tokens.push({201 collectionId: parseInt(data[0].toString(), 10),202 tokenId: parseInt(data[1].toString(), 10),203 owner: data[2].toHuman(),204 amount: data[3].toBigInt(),205 });206 }207 });208 return {success, tokens};209 }210211 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {212 let eventId = null;213 events.forEach(({event: {data, method, section}}) => {214 if ((section === expectedSection) && (method === expectedMethod)) {215 eventId = parseInt(data[0].toString(), 10);216 }217 });218219 if (eventId === null) {220 throw Error(`No ${expectedMethod} event was found!`);221 }222 return eventId === collectionId;223 }224225 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {226 const normalizeAddress = (address: string | ICrossAccountId) => {227 if(typeof address === 'string') return address;228 const obj = {} as any;229 Object.keys(address).forEach(k => {230 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];231 });232 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);233 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();234 return address;235 };236 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;237 events.forEach(({event: {data, method, section}}) => {238 if ((section === 'common') && (method === 'Transfer')) {239 const hData = (data as any).toJSON();240 transfer = {241 collectionId: hData[0],242 tokenId: hData[1],243 from: normalizeAddress(hData[2]),244 to: normalizeAddress(hData[3]),245 amount: BigInt(hData[4]),246 };247 }248 });249 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;250 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);251 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);252 isSuccess = isSuccess && amount === transfer.amount;253 return isSuccess;254 }255}256257class UniqueEventHelper {258 private static extractIndex(index: any): [number, number] | string {259 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];260 return index.toJSON();261 }262263 private static extractSub(data: any, subTypes: any): {[key: string]: any} {264 let obj: any = {};265 let index = 0;266267 if (data.entries) {268 for(const [key, value] of data.entries()) {269 obj[key] = this.extractData(value, subTypes[index]);270 index++;271 }272 } else obj = data.toJSON();273274 return obj;275 }276 277 private static extractData(data: any, type: any): any {278 if(!type) return data.toHuman();279 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();280 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();281 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);282 return data.toHuman();283 }284285 public static extractEvents(records: ITransactionResult): IEvent[] {286 const parsedEvents: IEvent[] = [];287288 records.result.events.forEach((record) => {289 const {event, phase} = record;290 const types = (event as any).typeDef;291292 const eventData: IEvent = {293 section: event.section.toString(),294 method: event.method.toString(),295 index: this.extractIndex(event.index),296 data: [],297 phase: phase.toJSON(),298 };299300 event.data.forEach((val: any, index: number) => {301 eventData.data.push(this.extractData(val, types[index]));302 });303304 parsedEvents.push(eventData);305 });306307 return parsedEvents;308 }309}310311class ChainHelperBase {312 transactionStatus = UniqueUtil.transactionStatus;313 chainLogType = UniqueUtil.chainLogType;314 util: typeof UniqueUtil;315 eventHelper: typeof UniqueEventHelper;316 logger: ILogger;317 api: ApiPromise | null;318 forcedNetwork: TUniqueNetworks | null;319 network: TUniqueNetworks | null;320 chainLog: IUniqueHelperLog[];321322 constructor(logger?: ILogger) {323 this.util = UniqueUtil;324 this.eventHelper = UniqueEventHelper;325 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();326 this.logger = logger;327 this.api = null;328 this.forcedNetwork = null;329 this.network = null;330 this.chainLog = [];331 }332333 getApi(): ApiPromise {334 if(this.api === null) throw Error('API not initialized');335 return this.api;336 }337338 clearChainLog(): void {339 this.chainLog = [];340 }341342 forceNetwork(value: TUniqueNetworks): void {343 this.forcedNetwork = value;344 }345346 async connect(wsEndpoint: string, listeners?: IApiListeners) {347 if (this.api !== null) throw Error('Already connected');348 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);349 this.api = api;350 this.network = network;351 }352353 async disconnect() {354 if (this.api === null) return;355 await this.api.disconnect();356 this.api = null;357 this.network = null;358 }359360 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {361 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;362 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;363 return 'opal';364 }365366 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {367 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});368 await api.isReady;369370 const network = await this.detectNetwork(api);371372 await api.disconnect();373374 return network;375 }376377 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{378 api: ApiPromise;379 network: TUniqueNetworks;380 }> {381 if(typeof network === 'undefined' || network === null) network = 'opal';382 const supportedRPC = {383 opal: {384 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,385 },386 quartz: {387 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,388 },389 unique: {390 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,391 },392 };393 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);394 const rpc = supportedRPC[network];395396 // TODO: investigate how to replace rpc in runtime397 // api._rpcCore.addUserInterfaces(rpc);398399 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});400401 await api.isReadyOrError;402403 if (typeof listeners === 'undefined') listeners = {};404 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {405 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;406 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);407 }408409 return {api, network};410 }411412 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {413 const {events, status} = data;414 if (status.isReady) {415 return this.transactionStatus.NOT_READY;416 }417 if (status.isBroadcast) {418 return this.transactionStatus.NOT_READY;419 }420 if (status.isInBlock || status.isFinalized) {421 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');422 if (errors.length > 0) {423 return this.transactionStatus.FAIL;424 }425 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {426 return this.transactionStatus.SUCCESS;427 }428 }429430 return this.transactionStatus.FAIL;431 }432433 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {434 const sign = (callback: any) => {435 if(options !== null) return transaction.signAndSend(sender, options, callback);436 return transaction.signAndSend(sender, callback);437 };438 // eslint-disable-next-line no-async-promise-executor439 return new Promise(async (resolve, reject) => {440 try {441 const unsub = await sign((result: any) => {442 const status = this.getTransactionStatus(result);443444 if (status === this.transactionStatus.SUCCESS) {445 this.logger.log(`${label} successful`);446 unsub();447 resolve({result, status});448 } else if (status === this.transactionStatus.FAIL) {449 let moduleError = null;450451 if (result.hasOwnProperty('dispatchError')) {452 const dispatchError = result['dispatchError'];453454 if (dispatchError) {455 if (dispatchError.isModule) {456 const modErr = dispatchError.asModule;457 const errorMeta = dispatchError.registry.findMetaError(modErr);458459 moduleError = `${errorMeta.section}.${errorMeta.name}`;460 } else {461 moduleError = dispatchError.toHuman();462 }463 } else {464 this.logger.log(result, this.logger.level.ERROR);465 }466 }467468 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);469 unsub();470 reject({status, moduleError, result});471 }472 });473 } catch (e) {474 this.logger.log(e, this.logger.level.ERROR);475 reject(e);476 }477 });478 }479480 constructApiCall(apiCall: string, params: any[]) {481 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);482 let call = this.api as any;483 for(const part of apiCall.slice(4).split('.')) {484 call = call[part];485 }486 return call(...params);487 }488489 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {490 if(this.api === null) throw Error('API not initialized');491 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);492493 const startTime = (new Date()).getTime();494 let result: ITransactionResult;495 let events: IEvent[] = [];496 try {497 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;498 events = this.eventHelper.extractEvents(result);499 }500 catch(e) {501 if(!(e as object).hasOwnProperty('status')) throw e;502 result = e as ITransactionResult;503 }504505 const endTime = (new Date()).getTime();506507 const log = {508 executedAt: endTime,509 executionTime: endTime - startTime,510 type: this.chainLogType.EXTRINSIC,511 status: result.status,512 call: extrinsic,513 signer: this.getSignerAddress(sender),514 params,515 } as IUniqueHelperLog;516517 if(result.status !== this.transactionStatus.SUCCESS) {518 if (result.moduleError) log.moduleError = result.moduleError;519 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;520 }521 if(events.length > 0) log.events = events;522523 this.chainLog.push(log);524525 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {526 if (result.moduleError) throw Error(`${result.moduleError}`);527 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));528 }529 return result;530 }531532 async callRpc(rpc: string, params?: any[]) {533 if(typeof params === 'undefined') params = [];534 if(this.api === null) throw Error('API not initialized');535 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);536537 const startTime = (new Date()).getTime();538 let result;539 let error = null;540 const log = {541 type: this.chainLogType.RPC,542 call: rpc,543 params,544 } as IUniqueHelperLog;545546 try {547 result = await this.constructApiCall(rpc, params);548 }549 catch(e) {550 error = e;551 }552553 const endTime = (new Date()).getTime();554555 log.executedAt = endTime;556 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';557 log.executionTime = endTime - startTime;558559 this.chainLog.push(log);560561 if(error !== null) throw error;562563 return result;564 }565566 getSignerAddress(signer: IKeyringPair | string): string {567 if(typeof signer === 'string') return signer;568 return signer.address;569 }570571 fetchAllPalletNames(): string[] {572 if(this.api === null) throw Error('API not initialized');573 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());574 }575576 fetchMissingPalletNames(requiredPallets: string[]): string[] {577 const palletNames = this.fetchAllPalletNames();578 return requiredPallets.filter(p => !palletNames.includes(p));579 }580}581582583class HelperGroup {584 helper: UniqueHelper;585586 constructor(uniqueHelper: UniqueHelper) {587 this.helper = uniqueHelper;588 }589}590591592class CollectionGroup extends HelperGroup {593 /**594 * Get number of blocks when sponsored transaction is available.595 *596 * @param collectionId ID of collection597 * @param tokenId ID of token598 * @param addressObj address for which the sponsorship is checked599 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});600 * @returns number of blocks or null if sponsorship hasn't been set601 */602 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {603 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();604 }605606 /**607 * Get the number of created collections.608 *609 * @returns number of created collections610 */611 async getTotalCount(): Promise<number> {612 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();613 }614615 /**616 * Get information about the collection with additional data,617 * including the number of tokens it contains, its administrators,618 * the normalized address of the collection's owner, and decoded name and description.619 *620 * @param collectionId ID of collection621 * @example await getData(2)622 * @returns collection information object623 */624 async getData(collectionId: number): Promise<{625 id: number;626 name: string;627 description: string;628 tokensCount: number;629 admins: CrossAccountId[];630 normalizedOwner: TSubstrateAccount;631 raw: any632 } | null> {633 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);634 const humanCollection = collection.toHuman(), collectionData = {635 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],636 raw: humanCollection,637 } as any, jsonCollection = collection.toJSON();638 if (humanCollection === null) return null;639 collectionData.raw.limits = jsonCollection.limits;640 collectionData.raw.permissions = jsonCollection.permissions;641 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);642 for (const key of ['name', 'description']) {643 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);644 }645646 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))647 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)648 : 0;649 collectionData.admins = await this.getAdmins(collectionId);650651 return collectionData;652 }653654 /**655 * Get the addresses of the collection's administrators, optionally normalized.656 *657 * @param collectionId ID of collection658 * @param normalize whether to normalize the addresses to the default ss58 format659 * @example await getAdmins(1)660 * @returns array of administrators661 */662 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {663 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();664665 return normalize666 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())667 : admins;668 }669670 /**671 * Get the addresses added to the collection allow-list, optionally normalized.672 * @param collectionId ID of collection673 * @param normalize whether to normalize the addresses to the default ss58 format674 * @example await getAllowList(1)675 * @returns array of allow-listed addresses676 */677 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {678 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();679 return normalize680 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())681 : allowListed;682 }683684 /**685 * Get the effective limits of the collection instead of null for default values686 *687 * @param collectionId ID of collection688 * @example await getEffectiveLimits(2)689 * @returns object of collection limits690 */691 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {692 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();693 }694695 /**696 * Burns the collection if the signer has sufficient permissions and collection is empty.697 *698 * @param signer keyring of signer699 * @param collectionId ID of collection700 * @example await helper.collection.burn(aliceKeyring, 3);701 * @returns ```true``` if extrinsic success, otherwise ```false```702 */703 async burn(signer: TSigner, collectionId: number): Promise<boolean> {704 const result = await this.helper.executeExtrinsic(705 signer,706 'api.tx.unique.destroyCollection', [collectionId],707 true,708 );709710 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');711 }712713 /**714 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.715 *716 * @param signer keyring of signer717 * @param collectionId ID of collection718 * @param sponsorAddress Sponsor substrate address719 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")720 * @returns ```true``` if extrinsic success, otherwise ```false```721 */722 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {723 const result = await this.helper.executeExtrinsic(724 signer,725 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],726 true,727 );728729 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');730 }731732 /**733 * Confirms consent to sponsor the collection on behalf of the signer.734 *735 * @param signer keyring of signer736 * @param collectionId ID of collection737 * @example confirmSponsorship(aliceKeyring, 10)738 * @returns ```true``` if extrinsic success, otherwise ```false```739 */740 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {741 const result = await this.helper.executeExtrinsic(742 signer,743 'api.tx.unique.confirmSponsorship', [collectionId],744 true,745 );746747 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');748 }749750 /**751 * Removes the sponsor of a collection, regardless if it consented or not.752 *753 * @param signer keyring of signer754 * @param collectionId ID of collection755 * @example removeSponsor(aliceKeyring, 10)756 * @returns ```true``` if extrinsic success, otherwise ```false```757 */758 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {759 const result = await this.helper.executeExtrinsic(760 signer,761 'api.tx.unique.removeCollectionSponsor', [collectionId],762 true,763 );764765 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');766 }767768 /**769 * Sets the limits of the collection. At least one limit must be specified for a correct call.770 *771 * @param signer keyring of signer772 * @param collectionId ID of collection773 * @param limits collection limits object774 * @example775 * await setLimits(776 * aliceKeyring,777 * 10,778 * {779 * sponsorTransferTimeout: 0,780 * ownerCanDestroy: false781 * }782 * )783 * @returns ```true``` if extrinsic success, otherwise ```false```784 */785 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {786 const result = await this.helper.executeExtrinsic(787 signer,788 'api.tx.unique.setCollectionLimits', [collectionId, limits],789 true,790 );791792 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');793 }794795 /**796 * Changes the owner of the collection to the new Substrate address.797 *798 * @param signer keyring of signer799 * @param collectionId ID of collection800 * @param ownerAddress substrate address of new owner801 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")802 * @returns ```true``` if extrinsic success, otherwise ```false```803 */804 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {805 const result = await this.helper.executeExtrinsic(806 signer,807 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],808 true,809 );810811 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');812 }813814 /**815 * Adds a collection administrator.816 *817 * @param signer keyring of signer818 * @param collectionId ID of collection819 * @param adminAddressObj Administrator address (substrate or ethereum)820 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})821 * @returns ```true``` if extrinsic success, otherwise ```false```822 */823 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {824 const result = await this.helper.executeExtrinsic(825 signer,826 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],827 true,828 );829830 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');831 }832833 /**834 * Removes a collection administrator.835 *836 * @param signer keyring of signer837 * @param collectionId ID of collection838 * @param adminAddressObj Administrator address (substrate or ethereum)839 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})840 * @returns ```true``` if extrinsic success, otherwise ```false```841 */842 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {843 const result = await this.helper.executeExtrinsic(844 signer,845 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],846 true,847 );848849 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');850 }851852 /**853 * Check if user is in allow list.854 * 855 * @param collectionId ID of collection856 * @param user Account to check857 * @example await getAdmins(1)858 * @returns is user in allow list859 */860 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {861 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();862 }863864 /**865 * Adds an address to allow list866 * @param signer keyring of signer867 * @param collectionId ID of collection868 * @param addressObj address to add to the allow list869 * @returns ```true``` if extrinsic success, otherwise ```false```870 */871 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {872 const result = await this.helper.executeExtrinsic(873 signer,874 'api.tx.unique.addToAllowList', [collectionId, addressObj],875 true,876 );877878 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');879 }880881 /**882 * Removes an address from allow list883 *884 * @param signer keyring of signer885 * @param collectionId ID of collection886 * @param addressObj address to remove from the allow list887 * @returns ```true``` if extrinsic success, otherwise ```false```888 */889 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {890 const result = await this.helper.executeExtrinsic(891 signer,892 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],893 true,894 );895896 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');897 }898899 /**900 * Sets onchain permissions for selected collection.901 *902 * @param signer keyring of signer903 * @param collectionId ID of collection904 * @param permissions collection permissions object905 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});906 * @returns ```true``` if extrinsic success, otherwise ```false```907 */908 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {909 const result = await this.helper.executeExtrinsic(910 signer,911 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],912 true,913 );914915 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');916 }917918 /**919 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.920 *921 * @param signer keyring of signer922 * @param collectionId ID of collection923 * @param permissions nesting permissions object924 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});925 * @returns ```true``` if extrinsic success, otherwise ```false```926 */927 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {928 return await this.setPermissions(signer, collectionId, {nesting: permissions});929 }930931 /**932 * Disables nesting for selected collection.933 *934 * @param signer keyring of signer935 * @param collectionId ID of collection936 * @example disableNesting(aliceKeyring, 10);937 * @returns ```true``` if extrinsic success, otherwise ```false```938 */939 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {940 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});941 }942943 /**944 * Sets onchain properties to the collection.945 *946 * @param signer keyring of signer947 * @param collectionId ID of collection948 * @param properties array of property objects949 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);950 * @returns ```true``` if extrinsic success, otherwise ```false```951 */952 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {953 const result = await this.helper.executeExtrinsic(954 signer,955 'api.tx.unique.setCollectionProperties', [collectionId, properties],956 true,957 );958959 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');960 }961962 /**963 * Get collection properties.964 * 965 * @param collectionId ID of collection966 * @param propertyKeys optionally filter the returned properties to only these keys967 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);968 * @returns array of key-value pairs969 */970 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {971 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();972 }973974 /**975 * Deletes onchain properties from the collection.976 *977 * @param signer keyring of signer978 * @param collectionId ID of collection979 * @param propertyKeys array of property keys to delete980 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);981 * @returns ```true``` if extrinsic success, otherwise ```false```982 */983 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {984 const result = await this.helper.executeExtrinsic(985 signer,986 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],987 true,988 );989990 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');991 }992993 /**994 * Changes the owner of the token.995 *996 * @param signer keyring of signer997 * @param collectionId ID of collection998 * @param tokenId ID of token999 * @param addressObj address of a new owner1000 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1001 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1002 * @returns true if the token success, otherwise false1003 */1004 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1005 const result = await this.helper.executeExtrinsic(1006 signer,1007 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1008 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1009 );10101011 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1012 }10131014 /**1015 *1016 * Change ownership of a token(s) on behalf of the owner.1017 *1018 * @param signer keyring of signer1019 * @param collectionId ID of collection1020 * @param tokenId ID of token1021 * @param fromAddressObj address on behalf of which the token will be sent1022 * @param toAddressObj new token owner1023 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1024 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1025 * @returns true if the token success, otherwise false1026 */1027 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1028 const result = await this.helper.executeExtrinsic(1029 signer,1030 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1031 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1032 );1033 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1034 }10351036 /**1037 *1038 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1039 *1040 * @param signer keyring of signer1041 * @param collectionId ID of collection1042 * @param tokenId ID of token1043 * @param amount amount of tokens to be burned. For NFT must be set to 1n1044 * @example burnToken(aliceKeyring, 10, 5);1045 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1046 */1047 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1048 const burnResult = await this.helper.executeExtrinsic(1049 signer,1050 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1051 true, // `Unable to burn token for ${label}`,1052 );1053 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1054 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1055 return burnedTokens.success;1056 }10571058 /**1059 * Destroys a concrete instance of NFT on behalf of the owner1060 *1061 * @param signer keyring of signer1062 * @param collectionId ID of collection1063 * @param tokenId ID of token1064 * @param fromAddressObj address on behalf of which the token will be burnt1065 * @param amount amount of tokens to be burned. For NFT must be set to 1n1066 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1067 * @returns ```true``` if extrinsic success, otherwise ```false```1068 */1069 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1070 const burnResult = await this.helper.executeExtrinsic(1071 signer,1072 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1073 true, // `Unable to burn token from for ${label}`,1074 );1075 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1076 return burnedTokens.success && burnedTokens.tokens.length > 0;1077 }10781079 /**1080 * Set, change, or remove approved address to transfer the ownership of the NFT.1081 *1082 * @param signer keyring of signer1083 * @param collectionId ID of collection1084 * @param tokenId ID of token1085 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1086 * @param amount amount of token to be approved. For NFT must be set to 1n1087 * @returns ```true``` if extrinsic success, otherwise ```false```1088 */1089 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1090 const approveResult = await this.helper.executeExtrinsic(1091 signer,1092 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1093 true, // `Unable to approve token for ${label}`,1094 );10951096 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1097 }10981099 /**1100 * Get the amount of token pieces approved to transfer or burn. Normally 0.1101 *1102 * @param collectionId ID of collection1103 * @param tokenId ID of token1104 * @param toAccountObj address which is approved to use token pieces1105 * @param fromAccountObj address which may have allowed the use of its owned tokens1106 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1107 * @returns number of approved to transfer pieces1108 */1109 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1110 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1111 }11121113 /**1114 * Get the last created token ID in a collection1115 *1116 * @param collectionId ID of collection1117 * @example getLastTokenId(10);1118 * @returns id of the last created token1119 */1120 async getLastTokenId(collectionId: number): Promise<number> {1121 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1122 }11231124 /**1125 * Check if token exists1126 *1127 * @param collectionId ID of collection1128 * @param tokenId ID of token1129 * @example doesTokenExist(10, 20);1130 * @returns true if the token exists, otherwise false1131 */1132 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1133 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1134 }1135}11361137class NFTnRFT extends CollectionGroup {1138 /**1139 * Get tokens owned by account1140 *1141 * @param collectionId ID of collection1142 * @param addressObj tokens owner1143 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1144 * @returns array of token ids owned by account1145 */1146 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1147 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1148 }11491150 /**1151 * Get token data1152 *1153 * @param collectionId ID of collection1154 * @param tokenId ID of token1155 * @param propertyKeys optionally filter the token properties to only these keys1156 * @param blockHashAt optionally query the data at some block with this hash1157 * @example getToken(10, 5);1158 * @returns human readable token data1159 */1160 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1161 properties: IProperty[];1162 owner: CrossAccountId;1163 normalizedOwner: CrossAccountId;1164 }| null> {1165 let tokenData;1166 if(typeof blockHashAt === 'undefined') {1167 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1168 }1169 else {1170 if(propertyKeys.length == 0) {1171 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1172 if(!collection) return null;1173 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1174 }1175 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1176 }1177 tokenData = tokenData.toHuman();1178 if (tokenData === null || tokenData.owner === null) return null;1179 const owner = {} as any;1180 for (const key of Object.keys(tokenData.owner)) {1181 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1182 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1183 : tokenData.owner[key];1184 }1185 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1186 return tokenData;1187 }11881189 /**1190 * Set permissions to change token properties1191 *1192 * @param signer keyring of signer1193 * @param collectionId ID of collection1194 * @param permissions permissions to change a property by the collection admin or token owner1195 * @example setTokenPropertyPermissions(1196 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1197 * )1198 * @returns true if extrinsic success otherwise false1199 */1200 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1201 const result = await this.helper.executeExtrinsic(1202 signer,1203 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1204 true,1205 );12061207 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1208 }12091210 /**1211 * Get token property permissions.1212 * 1213 * @param collectionId ID of collection1214 * @param propertyKeys optionally filter the returned property permissions to only these keys1215 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1216 * @returns array of key-permission pairs1217 */1218 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1219 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1220 }12211222 /**1223 * Set token properties1224 *1225 * @param signer keyring of signer1226 * @param collectionId ID of collection1227 * @param tokenId ID of token1228 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1229 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1230 * @returns ```true``` if extrinsic success, otherwise ```false```1231 */1232 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1233 const result = await this.helper.executeExtrinsic(1234 signer,1235 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1236 true,1237 );12381239 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1240 }12411242 /**1243 * Get properties, metadata assigned to a token.1244 * 1245 * @param collectionId ID of collection1246 * @param tokenId ID of token1247 * @param propertyKeys optionally filter the returned properties to only these keys1248 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1249 * @returns array of key-value pairs1250 */1251 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1252 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1253 }12541255 /**1256 * Delete the provided properties of a token1257 * @param signer keyring of signer1258 * @param collectionId ID of collection1259 * @param tokenId ID of token1260 * @param propertyKeys property keys to be deleted1261 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1262 * @returns ```true``` if extrinsic success, otherwise ```false```1263 */1264 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1265 const result = await this.helper.executeExtrinsic(1266 signer,1267 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1268 true,1269 );12701271 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1272 }12731274 /**1275 * Mint new collection1276 *1277 * @param signer keyring of signer1278 * @param collectionOptions basic collection options and properties1279 * @param mode NFT or RFT type of a collection1280 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1281 * @returns object of the created collection1282 */1283 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1284 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1285 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1286 for (const key of ['name', 'description', 'tokenPrefix']) {1287 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);1288 }1289 const creationResult = await this.helper.executeExtrinsic(1290 signer,1291 'api.tx.unique.createCollectionEx', [collectionOptions],1292 true, // errorLabel,1293 );1294 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1295 }12961297 getCollectionObject(_collectionId: number): any {1298 return null;1299 }13001301 getTokenObject(_collectionId: number, _tokenId: number): any {1302 return null;1303 }1304}130513061307class NFTGroup extends NFTnRFT {1308 /**1309 * Get collection object1310 * @param collectionId ID of collection1311 * @example getCollectionObject(2);1312 * @returns instance of UniqueNFTCollection1313 */1314 getCollectionObject(collectionId: number): UniqueNFTCollection {1315 return new UniqueNFTCollection(collectionId, this.helper);1316 }13171318 /**1319 * Get token object1320 * @param collectionId ID of collection1321 * @param tokenId ID of token1322 * @example getTokenObject(10, 5);1323 * @returns instance of UniqueNFTToken1324 */1325 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1326 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1327 }13281329 /**1330 * Get token's owner1331 * @param collectionId ID of collection1332 * @param tokenId ID of token1333 * @param blockHashAt optionally query the data at the block with this hash1334 * @example getTokenOwner(10, 5);1335 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1336 */1337 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1338 let owner;1339 if (typeof blockHashAt === 'undefined') {1340 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1341 } else {1342 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1343 }1344 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1345 }13461347 /**1348 * Is token approved to transfer1349 * @param collectionId ID of collection1350 * @param tokenId ID of token1351 * @param toAccountObj address to be approved1352 * @returns ```true``` if extrinsic success, otherwise ```false```1353 */1354 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1355 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1356 }13571358 /**1359 * Changes the owner of the token.1360 *1361 * @param signer keyring of signer1362 * @param collectionId ID of collection1363 * @param tokenId ID of token1364 * @param addressObj address of a new owner1365 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1366 * @returns ```true``` if extrinsic success, otherwise ```false```1367 */1368 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1369 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1370 }13711372 /**1373 *1374 * Change ownership of a NFT on behalf of the owner.1375 *1376 * @param signer keyring of signer1377 * @param collectionId ID of collection1378 * @param tokenId ID of token1379 * @param fromAddressObj address on behalf of which the token will be sent1380 * @param toAddressObj new token owner1381 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1382 * @returns ```true``` if extrinsic success, otherwise ```false```1383 */1384 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1385 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1386 }13871388 /**1389 * Recursively find the address that owns the token1390 * @param collectionId ID of collection1391 * @param tokenId ID of token1392 * @param blockHashAt1393 * @example getTokenTopmostOwner(10, 5);1394 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1395 */1396 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1397 let owner;1398 if (typeof blockHashAt === 'undefined') {1399 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1400 } else {1401 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1402 }14031404 if (owner === null) return null;14051406 return owner.toHuman();1407 }14081409 /**1410 * Get tokens nested in the provided token1411 * @param collectionId ID of collection1412 * @param tokenId ID of token1413 * @param blockHashAt optionally query the data at the block with this hash1414 * @example getTokenChildren(10, 5);1415 * @returns tokens whose depth of nesting is <= 51416 */1417 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1418 let children;1419 if(typeof blockHashAt === 'undefined') {1420 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1421 } else {1422 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1423 }14241425 return children.toJSON().map((x: any) => {1426 return {collectionId: x.collection, tokenId: x.token};1427 });1428 }14291430 /**1431 * Nest one token into another1432 * @param signer keyring of signer1433 * @param tokenObj token to be nested1434 * @param rootTokenObj token to be parent1435 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1436 * @returns ```true``` if extrinsic success, otherwise ```false```1437 */1438 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1439 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1440 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1441 if(!result) {1442 throw Error('Unable to nest token!');1443 }1444 return result;1445 }14461447 /**1448 * Remove token from nested state1449 * @param signer keyring of signer1450 * @param tokenObj token to unnest1451 * @param rootTokenObj parent of a token1452 * @param toAddressObj address of a new token owner1453 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1454 * @returns ```true``` if extrinsic success, otherwise ```false```1455 */1456 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1457 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1458 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1459 if(!result) {1460 throw Error('Unable to unnest token!');1461 }1462 return result;1463 }14641465 /**1466 * Mint new collection1467 * @param signer keyring of signer1468 * @param collectionOptions Collection options1469 * @example1470 * mintCollection(aliceKeyring, {1471 * name: 'New',1472 * description: 'New collection',1473 * tokenPrefix: 'NEW',1474 * })1475 * @returns object of the created collection1476 */1477 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1478 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1479 }14801481 /**1482 * Mint new token1483 * @param signer keyring of signer1484 * @param data token data1485 * @returns created token object1486 */1487 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1488 const creationResult = await this.helper.executeExtrinsic(1489 signer,1490 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1491 nft: {1492 properties: data.properties,1493 },1494 }],1495 true,1496 );1497 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1498 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1499 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1500 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1501 }15021503 /**1504 * Mint multiple NFT tokens1505 * @param signer keyring of signer1506 * @param collectionId ID of collection1507 * @param tokens array of tokens with owner and properties1508 * @example1509 * mintMultipleTokens(aliceKeyring, 10, [{1510 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1511 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1512 * },{1513 * owner: {Ethereum: "0x9F0583DbB855d..."},1514 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1515 * }]);1516 * @returns ```true``` if extrinsic success, otherwise ```false```1517 */1518 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1519 const creationResult = await this.helper.executeExtrinsic(1520 signer,1521 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1522 true,1523 );1524 const collection = this.getCollectionObject(collectionId);1525 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1526 }15271528 /**1529 * Mint multiple NFT tokens with one owner1530 * @param signer keyring of signer1531 * @param collectionId ID of collection1532 * @param owner tokens owner1533 * @param tokens array of tokens with owner and properties1534 * @example1535 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1536 * properties: [{1537 * key: "gender",1538 * value: "female",1539 * },{1540 * key: "age",1541 * value: "33",1542 * }],1543 * }]);1544 * @returns array of newly created tokens1545 */1546 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1547 const rawTokens = [];1548 for (const token of tokens) {1549 const raw = {NFT: {properties: token.properties}};1550 rawTokens.push(raw);1551 }1552 const creationResult = await this.helper.executeExtrinsic(1553 signer,1554 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1555 true,1556 );1557 const collection = this.getCollectionObject(collectionId);1558 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1559 }15601561 /**1562 * Set, change, or remove approved address to transfer the ownership of the NFT.1563 *1564 * @param signer keyring of signer1565 * @param collectionId ID of collection1566 * @param tokenId ID of token1567 * @param toAddressObj address to approve1568 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1569 * @returns ```true``` if extrinsic success, otherwise ```false```1570 */1571 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1572 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1573 }1574}157515761577class RFTGroup extends NFTnRFT {1578 /**1579 * Get collection object1580 * @param collectionId ID of collection1581 * @example getCollectionObject(2);1582 * @returns instance of UniqueRFTCollection1583 */1584 getCollectionObject(collectionId: number): UniqueRFTCollection {1585 return new UniqueRFTCollection(collectionId, this.helper);1586 }15871588 /**1589 * Get token object1590 * @param collectionId ID of collection1591 * @param tokenId ID of token1592 * @example getTokenObject(10, 5);1593 * @returns instance of UniqueNFTToken1594 */1595 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1596 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1597 }15981599 /**1600 * Get top 10 token owners with the largest number of pieces1601 * @param collectionId ID of collection1602 * @param tokenId ID of token1603 * @example getTokenTop10Owners(10, 5);1604 * @returns array of top 10 owners1605 */1606 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1607 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1608 }16091610 /**1611 * Get number of pieces owned by address1612 * @param collectionId ID of collection1613 * @param tokenId ID of token1614 * @param addressObj address token owner1615 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1616 * @returns number of pieces ownerd by address1617 */1618 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1619 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1620 }16211622 /**1623 * Transfer pieces of token to another address1624 * @param signer keyring of signer1625 * @param collectionId ID of collection1626 * @param tokenId ID of token1627 * @param addressObj address of a new owner1628 * @param amount number of pieces to be transfered1629 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1630 * @returns ```true``` if extrinsic success, otherwise ```false```1631 */1632 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1633 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1634 }16351636 /**1637 * Change ownership of some pieces of RFT on behalf of the owner.1638 * @param signer keyring of signer1639 * @param collectionId ID of collection1640 * @param tokenId ID of token1641 * @param fromAddressObj address on behalf of which the token will be sent1642 * @param toAddressObj new token owner1643 * @param amount number of pieces to be transfered1644 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1645 * @returns ```true``` if extrinsic success, otherwise ```false```1646 */1647 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1648 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1649 }16501651 /**1652 * Mint new collection1653 * @param signer keyring of signer1654 * @param collectionOptions Collection options1655 * @example1656 * mintCollection(aliceKeyring, {1657 * name: 'New',1658 * description: 'New collection',1659 * tokenPrefix: 'NEW',1660 * })1661 * @returns object of the created collection1662 */1663 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1664 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1665 }16661667 /**1668 * Mint new token1669 * @param signer keyring of signer1670 * @param data token data1671 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1672 * @returns created token object1673 */1674 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1675 const creationResult = await this.helper.executeExtrinsic(1676 signer,1677 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1678 refungible: {1679 pieces: data.pieces,1680 properties: data.properties,1681 },1682 }],1683 true,1684 );1685 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1686 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1687 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1688 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1689 }16901691 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1692 throw Error('Not implemented');1693 const creationResult = await this.helper.executeExtrinsic(1694 signer,1695 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1696 true, // `Unable to mint RFT tokens for ${label}`,1697 );1698 const collection = this.getCollectionObject(collectionId);1699 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1700 }17011702 /**1703 * Mint multiple RFT tokens with one owner1704 * @param signer keyring of signer1705 * @param collectionId ID of collection1706 * @param owner tokens owner1707 * @param tokens array of tokens with properties and pieces1708 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1709 * @returns array of newly created RFT tokens1710 */1711 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1712 const rawTokens = [];1713 for (const token of tokens) {1714 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1715 rawTokens.push(raw);1716 }1717 const creationResult = await this.helper.executeExtrinsic(1718 signer,1719 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1720 true,1721 );1722 const collection = this.getCollectionObject(collectionId);1723 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1724 }17251726 /**1727 * Destroys a concrete instance of RFT.1728 * @param signer keyring of signer1729 * @param collectionId ID of collection1730 * @param tokenId ID of token1731 * @param amount number of pieces to be burnt1732 * @example burnToken(aliceKeyring, 10, 5);1733 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1734 */1735 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1736 return await super.burnToken(signer, collectionId, tokenId, amount);1737 }17381739 /**1740 * Destroys a concrete instance of RFT on behalf of the owner.1741 * @param signer keyring of signer1742 * @param collectionId ID of collection1743 * @param tokenId ID of token1744 * @param fromAddressObj address on behalf of which the token will be burnt1745 * @param amount number of pieces to be burnt1746 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1747 * @returns ```true``` if extrinsic success, otherwise ```false```1748 */1749 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1750 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1751 }17521753 /**1754 * Set, change, or remove approved address to transfer the ownership of the RFT.1755 *1756 * @param signer keyring of signer1757 * @param collectionId ID of collection1758 * @param tokenId ID of token1759 * @param toAddressObj address to approve1760 * @param amount number of pieces to be approved1761 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1762 * @returns true if the token success, otherwise false1763 */1764 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1765 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1766 }17671768 /**1769 * Get total number of pieces1770 * @param collectionId ID of collection1771 * @param tokenId ID of token1772 * @example getTokenTotalPieces(10, 5);1773 * @returns number of pieces1774 */1775 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1776 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1777 }17781779 /**1780 * Change number of token pieces. Signer must be the owner of all token pieces.1781 * @param signer keyring of signer1782 * @param collectionId ID of collection1783 * @param tokenId ID of token1784 * @param amount new number of pieces1785 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1786 * @returns true if the repartion was success, otherwise false1787 */1788 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1789 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1790 const repartitionResult = await this.helper.executeExtrinsic(1791 signer,1792 'api.tx.unique.repartition', [collectionId, tokenId, amount],1793 true,1794 );1795 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1796 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1797 }1798}179918001801class FTGroup extends CollectionGroup {1802 /**1803 * Get collection object1804 * @param collectionId ID of collection1805 * @example getCollectionObject(2);1806 * @returns instance of UniqueFTCollection1807 */1808 getCollectionObject(collectionId: number): UniqueFTCollection {1809 return new UniqueFTCollection(collectionId, this.helper);1810 }18111812 /**1813 * Mint new fungible collection1814 * @param signer keyring of signer1815 * @param collectionOptions Collection options1816 * @param decimalPoints number of token decimals1817 * @example1818 * mintCollection(aliceKeyring, {1819 * name: 'New',1820 * description: 'New collection',1821 * tokenPrefix: 'NEW',1822 * }, 18)1823 * @returns newly created fungible collection1824 */1825 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1826 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1827 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1828 collectionOptions.mode = {fungible: decimalPoints};1829 for (const key of ['name', 'description', 'tokenPrefix']) {1830 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);1831 }1832 const creationResult = await this.helper.executeExtrinsic(1833 signer,1834 'api.tx.unique.createCollectionEx', [collectionOptions],1835 true,1836 );1837 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1838 }18391840 /**1841 * Mint tokens1842 * @param signer keyring of signer1843 * @param collectionId ID of collection1844 * @param owner address owner of new tokens1845 * @param amount amount of tokens to be meanted1846 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1847 * @returns ```true``` if extrinsic success, otherwise ```false```1848 */1849 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1850 const creationResult = await this.helper.executeExtrinsic(1851 signer,1852 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1853 fungible: {1854 value: amount,1855 },1856 }],1857 true, // `Unable to mint fungible tokens for ${label}`,1858 );1859 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1860 }18611862 /**1863 * Mint multiple Fungible tokens with one owner1864 * @param signer keyring of signer1865 * @param collectionId ID of collection1866 * @param owner tokens owner1867 * @param tokens array of tokens with properties and pieces1868 * @returns ```true``` if extrinsic success, otherwise ```false```1869 */1870 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1871 const rawTokens = [];1872 for (const token of tokens) {1873 const raw = {Fungible: {Value: token.value}};1874 rawTokens.push(raw);1875 }1876 const creationResult = await this.helper.executeExtrinsic(1877 signer,1878 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1879 true,1880 );1881 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1882 }18831884 /**1885 * Get the top 10 owners with the largest balance for the Fungible collection1886 * @param collectionId ID of collection1887 * @example getTop10Owners(10);1888 * @returns array of ```ICrossAccountId```1889 */1890 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1891 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1892 }18931894 /**1895 * Get account balance1896 * @param collectionId ID of collection1897 * @param addressObj address of owner1898 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1899 * @returns amount of fungible tokens owned by address1900 */1901 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1902 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1903 }19041905 /**1906 * Transfer tokens to address1907 * @param signer keyring of signer1908 * @param collectionId ID of collection1909 * @param toAddressObj address recipient1910 * @param amount amount of tokens to be sent1911 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1912 * @returns ```true``` if extrinsic success, otherwise ```false```1913 */1914 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1915 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1916 }19171918 /**1919 * Transfer some tokens on behalf of the owner.1920 * @param signer keyring of signer1921 * @param collectionId ID of collection1922 * @param fromAddressObj address on behalf of which tokens will be sent1923 * @param toAddressObj address where token to be sent1924 * @param amount number of tokens to be sent1925 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1926 * @returns ```true``` if extrinsic success, otherwise ```false```1927 */1928 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1929 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1930 }19311932 /**1933 * Destroy some amount of tokens1934 * @param signer keyring of signer1935 * @param collectionId ID of collection1936 * @param amount amount of tokens to be destroyed1937 * @example burnTokens(aliceKeyring, 10, 1000n);1938 * @returns ```true``` if extrinsic success, otherwise ```false```1939 */1940 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1941 return await super.burnToken(signer, collectionId, 0, amount);1942 }19431944 /**1945 * Burn some tokens on behalf of the owner.1946 * @param signer keyring of signer1947 * @param collectionId ID of collection1948 * @param fromAddressObj address on behalf of which tokens will be burnt1949 * @param amount amount of tokens to be burnt1950 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1951 * @returns ```true``` if extrinsic success, otherwise ```false```1952 */1953 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1954 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);1955 }19561957 /**1958 * Get total collection supply1959 * @param collectionId1960 * @returns1961 */1962 async getTotalPieces(collectionId: number): Promise<bigint> {1963 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1964 }19651966 /**1967 * Set, change, or remove approved address to transfer tokens.1968 *1969 * @param signer keyring of signer1970 * @param collectionId ID of collection1971 * @param toAddressObj address to be approved1972 * @param amount amount of tokens to be approved1973 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1974 * @returns ```true``` if extrinsic success, otherwise ```false```1975 */1976 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1977 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1978 }19791980 /**1981 * Get amount of fungible tokens approved to transfer1982 * @param collectionId ID of collection1983 * @param fromAddressObj owner of tokens1984 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1985 * @returns number of tokens approved for the transfer1986 */1987 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1988 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1989 }1990}199119921993class ChainGroup extends HelperGroup {1994 /**1995 * Get system properties of a chain1996 * @example getChainProperties();1997 * @returns ss58Format, token decimals, and token symbol1998 */1999 getChainProperties(): IChainProperties {2000 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2001 return {2002 ss58Format: properties.ss58Format.toJSON(),2003 tokenDecimals: properties.tokenDecimals.toJSON(),2004 tokenSymbol: properties.tokenSymbol.toJSON(),2005 };2006 }20072008 /**2009 * Get chain header2010 * @example getLatestBlockNumber();2011 * @returns the number of the last block2012 */2013 async getLatestBlockNumber(): Promise<number> {2014 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2015 }20162017 /**2018 * Get block hash by block number2019 * @param blockNumber number of block2020 * @example getBlockHashByNumber(12345);2021 * @returns hash of a block2022 */2023 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2024 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2025 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2026 return blockHash;2027 }20282029 // TODO add docs2030 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2031 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2032 if (!blockHash) return null;2033 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2034 }20352036 /**2037 * Get account nonce2038 * @param address substrate address2039 * @example getNonce("5GrwvaEF5zXb26Fz...");2040 * @returns number, account's nonce2041 */2042 async getNonce(address: TSubstrateAccount): Promise<number> {2043 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2044 }2045}204620472048class BalanceGroup extends HelperGroup {2049 getCollectionCreationPrice(): bigint {2050 return 2n * this.helper.balance.getOneTokenNominal();2051 }2052 /**2053 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2054 * @example getOneTokenNominal()2055 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2056 */2057 getOneTokenNominal(): bigint {2058 const chainProperties = this.helper.chain.getChainProperties();2059 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2060 }20612062 /**2063 * Get substrate address balance2064 * @param address substrate address2065 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2066 * @returns amount of tokens on address2067 */2068 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2069 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2070 }20712072 /**2073 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2074 * @param address substrate address2075 * @returns2076 */2077 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2078 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2079 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2080 }20812082 /**2083 * Get ethereum address balance2084 * @param address ethereum address2085 * @example getEthereum("0x9F0583DbB855d...")2086 * @returns amount of tokens on address2087 */2088 async getEthereum(address: TEthereumAccount): Promise<bigint> {2089 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2090 }20912092 /**2093 * Transfer tokens to substrate address2094 * @param signer keyring of signer2095 * @param address substrate address of a recipient2096 * @param amount amount of tokens to be transfered2097 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2098 * @returns ```true``` if extrinsic success, otherwise ```false```2099 */2100 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2101 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}`*/);21022103 let transfer = {from: null, to: null, amount: 0n} as any;2104 result.result.events.forEach(({event: {data, method, section}}) => {2105 if ((section === 'balances') && (method === 'Transfer')) {2106 transfer = {2107 from: this.helper.address.normalizeSubstrate(data[0]),2108 to: this.helper.address.normalizeSubstrate(data[1]),2109 amount: BigInt(data[2]),2110 };2111 }2112 });2113 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2114 && this.helper.address.normalizeSubstrate(address) === transfer.to 2115 && BigInt(amount) === transfer.amount;2116 return isSuccess;2117 }2118}211921202121class AddressGroup extends HelperGroup {2122 /**2123 * Normalizes the address to the specified ss58 format, by default ```42```.2124 * @param address substrate address2125 * @param ss58Format format for address conversion, by default ```42```2126 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2127 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2128 */2129 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2130 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2131 }21322133 /**2134 * Get address in the connected chain format2135 * @param address substrate address2136 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2137 * @returns address in chain format2138 */2139 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2140 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2141 }21422143 /**2144 * Get substrate mirror of an ethereum address2145 * @param ethAddress ethereum address2146 * @param toChainFormat false for normalized account2147 * @example ethToSubstrate('0x9F0583DbB855d...')2148 * @returns substrate mirror of a provided ethereum address2149 */2150 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2151 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2152 }21532154 /**2155 * Get ethereum mirror of a substrate address2156 * @param subAddress substrate account2157 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2158 * @returns ethereum mirror of a provided substrate address2159 */2160 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2161 return CrossAccountId.translateSubToEth(subAddress);2162 }2163}21642165class StakingGroup extends HelperGroup {2166 /**2167 * Stake tokens for App Promotion2168 * @param signer keyring of signer2169 * @param amountToStake amount of tokens to stake2170 * @param label extra label for log2171 * @returns2172 */2173 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2174 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2175 const _stakeResult = await this.helper.executeExtrinsic(2176 signer, 'api.tx.appPromotion.stake',2177 [amountToStake], true,2178 );2179 // TODO extract info from stakeResult2180 return true;2181 }21822183 /**2184 * Unstake tokens for App Promotion2185 * @param signer keyring of signer2186 * @param amountToUnstake amount of tokens to unstake2187 * @param label extra label for log2188 * @returns block number where balances will be unlocked2189 */2190 async unstake(signer: TSigner, label?: string): Promise<number> {2191 if(typeof label === 'undefined') label = `${signer.address}`;2192 const _unstakeResult = await this.helper.executeExtrinsic(2193 signer, 'api.tx.appPromotion.unstake',2194 [], true,2195 );2196 // TODO extract block number fron events2197 return 1;2198 }21992200 /**2201 * Get total staked amount for address2202 * @param address substrate or ethereum address2203 * @returns total staked amount2204 */2205 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2206 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2207 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2208 }22092210 /**2211 * Get total staked per block2212 * @param address substrate or ethereum address2213 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2214 */2215 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2216 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2217 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2218 return { 2219 block: block.toBigInt(),2220 amount: amount.toBigInt(),2221 };2222 });2223 }22242225 /**2226 * Get total pending unstake amount for address2227 * @param address substrate or ethereum address2228 * @returns total pending unstake amount2229 */2230 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2231 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2232 }22332234 /**2235 * Get pending unstake amount per block for address2236 * @param address substrate or ethereum address2237 * @returns array of pending stakes. `block` – the number of the block in which the unstake was made. `amount` - the number of tokens unstaked in the block2238 */2239 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2240 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2241 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2242 return {2243 block: block.toBigInt(),2244 amount: amount.toBigInt(),2245 };2246 });2247 return result;2248 }2249}22502251export class UniqueHelper extends ChainHelperBase {2252 chain: ChainGroup;2253 balance: BalanceGroup;2254 address: AddressGroup;2255 collection: CollectionGroup;2256 nft: NFTGroup;2257 rft: RFTGroup;2258 ft: FTGroup;2259 staking: StakingGroup;22602261 constructor(logger?: ILogger) {2262 super(logger);2263 this.chain = new ChainGroup(this);2264 this.balance = new BalanceGroup(this);2265 this.address = new AddressGroup(this);2266 this.collection = new CollectionGroup(this);2267 this.nft = new NFTGroup(this);2268 this.rft = new RFTGroup(this);2269 this.ft = new FTGroup(this);2270 this.staking = new StakingGroup(this);2271 }2272}227322742275export class UniqueBaseCollection {2276 helper: UniqueHelper;2277 collectionId: number;22782279 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2280 this.collectionId = collectionId;2281 this.helper = uniqueHelper;2282 }22832284 async getData() {2285 return await this.helper.collection.getData(this.collectionId);2286 }22872288 async getLastTokenId() {2289 return await this.helper.collection.getLastTokenId(this.collectionId);2290 }22912292 async doesTokenExist(tokenId: number) {2293 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2294 }22952296 async getAdmins() {2297 return await this.helper.collection.getAdmins(this.collectionId);2298 }22992300 async getAllowList() {2301 return await this.helper.collection.getAllowList(this.collectionId);2302 }23032304 async getEffectiveLimits() {2305 return await this.helper.collection.getEffectiveLimits(this.collectionId);2306 }23072308 async getProperties(propertyKeys?: string[] | null) {2309 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2310 }23112312 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2313 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2314 }23152316 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2317 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2318 }23192320 async confirmSponsorship(signer: TSigner) {2321 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2322 }23232324 async removeSponsor(signer: TSigner) {2325 return await this.helper.collection.removeSponsor(signer, this.collectionId);2326 }23272328 async setLimits(signer: TSigner, limits: ICollectionLimits) {2329 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2330 }23312332 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2333 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2334 }23352336 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2337 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2338 }23392340 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2341 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2342 }23432344 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2345 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2346 }23472348 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2349 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2350 }23512352 async setProperties(signer: TSigner, properties: IProperty[]) {2353 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2354 }23552356 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2357 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2358 }23592360 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2361 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2362 }23632364 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2365 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2366 }23672368 async disableNesting(signer: TSigner) {2369 return await this.helper.collection.disableNesting(signer, this.collectionId);2370 }23712372 async burn(signer: TSigner) {2373 return await this.helper.collection.burn(signer, this.collectionId);2374 }2375}237623772378export class UniqueNFTCollection extends UniqueBaseCollection {2379 getTokenObject(tokenId: number) {2380 return new UniqueNFToken(tokenId, this);2381 }23822383 async getTokensByAddress(addressObj: ICrossAccountId) {2384 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2385 }23862387 async getToken(tokenId: number, blockHashAt?: string) {2388 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2389 }23902391 async getTokenOwner(tokenId: number, blockHashAt?: string) {2392 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2393 }23942395 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2396 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2397 }23982399 async getTokenChildren(tokenId: number, blockHashAt?: string) {2400 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2401 }24022403 async getPropertyPermissions(propertyKeys: string[] | null = null) {2404 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2405 }24062407 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2408 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2409 }24102411 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2412 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2413 }24142415 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2416 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2417 }24182419 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2420 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2421 }24222423 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2424 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2425 }24262427 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2428 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2429 }24302431 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2432 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2433 }24342435 async burnToken(signer: TSigner, tokenId: number) {2436 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2437 }24382439 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2440 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2441 }24422443 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2444 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2445 }24462447 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2448 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2449 }24502451 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2452 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2453 }24542455 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2456 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2457 }24582459 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2460 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2461 }2462}246324642465export class UniqueRFTCollection extends UniqueBaseCollection {2466 getTokenObject(tokenId: number) {2467 return new UniqueRFToken(tokenId, this);2468 }24692470 async getToken(tokenId: number, blockHashAt?: string) {2471 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);2472 }24732474 async getTokensByAddress(addressObj: ICrossAccountId) {2475 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2476 }24772478 async getTop10TokenOwners(tokenId: number) {2479 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2480 }24812482 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2483 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2484 }24852486 async getTokenTotalPieces(tokenId: number) {2487 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2488 }24892490 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2491 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2492 }24932494 async getPropertyPermissions(propertyKeys: string[] | null = null) {2495 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);2496 }24972498 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2499 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2500 }25012502 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2503 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2504 }25052506 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2507 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2508 }25092510 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2511 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2512 }25132514 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2515 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2516 }25172518 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2519 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2520 }25212522 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2523 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2524 }25252526 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2527 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2528 }25292530 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {2531 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);2532 }25332534 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2535 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2536 }25372538 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2539 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2540 }25412542 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2543 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2544 }2545}254625472548export class UniqueFTCollection extends UniqueBaseCollection {2549 async getBalance(addressObj: ICrossAccountId) {2550 return await this.helper.ft.getBalance(this.collectionId, addressObj);2551 }25522553 async getTotalPieces() {2554 return await this.helper.ft.getTotalPieces(this.collectionId);2555 }25562557 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2558 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2559 }25602561 async getTop10Owners() {2562 return await this.helper.ft.getTop10Owners(this.collectionId);2563 }25642565 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2566 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2567 }25682569 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2570 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2571 }25722573 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2574 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2575 }25762577 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2578 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2579 }25802581 async burnTokens(signer: TSigner, amount=1n) {2582 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2583 }25842585 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2586 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2587 }25882589 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2590 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2591 }2592}259325942595export class UniqueBaseToken {2596 collection: UniqueNFTCollection | UniqueRFTCollection;2597 collectionId: number;2598 tokenId: number;25992600 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2601 this.collection = collection;2602 this.collectionId = collection.collectionId;2603 this.tokenId = tokenId;2604 }26052606 async getNextSponsored(addressObj: ICrossAccountId) {2607 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2608 }26092610 async getProperties(propertyKeys?: string[] | null) {2611 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);2612 }26132614 async setProperties(signer: TSigner, properties: IProperty[]) {2615 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2616 }26172618 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2619 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2620 }26212622 async doesExist() {2623 return await this.collection.doesTokenExist(this.tokenId);2624 }26252626 nestingAccount() {2627 return this.collection.helper.util.getTokenAccount(this);2628 }2629}263026312632export class UniqueNFToken extends UniqueBaseToken {2633 collection: UniqueNFTCollection;26342635 constructor(tokenId: number, collection: UniqueNFTCollection) {2636 super(tokenId, collection);2637 this.collection = collection;2638 }26392640 async getData(blockHashAt?: string) {2641 return await this.collection.getToken(this.tokenId, blockHashAt);2642 }26432644 async getOwner(blockHashAt?: string) {2645 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2646 }26472648 async getTopmostOwner(blockHashAt?: string) {2649 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2650 }26512652 async getChildren(blockHashAt?: string) {2653 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2654 }26552656 async nest(signer: TSigner, toTokenObj: IToken) {2657 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2658 }26592660 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2661 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2662 }26632664 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2665 return await this.collection.transferToken(signer, this.tokenId, addressObj);2666 }26672668 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2669 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2670 }26712672 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2673 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2674 }26752676 async isApproved(toAddressObj: ICrossAccountId) {2677 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2678 }26792680 async burn(signer: TSigner) {2681 return await this.collection.burnToken(signer, this.tokenId);2682 }26832684 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {2685 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);2686 }2687}26882689export class UniqueRFToken extends UniqueBaseToken {2690 collection: UniqueRFTCollection;26912692 constructor(tokenId: number, collection: UniqueRFTCollection) {2693 super(tokenId, collection);2694 this.collection = collection;2695 }26962697 async getData(blockHashAt?: string) {2698 return await this.collection.getToken(this.tokenId, blockHashAt);2699 }27002701 async getTop10Owners() {2702 return await this.collection.getTop10TokenOwners(this.tokenId);2703 }27042705 async getBalance(addressObj: ICrossAccountId) {2706 return await this.collection.getTokenBalance(this.tokenId, addressObj);2707 }27082709 async getTotalPieces() {2710 return await this.collection.getTokenTotalPieces(this.tokenId);2711 }27122713 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2714 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2715 }27162717 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2718 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2719 }27202721 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2722 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2723 }27242725 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2726 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2727 }27282729 async repartition(signer: TSigner, amount: bigint) {2730 return await this.collection.repartitionToken(signer, this.tokenId, amount);2731 }27322733 async burn(signer: TSigner, amount=1n) {2734 return await this.collection.burnToken(signer, this.tokenId, amount);2735 }27362737 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2738 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);2739 }2740}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, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISchedulerOptions, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';13import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';1415export class CrossAccountId implements ICrossAccountId {16 Substrate?: TSubstrateAccount;17 Ethereum?: TEthereumAccount;1819 constructor(account: ICrossAccountId) {20 if (account.Substrate) this.Substrate = account.Substrate;21 if (account.Ethereum) this.Ethereum = account.Ethereum;22 }2324 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {25 switch (domain) {26 case 'Substrate': return new CrossAccountId({Substrate: account.address});27 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();28 }29 }3031 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {32 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});33 }3435 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {36 return encodeAddress(decodeAddress(address), ss58Format);37 }3839 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {40 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});41 }42 43 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {44 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);45 return this;46 }4748 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {49 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));50 }5152 toEthereum(): CrossAccountId {53 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});54 return this;55 }5657 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {58 return evmToAddress(address, ss58Format);59 }6061 toSubstrate(ss58Format?: number): CrossAccountId {62 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});63 return this;64 }65 66 toLowerCase(): CrossAccountId {67 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();68 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();69 return this;70 }71}7273const nesting = {74 toChecksumAddress(address: string): string {75 if (typeof address === 'undefined') return '';7677 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);7879 address = address.toLowerCase().replace(/^0x/i,'');80 const addressHash = keccakAsHex(address).replace(/^0x/i,'');81 const checksumAddress = ['0x'];8283 for (let i = 0; i < address.length; i++) {84 // If ith character is 8 to f then make it uppercase85 if (parseInt(addressHash[i], 16) > 7) {86 checksumAddress.push(address[i].toUpperCase());87 } else {88 checksumAddress.push(address[i]);89 }90 }91 return checksumAddress.join('');92 },93 tokenIdToAddress(collectionId: number, tokenId: number) {94 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);95 },96};9798class UniqueUtil {99 static transactionStatus = {100 NOT_READY: 'NotReady',101 FAIL: 'Fail',102 SUCCESS: 'Success',103 };104105 static chainLogType = {106 EXTRINSIC: 'extrinsic',107 RPC: 'rpc',108 };109110 static getTokenAccount(token: IToken): CrossAccountId {111 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});112 }113114 static getTokenAddress(token: IToken): string {115 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);116 }117118 static getDefaultLogger(): ILogger {119 return {120 log(msg: any, level = 'INFO') {121 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));122 },123 level: {124 ERROR: 'ERROR',125 WARNING: 'WARNING',126 INFO: 'INFO',127 },128 };129 }130131 static vec2str(arr: string[] | number[]) {132 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');133 }134135 static str2vec(string: string) {136 if (typeof string !== 'string') return string;137 return Array.from(string).map(x => x.charCodeAt(0));138 }139140 static fromSeed(seed: string, ss58Format = 42) {141 const keyring = new Keyring({type: 'sr25519', ss58Format});142 return keyring.addFromUri(seed);143 }144145 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {146 if (creationResult.status !== this.transactionStatus.SUCCESS) {147 throw Error('Unable to create collection!');148 }149150 let collectionId = null;151 creationResult.result.events.forEach(({event: {data, method, section}}) => {152 if ((section === 'common') && (method === 'CollectionCreated')) {153 collectionId = parseInt(data[0].toString(), 10);154 }155 });156157 if (collectionId === null) {158 throw Error('No CollectionCreated event was found!');159 }160161 return collectionId;162 }163164 static extractTokensFromCreationResult(creationResult: ITransactionResult): {165 success: boolean, 166 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],167 } {168 if (creationResult.status !== this.transactionStatus.SUCCESS) {169 throw Error('Unable to create tokens!');170 }171 let success = false;172 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];173 creationResult.result.events.forEach(({event: {data, method, section}}) => {174 if (method === 'ExtrinsicSuccess') {175 success = true;176 } else if ((section === 'common') && (method === 'ItemCreated')) {177 tokens.push({178 collectionId: parseInt(data[0].toString(), 10),179 tokenId: parseInt(data[1].toString(), 10),180 owner: data[2].toHuman(),181 amount: data[3].toBigInt(),182 });183 }184 });185 return {success, tokens};186 }187188 static extractTokensFromBurnResult(burnResult: ITransactionResult): {189 success: boolean, 190 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],191 } {192 if (burnResult.status !== this.transactionStatus.SUCCESS) {193 throw Error('Unable to burn tokens!');194 }195 let success = false;196 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];197 burnResult.result.events.forEach(({event: {data, method, section}}) => {198 if (method === 'ExtrinsicSuccess') {199 success = true;200 } else if ((section === 'common') && (method === 'ItemDestroyed')) {201 tokens.push({202 collectionId: parseInt(data[0].toString(), 10),203 tokenId: parseInt(data[1].toString(), 10),204 owner: data[2].toHuman(),205 amount: data[3].toBigInt(),206 });207 }208 });209 return {success, tokens};210 }211212 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {213 let eventId = null;214 events.forEach(({event: {data, method, section}}) => {215 if ((section === expectedSection) && (method === expectedMethod)) {216 eventId = parseInt(data[0].toString(), 10);217 }218 });219220 if (eventId === null) {221 throw Error(`No ${expectedMethod} event was found!`);222 }223 return eventId === collectionId;224 }225226 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {227 const normalizeAddress = (address: string | ICrossAccountId) => {228 if(typeof address === 'string') return address;229 const obj = {} as any;230 Object.keys(address).forEach(k => {231 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];232 });233 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);234 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();235 return address;236 };237 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;238 events.forEach(({event: {data, method, section}}) => {239 if ((section === 'common') && (method === 'Transfer')) {240 const hData = (data as any).toJSON();241 transfer = {242 collectionId: hData[0],243 tokenId: hData[1],244 from: normalizeAddress(hData[2]),245 to: normalizeAddress(hData[3]),246 amount: BigInt(hData[4]),247 };248 }249 });250 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;251 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);252 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);253 isSuccess = isSuccess && amount === transfer.amount;254 return isSuccess;255 }256}257258class UniqueEventHelper {259 private static extractIndex(index: any): [number, number] | string {260 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];261 return index.toJSON();262 }263264 private static extractSub(data: any, subTypes: any): {[key: string]: any} {265 let obj: any = {};266 let index = 0;267268 if (data.entries) {269 for(const [key, value] of data.entries()) {270 obj[key] = this.extractData(value, subTypes[index]);271 index++;272 }273 } else obj = data.toJSON();274275 return obj;276 }277 278 private static extractData(data: any, type: any): any {279 if(!type) return data.toHuman();280 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();281 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();282 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);283 return data.toHuman();284 }285286 public static extractEvents(records: ITransactionResult): IEvent[] {287 const parsedEvents: IEvent[] = [];288289 records.result.events.forEach((record) => {290 const {event, phase} = record;291 const types = (event as any).typeDef;292293 const eventData: IEvent = {294 section: event.section.toString(),295 method: event.method.toString(),296 index: this.extractIndex(event.index),297 data: [],298 phase: phase.toJSON(),299 };300301 event.data.forEach((val: any, index: number) => {302 eventData.data.push(this.extractData(val, types[index]));303 });304305 parsedEvents.push(eventData);306 });307308 return parsedEvents;309 }310}311312class ChainHelperBase {313 transactionStatus = UniqueUtil.transactionStatus;314 chainLogType = UniqueUtil.chainLogType;315 util: typeof UniqueUtil;316 eventHelper: typeof UniqueEventHelper;317 logger: ILogger;318 api: ApiPromise | null;319 forcedNetwork: TUniqueNetworks | null;320 network: TUniqueNetworks | null;321 chainLog: IUniqueHelperLog[];322 children: ChainHelperBase[];323324 constructor(logger?: ILogger) {325 this.util = UniqueUtil;326 this.eventHelper = UniqueEventHelper;327 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();328 this.logger = logger;329 this.api = null;330 this.forcedNetwork = null;331 this.network = null;332 this.chainLog = [];333 this.children = [];334 }335336 getApi(): ApiPromise {337 if(this.api === null) throw Error('API not initialized');338 return this.api;339 }340341 clearChainLog(): void {342 this.chainLog = [];343 }344345 forceNetwork(value: TUniqueNetworks): void {346 this.forcedNetwork = value;347 }348349 async connect(wsEndpoint: string, listeners?: IApiListeners) {350 if (this.api !== null) throw Error('Already connected');351 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);352 this.api = api;353 this.network = network;354 }355356 async disconnect() {357 for (const child of this.children) {358 child.clearApi();359 }360361 if (this.api === null) return;362 await this.api.disconnect();363 this.clearApi();364 }365366 clearApi() {367 this.api = null;368 this.network = null;369 }370371 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {372 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;373 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;374 return 'opal';375 }376377 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {378 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});379 await api.isReady;380381 const network = await this.detectNetwork(api);382383 await api.disconnect();384385 return network;386 }387388 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{389 api: ApiPromise;390 network: TUniqueNetworks;391 }> {392 if(typeof network === 'undefined' || network === null) network = 'opal';393 const supportedRPC = {394 opal: {395 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,396 },397 quartz: {398 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,399 },400 unique: {401 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,402 },403 };404 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);405 const rpc = supportedRPC[network];406407 // TODO: investigate how to replace rpc in runtime408 // api._rpcCore.addUserInterfaces(rpc);409410 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});411412 await api.isReadyOrError;413414 if (typeof listeners === 'undefined') listeners = {};415 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {416 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;417 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);418 }419420 return {api, network};421 }422423 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {424 const {events, status} = data;425 if (status.isReady) {426 return this.transactionStatus.NOT_READY;427 }428 if (status.isBroadcast) {429 return this.transactionStatus.NOT_READY;430 }431 if (status.isInBlock || status.isFinalized) {432 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');433 if (errors.length > 0) {434 return this.transactionStatus.FAIL;435 }436 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {437 return this.transactionStatus.SUCCESS;438 }439 }440441 return this.transactionStatus.FAIL;442 }443444 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {445 const sign = (callback: any) => {446 if(options !== null) return transaction.signAndSend(sender, options, callback);447 return transaction.signAndSend(sender, callback);448 };449 // eslint-disable-next-line no-async-promise-executor450 return new Promise(async (resolve, reject) => {451 try {452 const unsub = await sign((result: any) => {453 const status = this.getTransactionStatus(result);454455 if (status === this.transactionStatus.SUCCESS) {456 this.logger.log(`${label} successful`);457 unsub();458 resolve({result, status});459 } else if (status === this.transactionStatus.FAIL) {460 let moduleError = null;461462 if (result.hasOwnProperty('dispatchError')) {463 const dispatchError = result['dispatchError'];464465 if (dispatchError) {466 if (dispatchError.isModule) {467 const modErr = dispatchError.asModule;468 const errorMeta = dispatchError.registry.findMetaError(modErr);469470 moduleError = `${errorMeta.section}.${errorMeta.name}`;471 } else {472 moduleError = dispatchError.toHuman();473 }474 } else {475 this.logger.log(result, this.logger.level.ERROR);476 }477 }478479 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);480 unsub();481 reject({status, moduleError, result});482 }483 });484 } catch (e) {485 this.logger.log(e, this.logger.level.ERROR);486 reject(e);487 }488 });489 }490491 constructApiCall(apiCall: string, params: any[]) {492 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);493 let call = this.getApi() as any;494 for(const part of apiCall.slice(4).split('.')) {495 call = call[part];496 }497 return call(...params);498 }499500 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {501 if(this.api === null) throw Error('API not initialized');502 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);503504 const startTime = (new Date()).getTime();505 let result: ITransactionResult;506 let events: IEvent[] = [];507 try {508 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;509 events = this.eventHelper.extractEvents(result);510 }511 catch(e) {512 if(!(e as object).hasOwnProperty('status')) throw e;513 result = e as ITransactionResult;514 }515516 const endTime = (new Date()).getTime();517518 const log = {519 executedAt: endTime,520 executionTime: endTime - startTime,521 type: this.chainLogType.EXTRINSIC,522 status: result.status,523 call: extrinsic,524 signer: this.getSignerAddress(sender),525 params,526 } as IUniqueHelperLog;527528 if(result.status !== this.transactionStatus.SUCCESS) {529 if (result.moduleError) log.moduleError = result.moduleError;530 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;531 }532 if(events.length > 0) log.events = events;533534 this.chainLog.push(log);535536 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {537 if (result.moduleError) throw Error(`${result.moduleError}`);538 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));539 }540 return result;541 }542543 async callRpc(rpc: string, params?: any[]) {544 if(typeof params === 'undefined') params = [];545 if(this.api === null) throw Error('API not initialized');546 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);547548 const startTime = (new Date()).getTime();549 let result;550 let error = null;551 const log = {552 type: this.chainLogType.RPC,553 call: rpc,554 params,555 } as IUniqueHelperLog;556557 try {558 result = await this.constructApiCall(rpc, params);559 }560 catch(e) {561 error = e;562 }563564 const endTime = (new Date()).getTime();565566 log.executedAt = endTime;567 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';568 log.executionTime = endTime - startTime;569570 this.chainLog.push(log);571572 if(error !== null) throw error;573574 return result;575 }576577 getSignerAddress(signer: IKeyringPair | string): string {578 if(typeof signer === 'string') return signer;579 return signer.address;580 }581582 fetchAllPalletNames(): string[] {583 if(this.api === null) throw Error('API not initialized');584 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());585 }586587 fetchMissingPalletNames(requiredPallets: string[]): string[] {588 const palletNames = this.fetchAllPalletNames();589 return requiredPallets.filter(p => !palletNames.includes(p));590 }591}592593594class HelperGroup {595 helper: UniqueHelper;596597 constructor(uniqueHelper: UniqueHelper) {598 this.helper = uniqueHelper;599 }600}601602603class CollectionGroup extends HelperGroup {604 /**605 * Get number of blocks when sponsored transaction is available.606 *607 * @param collectionId ID of collection608 * @param tokenId ID of token609 * @param addressObj address for which the sponsorship is checked610 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});611 * @returns number of blocks or null if sponsorship hasn't been set612 */613 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {614 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();615 }616617 /**618 * Get the number of created collections.619 *620 * @returns number of created collections621 */622 async getTotalCount(): Promise<number> {623 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();624 }625626 /**627 * Get information about the collection with additional data,628 * including the number of tokens it contains, its administrators,629 * the normalized address of the collection's owner, and decoded name and description.630 *631 * @param collectionId ID of collection632 * @example await getData(2)633 * @returns collection information object634 */635 async getData(collectionId: number): Promise<{636 id: number;637 name: string;638 description: string;639 tokensCount: number;640 admins: CrossAccountId[];641 normalizedOwner: TSubstrateAccount;642 raw: any643 } | null> {644 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);645 const humanCollection = collection.toHuman(), collectionData = {646 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],647 raw: humanCollection,648 } as any, jsonCollection = collection.toJSON();649 if (humanCollection === null) return null;650 collectionData.raw.limits = jsonCollection.limits;651 collectionData.raw.permissions = jsonCollection.permissions;652 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);653 for (const key of ['name', 'description']) {654 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);655 }656657 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))658 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)659 : 0;660 collectionData.admins = await this.getAdmins(collectionId);661662 return collectionData;663 }664665 /**666 * Get the addresses of the collection's administrators, optionally normalized.667 *668 * @param collectionId ID of collection669 * @param normalize whether to normalize the addresses to the default ss58 format670 * @example await getAdmins(1)671 * @returns array of administrators672 */673 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {674 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();675676 return normalize677 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())678 : admins;679 }680681 /**682 * Get the addresses added to the collection allow-list, optionally normalized.683 * @param collectionId ID of collection684 * @param normalize whether to normalize the addresses to the default ss58 format685 * @example await getAllowList(1)686 * @returns array of allow-listed addresses687 */688 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {689 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();690 return normalize691 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())692 : allowListed;693 }694695 /**696 * Get the effective limits of the collection instead of null for default values697 *698 * @param collectionId ID of collection699 * @example await getEffectiveLimits(2)700 * @returns object of collection limits701 */702 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {703 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();704 }705706 /**707 * Burns the collection if the signer has sufficient permissions and collection is empty.708 *709 * @param signer keyring of signer710 * @param collectionId ID of collection711 * @example await helper.collection.burn(aliceKeyring, 3);712 * @returns ```true``` if extrinsic success, otherwise ```false```713 */714 async burn(signer: TSigner, collectionId: number): Promise<boolean> {715 const result = await this.helper.executeExtrinsic(716 signer,717 'api.tx.unique.destroyCollection', [collectionId],718 true,719 );720721 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');722 }723724 /**725 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.726 *727 * @param signer keyring of signer728 * @param collectionId ID of collection729 * @param sponsorAddress Sponsor substrate address730 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")731 * @returns ```true``` if extrinsic success, otherwise ```false```732 */733 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {734 const result = await this.helper.executeExtrinsic(735 signer,736 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],737 true,738 );739740 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');741 }742743 /**744 * Confirms consent to sponsor the collection on behalf of the signer.745 *746 * @param signer keyring of signer747 * @param collectionId ID of collection748 * @example confirmSponsorship(aliceKeyring, 10)749 * @returns ```true``` if extrinsic success, otherwise ```false```750 */751 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {752 const result = await this.helper.executeExtrinsic(753 signer,754 'api.tx.unique.confirmSponsorship', [collectionId],755 true,756 );757758 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');759 }760761 /**762 * Removes the sponsor of a collection, regardless if it consented or not.763 *764 * @param signer keyring of signer765 * @param collectionId ID of collection766 * @example removeSponsor(aliceKeyring, 10)767 * @returns ```true``` if extrinsic success, otherwise ```false```768 */769 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {770 const result = await this.helper.executeExtrinsic(771 signer,772 'api.tx.unique.removeCollectionSponsor', [collectionId],773 true,774 );775776 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');777 }778779 /**780 * Sets the limits of the collection. At least one limit must be specified for a correct call.781 *782 * @param signer keyring of signer783 * @param collectionId ID of collection784 * @param limits collection limits object785 * @example786 * await setLimits(787 * aliceKeyring,788 * 10,789 * {790 * sponsorTransferTimeout: 0,791 * ownerCanDestroy: false792 * }793 * )794 * @returns ```true``` if extrinsic success, otherwise ```false```795 */796 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {797 const result = await this.helper.executeExtrinsic(798 signer,799 'api.tx.unique.setCollectionLimits', [collectionId, limits],800 true,801 );802803 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');804 }805806 /**807 * Changes the owner of the collection to the new Substrate address.808 *809 * @param signer keyring of signer810 * @param collectionId ID of collection811 * @param ownerAddress substrate address of new owner812 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")813 * @returns ```true``` if extrinsic success, otherwise ```false```814 */815 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {816 const result = await this.helper.executeExtrinsic(817 signer,818 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],819 true,820 );821822 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');823 }824825 /**826 * Adds a collection administrator.827 *828 * @param signer keyring of signer829 * @param collectionId ID of collection830 * @param adminAddressObj Administrator address (substrate or ethereum)831 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})832 * @returns ```true``` if extrinsic success, otherwise ```false```833 */834 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {835 const result = await this.helper.executeExtrinsic(836 signer,837 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],838 true,839 );840841 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');842 }843844 /**845 * Removes a collection administrator.846 *847 * @param signer keyring of signer848 * @param collectionId ID of collection849 * @param adminAddressObj Administrator address (substrate or ethereum)850 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})851 * @returns ```true``` if extrinsic success, otherwise ```false```852 */853 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {854 const result = await this.helper.executeExtrinsic(855 signer,856 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],857 true,858 );859860 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');861 }862863 /**864 * Check if user is in allow list.865 * 866 * @param collectionId ID of collection867 * @param user Account to check868 * @example await getAdmins(1)869 * @returns is user in allow list870 */871 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {872 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();873 }874875 /**876 * Adds an address to allow list877 * @param signer keyring of signer878 * @param collectionId ID of collection879 * @param addressObj address to add to the allow list880 * @returns ```true``` if extrinsic success, otherwise ```false```881 */882 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {883 const result = await this.helper.executeExtrinsic(884 signer,885 'api.tx.unique.addToAllowList', [collectionId, addressObj],886 true,887 );888889 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');890 }891892 /**893 * Removes an address from allow list894 *895 * @param signer keyring of signer896 * @param collectionId ID of collection897 * @param addressObj address to remove from the allow list898 * @returns ```true``` if extrinsic success, otherwise ```false```899 */900 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {901 const result = await this.helper.executeExtrinsic(902 signer,903 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],904 true,905 );906907 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');908 }909910 /**911 * Sets onchain permissions for selected collection.912 *913 * @param signer keyring of signer914 * @param collectionId ID of collection915 * @param permissions collection permissions object916 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});917 * @returns ```true``` if extrinsic success, otherwise ```false```918 */919 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {920 const result = await this.helper.executeExtrinsic(921 signer,922 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],923 true,924 );925926 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');927 }928929 /**930 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.931 *932 * @param signer keyring of signer933 * @param collectionId ID of collection934 * @param permissions nesting permissions object935 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});936 * @returns ```true``` if extrinsic success, otherwise ```false```937 */938 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {939 return await this.setPermissions(signer, collectionId, {nesting: permissions});940 }941942 /**943 * Disables nesting for selected collection.944 *945 * @param signer keyring of signer946 * @param collectionId ID of collection947 * @example disableNesting(aliceKeyring, 10);948 * @returns ```true``` if extrinsic success, otherwise ```false```949 */950 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {951 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});952 }953954 /**955 * Sets onchain properties to the collection.956 *957 * @param signer keyring of signer958 * @param collectionId ID of collection959 * @param properties array of property objects960 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);961 * @returns ```true``` if extrinsic success, otherwise ```false```962 */963 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {964 const result = await this.helper.executeExtrinsic(965 signer,966 'api.tx.unique.setCollectionProperties', [collectionId, properties],967 true,968 );969970 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');971 }972973 /**974 * Get collection properties.975 * 976 * @param collectionId ID of collection977 * @param propertyKeys optionally filter the returned properties to only these keys978 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);979 * @returns array of key-value pairs980 */981 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {982 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();983 }984985 /**986 * Deletes onchain properties from the collection.987 *988 * @param signer keyring of signer989 * @param collectionId ID of collection990 * @param propertyKeys array of property keys to delete991 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);992 * @returns ```true``` if extrinsic success, otherwise ```false```993 */994 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {995 const result = await this.helper.executeExtrinsic(996 signer,997 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],998 true,999 );10001001 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1002 }10031004 /**1005 * Changes the owner of the token.1006 *1007 * @param signer keyring of signer1008 * @param collectionId ID of collection1009 * @param tokenId ID of token1010 * @param addressObj address of a new owner1011 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1012 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1013 * @returns true if the token success, otherwise false1014 */1015 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1016 const result = await this.helper.executeExtrinsic(1017 signer,1018 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1019 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1020 );10211022 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1023 }10241025 /**1026 *1027 * Change ownership of a token(s) on behalf of the owner.1028 *1029 * @param signer keyring of signer1030 * @param collectionId ID of collection1031 * @param tokenId ID of token1032 * @param fromAddressObj address on behalf of which the token will be sent1033 * @param toAddressObj new token owner1034 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1035 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1036 * @returns true if the token success, otherwise false1037 */1038 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1039 const result = await this.helper.executeExtrinsic(1040 signer,1041 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1042 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1043 );1044 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1045 }10461047 /**1048 *1049 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1050 *1051 * @param signer keyring of signer1052 * @param collectionId ID of collection1053 * @param tokenId ID of token1054 * @param amount amount of tokens to be burned. For NFT must be set to 1n1055 * @example burnToken(aliceKeyring, 10, 5);1056 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1057 */1058 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1059 const burnResult = await this.helper.executeExtrinsic(1060 signer,1061 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1062 true, // `Unable to burn token for ${label}`,1063 );1064 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1065 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1066 return burnedTokens.success;1067 }10681069 /**1070 * Destroys a concrete instance of NFT on behalf of the owner1071 *1072 * @param signer keyring of signer1073 * @param collectionId ID of collection1074 * @param tokenId ID of token1075 * @param fromAddressObj address on behalf of which the token will be burnt1076 * @param amount amount of tokens to be burned. For NFT must be set to 1n1077 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1078 * @returns ```true``` if extrinsic success, otherwise ```false```1079 */1080 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1081 const burnResult = await this.helper.executeExtrinsic(1082 signer,1083 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1084 true, // `Unable to burn token from for ${label}`,1085 );1086 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1087 return burnedTokens.success && burnedTokens.tokens.length > 0;1088 }10891090 /**1091 * Set, change, or remove approved address to transfer the ownership of the NFT.1092 *1093 * @param signer keyring of signer1094 * @param collectionId ID of collection1095 * @param tokenId ID of token1096 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1097 * @param amount amount of token to be approved. For NFT must be set to 1n1098 * @returns ```true``` if extrinsic success, otherwise ```false```1099 */1100 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1101 const approveResult = await this.helper.executeExtrinsic(1102 signer,1103 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1104 true, // `Unable to approve token for ${label}`,1105 );11061107 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1108 }11091110 /**1111 * Get the amount of token pieces approved to transfer or burn. Normally 0.1112 *1113 * @param collectionId ID of collection1114 * @param tokenId ID of token1115 * @param toAccountObj address which is approved to use token pieces1116 * @param fromAccountObj address which may have allowed the use of its owned tokens1117 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1118 * @returns number of approved to transfer pieces1119 */1120 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1121 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1122 }11231124 /**1125 * Get the last created token ID in a collection1126 *1127 * @param collectionId ID of collection1128 * @example getLastTokenId(10);1129 * @returns id of the last created token1130 */1131 async getLastTokenId(collectionId: number): Promise<number> {1132 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1133 }11341135 /**1136 * Check if token exists1137 *1138 * @param collectionId ID of collection1139 * @param tokenId ID of token1140 * @example doesTokenExist(10, 20);1141 * @returns true if the token exists, otherwise false1142 */1143 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1144 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1145 }1146}11471148class NFTnRFT extends CollectionGroup {1149 /**1150 * Get tokens owned by account1151 *1152 * @param collectionId ID of collection1153 * @param addressObj tokens owner1154 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1155 * @returns array of token ids owned by account1156 */1157 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1158 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1159 }11601161 /**1162 * Get token data1163 *1164 * @param collectionId ID of collection1165 * @param tokenId ID of token1166 * @param propertyKeys optionally filter the token properties to only these keys1167 * @param blockHashAt optionally query the data at some block with this hash1168 * @example getToken(10, 5);1169 * @returns human readable token data1170 */1171 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1172 properties: IProperty[];1173 owner: CrossAccountId;1174 normalizedOwner: CrossAccountId;1175 }| null> {1176 let tokenData;1177 if(typeof blockHashAt === 'undefined') {1178 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1179 }1180 else {1181 if(propertyKeys.length == 0) {1182 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1183 if(!collection) return null;1184 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1185 }1186 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1187 }1188 tokenData = tokenData.toHuman();1189 if (tokenData === null || tokenData.owner === null) return null;1190 const owner = {} as any;1191 for (const key of Object.keys(tokenData.owner)) {1192 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1193 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1194 : tokenData.owner[key];1195 }1196 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1197 return tokenData;1198 }11991200 /**1201 * Set permissions to change token properties1202 *1203 * @param signer keyring of signer1204 * @param collectionId ID of collection1205 * @param permissions permissions to change a property by the collection admin or token owner1206 * @example setTokenPropertyPermissions(1207 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1208 * )1209 * @returns true if extrinsic success otherwise false1210 */1211 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1212 const result = await this.helper.executeExtrinsic(1213 signer,1214 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1215 true,1216 );12171218 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1219 }12201221 /**1222 * Get token property permissions.1223 * 1224 * @param collectionId ID of collection1225 * @param propertyKeys optionally filter the returned property permissions to only these keys1226 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1227 * @returns array of key-permission pairs1228 */1229 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1230 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1231 }12321233 /**1234 * Set token properties1235 *1236 * @param signer keyring of signer1237 * @param collectionId ID of collection1238 * @param tokenId ID of token1239 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1240 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1241 * @returns ```true``` if extrinsic success, otherwise ```false```1242 */1243 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1244 const result = await this.helper.executeExtrinsic(1245 signer,1246 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1247 true,1248 );12491250 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1251 }12521253 /**1254 * Get properties, metadata assigned to a token.1255 * 1256 * @param collectionId ID of collection1257 * @param tokenId ID of token1258 * @param propertyKeys optionally filter the returned properties to only these keys1259 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1260 * @returns array of key-value pairs1261 */1262 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1263 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1264 }12651266 /**1267 * Delete the provided properties of a token1268 * @param signer keyring of signer1269 * @param collectionId ID of collection1270 * @param tokenId ID of token1271 * @param propertyKeys property keys to be deleted1272 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1273 * @returns ```true``` if extrinsic success, otherwise ```false```1274 */1275 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1276 const result = await this.helper.executeExtrinsic(1277 signer,1278 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1279 true,1280 );12811282 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1283 }12841285 /**1286 * Mint new collection1287 *1288 * @param signer keyring of signer1289 * @param collectionOptions basic collection options and properties1290 * @param mode NFT or RFT type of a collection1291 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1292 * @returns object of the created collection1293 */1294 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1295 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1296 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1297 for (const key of ['name', 'description', 'tokenPrefix']) {1298 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);1299 }1300 const creationResult = await this.helper.executeExtrinsic(1301 signer,1302 'api.tx.unique.createCollectionEx', [collectionOptions],1303 true, // errorLabel,1304 );1305 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1306 }13071308 getCollectionObject(_collectionId: number): any {1309 return null;1310 }13111312 getTokenObject(_collectionId: number, _tokenId: number): any {1313 return null;1314 }1315}131613171318class NFTGroup extends NFTnRFT {1319 /**1320 * Get collection object1321 * @param collectionId ID of collection1322 * @example getCollectionObject(2);1323 * @returns instance of UniqueNFTCollection1324 */1325 getCollectionObject(collectionId: number): UniqueNFTCollection {1326 return new UniqueNFTCollection(collectionId, this.helper);1327 }13281329 /**1330 * Get token object1331 * @param collectionId ID of collection1332 * @param tokenId ID of token1333 * @example getTokenObject(10, 5);1334 * @returns instance of UniqueNFTToken1335 */1336 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1337 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1338 }13391340 /**1341 * Get token's owner1342 * @param collectionId ID of collection1343 * @param tokenId ID of token1344 * @param blockHashAt optionally query the data at the block with this hash1345 * @example getTokenOwner(10, 5);1346 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1347 */1348 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1349 let owner;1350 if (typeof blockHashAt === 'undefined') {1351 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1352 } else {1353 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1354 }1355 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1356 }13571358 /**1359 * Is token approved to transfer1360 * @param collectionId ID of collection1361 * @param tokenId ID of token1362 * @param toAccountObj address to be approved1363 * @returns ```true``` if extrinsic success, otherwise ```false```1364 */1365 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1366 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1367 }13681369 /**1370 * Changes the owner of the token.1371 *1372 * @param signer keyring of signer1373 * @param collectionId ID of collection1374 * @param tokenId ID of token1375 * @param addressObj address of a new owner1376 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1377 * @returns ```true``` if extrinsic success, otherwise ```false```1378 */1379 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1380 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1381 }13821383 /**1384 *1385 * Change ownership of a NFT on behalf of the owner.1386 *1387 * @param signer keyring of signer1388 * @param collectionId ID of collection1389 * @param tokenId ID of token1390 * @param fromAddressObj address on behalf of which the token will be sent1391 * @param toAddressObj new token owner1392 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1393 * @returns ```true``` if extrinsic success, otherwise ```false```1394 */1395 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1396 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1397 }13981399 /**1400 * Recursively find the address that owns the token1401 * @param collectionId ID of collection1402 * @param tokenId ID of token1403 * @param blockHashAt1404 * @example getTokenTopmostOwner(10, 5);1405 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1406 */1407 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1408 let owner;1409 if (typeof blockHashAt === 'undefined') {1410 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1411 } else {1412 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1413 }14141415 if (owner === null) return null;14161417 return owner.toHuman();1418 }14191420 /**1421 * Get tokens nested in the provided token1422 * @param collectionId ID of collection1423 * @param tokenId ID of token1424 * @param blockHashAt optionally query the data at the block with this hash1425 * @example getTokenChildren(10, 5);1426 * @returns tokens whose depth of nesting is <= 51427 */1428 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1429 let children;1430 if(typeof blockHashAt === 'undefined') {1431 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1432 } else {1433 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1434 }14351436 return children.toJSON().map((x: any) => {1437 return {collectionId: x.collection, tokenId: x.token};1438 });1439 }14401441 /**1442 * Nest one token into another1443 * @param signer keyring of signer1444 * @param tokenObj token to be nested1445 * @param rootTokenObj token to be parent1446 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1447 * @returns ```true``` if extrinsic success, otherwise ```false```1448 */1449 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1450 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1451 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1452 if(!result) {1453 throw Error('Unable to nest token!');1454 }1455 return result;1456 }14571458 /**1459 * Remove token from nested state1460 * @param signer keyring of signer1461 * @param tokenObj token to unnest1462 * @param rootTokenObj parent of a token1463 * @param toAddressObj address of a new token owner1464 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1465 * @returns ```true``` if extrinsic success, otherwise ```false```1466 */1467 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1468 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1469 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1470 if(!result) {1471 throw Error('Unable to unnest token!');1472 }1473 return result;1474 }14751476 /**1477 * Mint new collection1478 * @param signer keyring of signer1479 * @param collectionOptions Collection options1480 * @example1481 * mintCollection(aliceKeyring, {1482 * name: 'New',1483 * description: 'New collection',1484 * tokenPrefix: 'NEW',1485 * })1486 * @returns object of the created collection1487 */1488 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1489 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1490 }14911492 /**1493 * Mint new token1494 * @param signer keyring of signer1495 * @param data token data1496 * @returns created token object1497 */1498 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1499 const creationResult = await this.helper.executeExtrinsic(1500 signer,1501 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1502 nft: {1503 properties: data.properties,1504 },1505 }],1506 true,1507 );1508 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1509 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1510 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1511 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1512 }15131514 /**1515 * Mint multiple NFT tokens1516 * @param signer keyring of signer1517 * @param collectionId ID of collection1518 * @param tokens array of tokens with owner and properties1519 * @example1520 * mintMultipleTokens(aliceKeyring, 10, [{1521 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1522 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1523 * },{1524 * owner: {Ethereum: "0x9F0583DbB855d..."},1525 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1526 * }]);1527 * @returns ```true``` if extrinsic success, otherwise ```false```1528 */1529 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1530 const creationResult = await this.helper.executeExtrinsic(1531 signer,1532 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1533 true,1534 );1535 const collection = this.getCollectionObject(collectionId);1536 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1537 }15381539 /**1540 * Mint multiple NFT tokens with one owner1541 * @param signer keyring of signer1542 * @param collectionId ID of collection1543 * @param owner tokens owner1544 * @param tokens array of tokens with owner and properties1545 * @example1546 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1547 * properties: [{1548 * key: "gender",1549 * value: "female",1550 * },{1551 * key: "age",1552 * value: "33",1553 * }],1554 * }]);1555 * @returns array of newly created tokens1556 */1557 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1558 const rawTokens = [];1559 for (const token of tokens) {1560 const raw = {NFT: {properties: token.properties}};1561 rawTokens.push(raw);1562 }1563 const creationResult = await this.helper.executeExtrinsic(1564 signer,1565 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1566 true,1567 );1568 const collection = this.getCollectionObject(collectionId);1569 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1570 }15711572 /**1573 * Set, change, or remove approved address to transfer the ownership of the NFT.1574 *1575 * @param signer keyring of signer1576 * @param collectionId ID of collection1577 * @param tokenId ID of token1578 * @param toAddressObj address to approve1579 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1580 * @returns ```true``` if extrinsic success, otherwise ```false```1581 */1582 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1583 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1584 }1585}158615871588class RFTGroup extends NFTnRFT {1589 /**1590 * Get collection object1591 * @param collectionId ID of collection1592 * @example getCollectionObject(2);1593 * @returns instance of UniqueRFTCollection1594 */1595 getCollectionObject(collectionId: number): UniqueRFTCollection {1596 return new UniqueRFTCollection(collectionId, this.helper);1597 }15981599 /**1600 * Get token object1601 * @param collectionId ID of collection1602 * @param tokenId ID of token1603 * @example getTokenObject(10, 5);1604 * @returns instance of UniqueNFTToken1605 */1606 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1607 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1608 }16091610 /**1611 * Get top 10 token owners with the largest number of pieces1612 * @param collectionId ID of collection1613 * @param tokenId ID of token1614 * @example getTokenTop10Owners(10, 5);1615 * @returns array of top 10 owners1616 */1617 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1618 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1619 }16201621 /**1622 * Get number of pieces owned by address1623 * @param collectionId ID of collection1624 * @param tokenId ID of token1625 * @param addressObj address token owner1626 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1627 * @returns number of pieces ownerd by address1628 */1629 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1630 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1631 }16321633 /**1634 * Transfer pieces of token to another address1635 * @param signer keyring of signer1636 * @param collectionId ID of collection1637 * @param tokenId ID of token1638 * @param addressObj address of a new owner1639 * @param amount number of pieces to be transfered1640 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1641 * @returns ```true``` if extrinsic success, otherwise ```false```1642 */1643 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1644 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1645 }16461647 /**1648 * Change ownership of some pieces of RFT on behalf of the owner.1649 * @param signer keyring of signer1650 * @param collectionId ID of collection1651 * @param tokenId ID of token1652 * @param fromAddressObj address on behalf of which the token will be sent1653 * @param toAddressObj new token owner1654 * @param amount number of pieces to be transfered1655 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1656 * @returns ```true``` if extrinsic success, otherwise ```false```1657 */1658 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1659 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1660 }16611662 /**1663 * Mint new collection1664 * @param signer keyring of signer1665 * @param collectionOptions Collection options1666 * @example1667 * mintCollection(aliceKeyring, {1668 * name: 'New',1669 * description: 'New collection',1670 * tokenPrefix: 'NEW',1671 * })1672 * @returns object of the created collection1673 */1674 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1675 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1676 }16771678 /**1679 * Mint new token1680 * @param signer keyring of signer1681 * @param data token data1682 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1683 * @returns created token object1684 */1685 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1686 const creationResult = await this.helper.executeExtrinsic(1687 signer,1688 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1689 refungible: {1690 pieces: data.pieces,1691 properties: data.properties,1692 },1693 }],1694 true,1695 );1696 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1697 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1698 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1699 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1700 }17011702 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1703 throw Error('Not implemented');1704 const creationResult = await this.helper.executeExtrinsic(1705 signer,1706 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1707 true, // `Unable to mint RFT tokens for ${label}`,1708 );1709 const collection = this.getCollectionObject(collectionId);1710 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1711 }17121713 /**1714 * Mint multiple RFT tokens with one owner1715 * @param signer keyring of signer1716 * @param collectionId ID of collection1717 * @param owner tokens owner1718 * @param tokens array of tokens with properties and pieces1719 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1720 * @returns array of newly created RFT tokens1721 */1722 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1723 const rawTokens = [];1724 for (const token of tokens) {1725 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1726 rawTokens.push(raw);1727 }1728 const creationResult = await this.helper.executeExtrinsic(1729 signer,1730 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1731 true,1732 );1733 const collection = this.getCollectionObject(collectionId);1734 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1735 }17361737 /**1738 * Destroys a concrete instance of RFT.1739 * @param signer keyring of signer1740 * @param collectionId ID of collection1741 * @param tokenId ID of token1742 * @param amount number of pieces to be burnt1743 * @example burnToken(aliceKeyring, 10, 5);1744 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1745 */1746 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1747 return await super.burnToken(signer, collectionId, tokenId, amount);1748 }17491750 /**1751 * Destroys a concrete instance of RFT on behalf of the owner.1752 * @param signer keyring of signer1753 * @param collectionId ID of collection1754 * @param tokenId ID of token1755 * @param fromAddressObj address on behalf of which the token will be burnt1756 * @param amount number of pieces to be burnt1757 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1758 * @returns ```true``` if extrinsic success, otherwise ```false```1759 */1760 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1761 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1762 }17631764 /**1765 * Set, change, or remove approved address to transfer the ownership of the RFT.1766 *1767 * @param signer keyring of signer1768 * @param collectionId ID of collection1769 * @param tokenId ID of token1770 * @param toAddressObj address to approve1771 * @param amount number of pieces to be approved1772 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1773 * @returns true if the token success, otherwise false1774 */1775 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1776 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1777 }17781779 /**1780 * Get total number of pieces1781 * @param collectionId ID of collection1782 * @param tokenId ID of token1783 * @example getTokenTotalPieces(10, 5);1784 * @returns number of pieces1785 */1786 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1787 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1788 }17891790 /**1791 * Change number of token pieces. Signer must be the owner of all token pieces.1792 * @param signer keyring of signer1793 * @param collectionId ID of collection1794 * @param tokenId ID of token1795 * @param amount new number of pieces1796 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1797 * @returns true if the repartion was success, otherwise false1798 */1799 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1800 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1801 const repartitionResult = await this.helper.executeExtrinsic(1802 signer,1803 'api.tx.unique.repartition', [collectionId, tokenId, amount],1804 true,1805 );1806 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1807 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1808 }1809}181018111812class FTGroup extends CollectionGroup {1813 /**1814 * Get collection object1815 * @param collectionId ID of collection1816 * @example getCollectionObject(2);1817 * @returns instance of UniqueFTCollection1818 */1819 getCollectionObject(collectionId: number): UniqueFTCollection {1820 return new UniqueFTCollection(collectionId, this.helper);1821 }18221823 /**1824 * Mint new fungible collection1825 * @param signer keyring of signer1826 * @param collectionOptions Collection options1827 * @param decimalPoints number of token decimals1828 * @example1829 * mintCollection(aliceKeyring, {1830 * name: 'New',1831 * description: 'New collection',1832 * tokenPrefix: 'NEW',1833 * }, 18)1834 * @returns newly created fungible collection1835 */1836 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1837 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1838 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1839 collectionOptions.mode = {fungible: decimalPoints};1840 for (const key of ['name', 'description', 'tokenPrefix']) {1841 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);1842 }1843 const creationResult = await this.helper.executeExtrinsic(1844 signer,1845 'api.tx.unique.createCollectionEx', [collectionOptions],1846 true,1847 );1848 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1849 }18501851 /**1852 * Mint tokens1853 * @param signer keyring of signer1854 * @param collectionId ID of collection1855 * @param owner address owner of new tokens1856 * @param amount amount of tokens to be meanted1857 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1858 * @returns ```true``` if extrinsic success, otherwise ```false```1859 */1860 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1861 const creationResult = await this.helper.executeExtrinsic(1862 signer,1863 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1864 fungible: {1865 value: amount,1866 },1867 }],1868 true, // `Unable to mint fungible tokens for ${label}`,1869 );1870 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1871 }18721873 /**1874 * Mint multiple Fungible tokens with one owner1875 * @param signer keyring of signer1876 * @param collectionId ID of collection1877 * @param owner tokens owner1878 * @param tokens array of tokens with properties and pieces1879 * @returns ```true``` if extrinsic success, otherwise ```false```1880 */1881 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1882 const rawTokens = [];1883 for (const token of tokens) {1884 const raw = {Fungible: {Value: token.value}};1885 rawTokens.push(raw);1886 }1887 const creationResult = await this.helper.executeExtrinsic(1888 signer,1889 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1890 true,1891 );1892 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1893 }18941895 /**1896 * Get the top 10 owners with the largest balance for the Fungible collection1897 * @param collectionId ID of collection1898 * @example getTop10Owners(10);1899 * @returns array of ```ICrossAccountId```1900 */1901 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1902 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1903 }19041905 /**1906 * Get account balance1907 * @param collectionId ID of collection1908 * @param addressObj address of owner1909 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1910 * @returns amount of fungible tokens owned by address1911 */1912 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1913 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1914 }19151916 /**1917 * Transfer tokens to address1918 * @param signer keyring of signer1919 * @param collectionId ID of collection1920 * @param toAddressObj address recipient1921 * @param amount amount of tokens to be sent1922 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1923 * @returns ```true``` if extrinsic success, otherwise ```false```1924 */1925 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1926 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1927 }19281929 /**1930 * Transfer some tokens on behalf of the owner.1931 * @param signer keyring of signer1932 * @param collectionId ID of collection1933 * @param fromAddressObj address on behalf of which tokens will be sent1934 * @param toAddressObj address where token to be sent1935 * @param amount number of tokens to be sent1936 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1937 * @returns ```true``` if extrinsic success, otherwise ```false```1938 */1939 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1940 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1941 }19421943 /**1944 * Destroy some amount of tokens1945 * @param signer keyring of signer1946 * @param collectionId ID of collection1947 * @param amount amount of tokens to be destroyed1948 * @example burnTokens(aliceKeyring, 10, 1000n);1949 * @returns ```true``` if extrinsic success, otherwise ```false```1950 */1951 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1952 return await super.burnToken(signer, collectionId, 0, amount);1953 }19541955 /**1956 * Burn some tokens on behalf of the owner.1957 * @param signer keyring of signer1958 * @param collectionId ID of collection1959 * @param fromAddressObj address on behalf of which tokens will be burnt1960 * @param amount amount of tokens to be burnt1961 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1962 * @returns ```true``` if extrinsic success, otherwise ```false```1963 */1964 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1965 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);1966 }19671968 /**1969 * Get total collection supply1970 * @param collectionId1971 * @returns1972 */1973 async getTotalPieces(collectionId: number): Promise<bigint> {1974 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1975 }19761977 /**1978 * Set, change, or remove approved address to transfer tokens.1979 *1980 * @param signer keyring of signer1981 * @param collectionId ID of collection1982 * @param toAddressObj address to be approved1983 * @param amount amount of tokens to be approved1984 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1985 * @returns ```true``` if extrinsic success, otherwise ```false```1986 */1987 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1988 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1989 }19901991 /**1992 * Get amount of fungible tokens approved to transfer1993 * @param collectionId ID of collection1994 * @param fromAddressObj owner of tokens1995 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1996 * @returns number of tokens approved for the transfer1997 */1998 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1999 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2000 }2001}200220032004class ChainGroup extends HelperGroup {2005 /**2006 * Get system properties of a chain2007 * @example getChainProperties();2008 * @returns ss58Format, token decimals, and token symbol2009 */2010 getChainProperties(): IChainProperties {2011 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2012 return {2013 ss58Format: properties.ss58Format.toJSON(),2014 tokenDecimals: properties.tokenDecimals.toJSON(),2015 tokenSymbol: properties.tokenSymbol.toJSON(),2016 };2017 }20182019 /**2020 * Get chain header2021 * @example getLatestBlockNumber();2022 * @returns the number of the last block2023 */2024 async getLatestBlockNumber(): Promise<number> {2025 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2026 }20272028 /**2029 * Get block hash by block number2030 * @param blockNumber number of block2031 * @example getBlockHashByNumber(12345);2032 * @returns hash of a block2033 */2034 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2035 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2036 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2037 return blockHash;2038 }20392040 // TODO add docs2041 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2042 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2043 if (!blockHash) return null;2044 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2045 }20462047 /**2048 * Get account nonce2049 * @param address substrate address2050 * @example getNonce("5GrwvaEF5zXb26Fz...");2051 * @returns number, account's nonce2052 */2053 async getNonce(address: TSubstrateAccount): Promise<number> {2054 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2055 }2056}205720582059class BalanceGroup extends HelperGroup {2060 getCollectionCreationPrice(): bigint {2061 return 2n * this.helper.balance.getOneTokenNominal();2062 }2063 /**2064 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2065 * @example getOneTokenNominal()2066 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2067 */2068 getOneTokenNominal(): bigint {2069 const chainProperties = this.helper.chain.getChainProperties();2070 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2071 }20722073 /**2074 * Get substrate address balance2075 * @param address substrate address2076 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2077 * @returns amount of tokens on address2078 */2079 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2080 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2081 }20822083 /**2084 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2085 * @param address substrate address2086 * @returns2087 */2088 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2089 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2090 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2091 }20922093 /**2094 * Get ethereum address balance2095 * @param address ethereum address2096 * @example getEthereum("0x9F0583DbB855d...")2097 * @returns amount of tokens on address2098 */2099 async getEthereum(address: TEthereumAccount): Promise<bigint> {2100 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2101 }21022103 /**2104 * Transfer tokens to substrate address2105 * @param signer keyring of signer2106 * @param address substrate address of a recipient2107 * @param amount amount of tokens to be transfered2108 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2109 * @returns ```true``` if extrinsic success, otherwise ```false```2110 */2111 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2112 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}`*/);21132114 let transfer = {from: null, to: null, amount: 0n} as any;2115 result.result.events.forEach(({event: {data, method, section}}) => {2116 if ((section === 'balances') && (method === 'Transfer')) {2117 transfer = {2118 from: this.helper.address.normalizeSubstrate(data[0]),2119 to: this.helper.address.normalizeSubstrate(data[1]),2120 amount: BigInt(data[2]),2121 };2122 }2123 });2124 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2125 && this.helper.address.normalizeSubstrate(address) === transfer.to 2126 && BigInt(amount) === transfer.amount;2127 return isSuccess;2128 }2129}213021312132class AddressGroup extends HelperGroup {2133 /**2134 * Normalizes the address to the specified ss58 format, by default ```42```.2135 * @param address substrate address2136 * @param ss58Format format for address conversion, by default ```42```2137 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2138 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2139 */2140 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2141 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2142 }21432144 /**2145 * Get address in the connected chain format2146 * @param address substrate address2147 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2148 * @returns address in chain format2149 */2150 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2151 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2152 }21532154 /**2155 * Get substrate mirror of an ethereum address2156 * @param ethAddress ethereum address2157 * @param toChainFormat false for normalized account2158 * @example ethToSubstrate('0x9F0583DbB855d...')2159 * @returns substrate mirror of a provided ethereum address2160 */2161 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2162 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2163 }21642165 /**2166 * Get ethereum mirror of a substrate address2167 * @param subAddress substrate account2168 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2169 * @returns ethereum mirror of a provided substrate address2170 */2171 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2172 return CrossAccountId.translateSubToEth(subAddress);2173 }2174}21752176class StakingGroup extends HelperGroup {2177 /**2178 * Stake tokens for App Promotion2179 * @param signer keyring of signer2180 * @param amountToStake amount of tokens to stake2181 * @param label extra label for log2182 * @returns2183 */2184 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2185 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2186 const _stakeResult = await this.helper.executeExtrinsic(2187 signer, 'api.tx.appPromotion.stake',2188 [amountToStake], true,2189 );2190 // TODO extract info from stakeResult2191 return true;2192 }21932194 /**2195 * Unstake tokens for App Promotion2196 * @param signer keyring of signer2197 * @param amountToUnstake amount of tokens to unstake2198 * @param label extra label for log2199 * @returns block number where balances will be unlocked2200 */2201 async unstake(signer: TSigner, label?: string): Promise<number> {2202 if(typeof label === 'undefined') label = `${signer.address}`;2203 const _unstakeResult = await this.helper.executeExtrinsic(2204 signer, 'api.tx.appPromotion.unstake',2205 [], true,2206 );2207 // TODO extract block number fron events2208 return 1;2209 }22102211 /**2212 * Get total staked amount for address2213 * @param address substrate or ethereum address2214 * @returns total staked amount2215 */2216 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2217 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2218 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2219 }22202221 /**2222 * Get total staked per block2223 * @param address substrate or ethereum address2224 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2225 */2226 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2227 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2228 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2229 return { 2230 block: block.toBigInt(),2231 amount: amount.toBigInt(),2232 };2233 });2234 }22352236 /**2237 * Get total pending unstake amount for address2238 * @param address substrate or ethereum address2239 * @returns total pending unstake amount2240 */2241 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2242 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2243 }22442245 /**2246 * Get pending unstake amount per block for address2247 * @param address substrate or ethereum address2248 * @returns array of pending stakes. `block` – the number of the block in which the unstake was made. `amount` - the number of tokens unstaked in the block2249 */2250 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2251 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2252 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2253 return {2254 block: block.toBigInt(),2255 amount: amount.toBigInt(),2256 };2257 });2258 return result;2259 }2260}22612262class SchedulerGroup extends HelperGroup {2263 constructor(helper: UniqueHelper) {2264 super(helper);2265 }22662267 async cancelScheduled(signer: TSigner, scheduledId: string) {2268 return this.helper.executeExtrinsic(2269 signer,2270 'api.tx.scheduler.cancelNamed',2271 [scheduledId],2272 true,2273 );2274 }22752276 async changePriority(signer: TSigner, scheduledId: string, priority: number) {2277 return this.helper.executeExtrinsic(2278 signer,2279 'api.tx.scheduler.changeNamedPriority',2280 [scheduledId, priority],2281 true,2282 );2283 }22842285 scheduleAt<T extends UniqueHelper>(2286 scheduledId: string,2287 executionBlockNumber: number,2288 options: ISchedulerOptions = {},2289 ) {2290 return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2291 }22922293 scheduleAfter<T extends UniqueHelper>(2294 scheduledId: string,2295 blocksBeforeExecution: number,2296 options: ISchedulerOptions = {},2297 ) {2298 return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2299 }23002301 schedule<T extends UniqueHelper>(2302 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2303 scheduledId: string,2304 blocksNum: number,2305 options: ISchedulerOptions = {},2306 ) {2307 // eslint-disable-next-line @typescript-eslint/naming-convention2308 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2309 return this.helper.clone(ScheduledHelperType, {2310 scheduleFn,2311 scheduledId,2312 blocksNum,2313 options,2314 }) as T;2315 }2316}23172318export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;23192320export class UniqueHelper extends ChainHelperBase {2321 helperBase: any;23222323 chain: ChainGroup;2324 balance: BalanceGroup;2325 address: AddressGroup;2326 collection: CollectionGroup;2327 nft: NFTGroup;2328 rft: RFTGroup;2329 ft: FTGroup;2330 staking: StakingGroup;2331 scheduler: SchedulerGroup;23322333 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2334 super(logger);23352336 this.helperBase = options.helperBase ?? UniqueHelper;23372338 this.chain = new ChainGroup(this);2339 this.balance = new BalanceGroup(this);2340 this.address = new AddressGroup(this);2341 this.collection = new CollectionGroup(this);2342 this.nft = new NFTGroup(this);2343 this.rft = new RFTGroup(this);2344 this.ft = new FTGroup(this);2345 this.staking = new StakingGroup(this);2346 this.scheduler = new SchedulerGroup(this);2347 }23482349 clone(helperCls: UniqueHelperConstructor, options: {[key: string]: any} = {}) {2350 Object.setPrototypeOf(helperCls.prototype, this);2351 const newHelper = new helperCls(this.logger, options);23522353 newHelper.api = this.api;2354 newHelper.network = this.network;2355 newHelper.forceNetwork = this.forceNetwork;23562357 this.children.push(newHelper);23582359 return newHelper;2360 }23612362 getSudo<T extends UniqueHelper>() {2363 // eslint-disable-next-line @typescript-eslint/naming-convention2364 const SudoHelperType = SudoUniqueHelper(this.helperBase);2365 return this.clone(SudoHelperType) as T;2366 }2367}23682369// eslint-disable-next-line @typescript-eslint/naming-convention2370function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2371 return class extends Base {2372 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2373 scheduledId: string;2374 blocksNum: number;2375 options: ISchedulerOptions;23762377 constructor(...args: any[]) {2378 const logger = args[0] as ILogger;2379 const options = args[1] as {2380 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2381 scheduledId: string,2382 blocksNum: number,2383 options: ISchedulerOptions2384 };23852386 super(logger);23872388 this.scheduleFn = options.scheduleFn;2389 this.scheduledId = options.scheduledId;2390 this.blocksNum = options.blocksNum;2391 this.options = options.options;2392 }23932394 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2395 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2396 const extrinsic = 'api.tx.scheduler.' + this.scheduleFn;23972398 return super.executeExtrinsic(2399 sender,2400 extrinsic,2401 [2402 this.scheduledId,2403 this.blocksNum,2404 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2405 this.options.priority ?? null,2406 {Value: scheduledTx},2407 ],2408 expectSuccess,2409 );2410 }2411 };2412}24132414// eslint-disable-next-line @typescript-eslint/naming-convention2415function SudoUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2416 return class extends Base {2417 constructor(...args: any[]) {2418 super(...args);2419 }24202421 executeExtrinsic (2422 sender: IKeyringPair,2423 extrinsic: string,2424 params: any[],2425 expectSuccess?: boolean,2426 ): Promise<ITransactionResult> {2427 const call = this.constructApiCall(extrinsic, params);24282429 return super.executeExtrinsic(2430 sender,2431 'api.tx.sudo.sudo',2432 [call],2433 expectSuccess,2434 );2435 }2436 };2437}24382439export class UniqueBaseCollection {2440 helper: UniqueHelper;2441 collectionId: number;24422443 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2444 this.collectionId = collectionId;2445 this.helper = uniqueHelper;2446 }24472448 async getData() {2449 return await this.helper.collection.getData(this.collectionId);2450 }24512452 async getLastTokenId() {2453 return await this.helper.collection.getLastTokenId(this.collectionId);2454 }24552456 async doesTokenExist(tokenId: number) {2457 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2458 }24592460 async getAdmins() {2461 return await this.helper.collection.getAdmins(this.collectionId);2462 }24632464 async getAllowList() {2465 return await this.helper.collection.getAllowList(this.collectionId);2466 }24672468 async getEffectiveLimits() {2469 return await this.helper.collection.getEffectiveLimits(this.collectionId);2470 }24712472 async getProperties(propertyKeys?: string[] | null) {2473 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2474 }24752476 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2477 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2478 }24792480 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2481 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2482 }24832484 async confirmSponsorship(signer: TSigner) {2485 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2486 }24872488 async removeSponsor(signer: TSigner) {2489 return await this.helper.collection.removeSponsor(signer, this.collectionId);2490 }24912492 async setLimits(signer: TSigner, limits: ICollectionLimits) {2493 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2494 }24952496 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2497 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2498 }24992500 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2501 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2502 }25032504 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2505 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2506 }25072508 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2509 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2510 }25112512 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2513 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2514 }25152516 async setProperties(signer: TSigner, properties: IProperty[]) {2517 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2518 }25192520 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2521 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2522 }25232524 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2525 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2526 }25272528 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2529 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2530 }25312532 async disableNesting(signer: TSigner) {2533 return await this.helper.collection.disableNesting(signer, this.collectionId);2534 }25352536 async burn(signer: TSigner) {2537 return await this.helper.collection.burn(signer, this.collectionId);2538 }25392540 scheduleAt<T extends UniqueHelper>(2541 scheduledId: string,2542 executionBlockNumber: number,2543 options: ISchedulerOptions = {},2544 ) {2545 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2546 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2547 }25482549 scheduleAfter<T extends UniqueHelper>(2550 scheduledId: string,2551 blocksBeforeExecution: number,2552 options: ISchedulerOptions = {},2553 ) {2554 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2555 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2556 }25572558 getSudo<T extends UniqueHelper>() {2559 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2560 }2561}256225632564export class UniqueNFTCollection extends UniqueBaseCollection {2565 getTokenObject(tokenId: number) {2566 return new UniqueNFToken(tokenId, this);2567 }25682569 async getTokensByAddress(addressObj: ICrossAccountId) {2570 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2571 }25722573 async getToken(tokenId: number, blockHashAt?: string) {2574 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2575 }25762577 async getTokenOwner(tokenId: number, blockHashAt?: string) {2578 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2579 }25802581 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2582 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2583 }25842585 async getTokenChildren(tokenId: number, blockHashAt?: string) {2586 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2587 }25882589 async getPropertyPermissions(propertyKeys: string[] | null = null) {2590 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2591 }25922593 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2594 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2595 }25962597 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2598 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2599 }26002601 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2602 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2603 }26042605 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2606 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2607 }26082609 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2610 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2611 }26122613 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2614 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2615 }26162617 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2618 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2619 }26202621 async burnToken(signer: TSigner, tokenId: number) {2622 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2623 }26242625 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2626 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2627 }26282629 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2630 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2631 }26322633 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2634 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2635 }26362637 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2638 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2639 }26402641 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2642 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2643 }26442645 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2646 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2647 }26482649 scheduleAt<T extends UniqueHelper>(2650 scheduledId: string,2651 executionBlockNumber: number,2652 options: ISchedulerOptions = {},2653 ) {2654 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2655 return new UniqueNFTCollection(this.collectionId, scheduledHelper);2656 }26572658 scheduleAfter<T extends UniqueHelper>(2659 scheduledId: string,2660 blocksBeforeExecution: number,2661 options: ISchedulerOptions = {},2662 ) {2663 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2664 return new UniqueNFTCollection(this.collectionId, scheduledHelper);2665 }26662667 getSudo<T extends UniqueHelper>() {2668 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());2669 }2670}267126722673export class UniqueRFTCollection extends UniqueBaseCollection {2674 getTokenObject(tokenId: number) {2675 return new UniqueRFToken(tokenId, this);2676 }26772678 async getToken(tokenId: number, blockHashAt?: string) {2679 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);2680 }26812682 async getTokensByAddress(addressObj: ICrossAccountId) {2683 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2684 }26852686 async getTop10TokenOwners(tokenId: number) {2687 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2688 }26892690 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2691 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2692 }26932694 async getTokenTotalPieces(tokenId: number) {2695 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2696 }26972698 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2699 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2700 }27012702 async getPropertyPermissions(propertyKeys: string[] | null = null) {2703 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);2704 }27052706 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2707 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2708 }27092710 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2711 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2712 }27132714 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2715 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2716 }27172718 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2719 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2720 }27212722 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2723 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2724 }27252726 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2727 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2728 }27292730 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2731 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2732 }27332734 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2735 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2736 }27372738 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {2739 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);2740 }27412742 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2743 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2744 }27452746 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2747 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2748 }27492750 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2751 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2752 }27532754 scheduleAt<T extends UniqueHelper>(2755 scheduledId: string,2756 executionBlockNumber: number,2757 options: ISchedulerOptions = {},2758 ) {2759 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2760 return new UniqueRFTCollection(this.collectionId, scheduledHelper);2761 }27622763 scheduleAfter<T extends UniqueHelper>(2764 scheduledId: string,2765 blocksBeforeExecution: number,2766 options: ISchedulerOptions = {},2767 ) {2768 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2769 return new UniqueRFTCollection(this.collectionId, scheduledHelper);2770 }27712772 getSudo<T extends UniqueHelper>() {2773 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());2774 }2775}277627772778export class UniqueFTCollection extends UniqueBaseCollection {2779 async getBalance(addressObj: ICrossAccountId) {2780 return await this.helper.ft.getBalance(this.collectionId, addressObj);2781 }27822783 async getTotalPieces() {2784 return await this.helper.ft.getTotalPieces(this.collectionId);2785 }27862787 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2788 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2789 }27902791 async getTop10Owners() {2792 return await this.helper.ft.getTop10Owners(this.collectionId);2793 }27942795 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2796 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2797 }27982799 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2800 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2801 }28022803 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2804 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2805 }28062807 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2808 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2809 }28102811 async burnTokens(signer: TSigner, amount=1n) {2812 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2813 }28142815 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2816 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2817 }28182819 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2820 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2821 }28222823 scheduleAt<T extends UniqueHelper>(2824 scheduledId: string,2825 executionBlockNumber: number,2826 options: ISchedulerOptions = {},2827 ) {2828 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2829 return new UniqueFTCollection(this.collectionId, scheduledHelper);2830 }28312832 scheduleAfter<T extends UniqueHelper>(2833 scheduledId: string,2834 blocksBeforeExecution: number,2835 options: ISchedulerOptions = {},2836 ) {2837 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2838 return new UniqueFTCollection(this.collectionId, scheduledHelper);2839 }28402841 getSudo<T extends UniqueHelper>() {2842 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());2843 }2844}284528462847export class UniqueBaseToken {2848 collection: UniqueNFTCollection | UniqueRFTCollection;2849 collectionId: number;2850 tokenId: number;28512852 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2853 this.collection = collection;2854 this.collectionId = collection.collectionId;2855 this.tokenId = tokenId;2856 }28572858 async getNextSponsored(addressObj: ICrossAccountId) {2859 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2860 }28612862 async getProperties(propertyKeys?: string[] | null) {2863 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);2864 }28652866 async setProperties(signer: TSigner, properties: IProperty[]) {2867 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2868 }28692870 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2871 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2872 }28732874 async doesExist() {2875 return await this.collection.doesTokenExist(this.tokenId);2876 }28772878 nestingAccount() {2879 return this.collection.helper.util.getTokenAccount(this);2880 }28812882 scheduleAt<T extends UniqueHelper>(2883 scheduledId: string,2884 executionBlockNumber: number,2885 options: ISchedulerOptions = {},2886 ) {2887 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);2888 return new UniqueBaseToken(this.tokenId, scheduledCollection);2889 }28902891 scheduleAfter<T extends UniqueHelper>(2892 scheduledId: string,2893 blocksBeforeExecution: number,2894 options: ISchedulerOptions = {},2895 ) {2896 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2897 return new UniqueBaseToken(this.tokenId, scheduledCollection);2898 }28992900 getSudo<T extends UniqueHelper>() {2901 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());2902 }2903}290429052906export class UniqueNFToken extends UniqueBaseToken {2907 collection: UniqueNFTCollection;29082909 constructor(tokenId: number, collection: UniqueNFTCollection) {2910 super(tokenId, collection);2911 this.collection = collection;2912 }29132914 async getData(blockHashAt?: string) {2915 return await this.collection.getToken(this.tokenId, blockHashAt);2916 }29172918 async getOwner(blockHashAt?: string) {2919 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2920 }29212922 async getTopmostOwner(blockHashAt?: string) {2923 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2924 }29252926 async getChildren(blockHashAt?: string) {2927 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2928 }29292930 async nest(signer: TSigner, toTokenObj: IToken) {2931 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2932 }29332934 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2935 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2936 }29372938 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2939 return await this.collection.transferToken(signer, this.tokenId, addressObj);2940 }29412942 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2943 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2944 }29452946 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2947 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2948 }29492950 async isApproved(toAddressObj: ICrossAccountId) {2951 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2952 }29532954 async burn(signer: TSigner) {2955 return await this.collection.burnToken(signer, this.tokenId);2956 }29572958 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {2959 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);2960 }29612962 scheduleAt<T extends UniqueHelper>(2963 scheduledId: string,2964 executionBlockNumber: number,2965 options: ISchedulerOptions = {},2966 ) {2967 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);2968 return new UniqueNFToken(this.tokenId, scheduledCollection);2969 }29702971 scheduleAfter<T extends UniqueHelper>(2972 scheduledId: string,2973 blocksBeforeExecution: number,2974 options: ISchedulerOptions = {},2975 ) {2976 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2977 return new UniqueNFToken(this.tokenId, scheduledCollection);2978 }29792980 getSudo<T extends UniqueHelper>() {2981 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());2982 }2983}29842985export class UniqueRFToken extends UniqueBaseToken {2986 collection: UniqueRFTCollection;29872988 constructor(tokenId: number, collection: UniqueRFTCollection) {2989 super(tokenId, collection);2990 this.collection = collection;2991 }29922993 async getData(blockHashAt?: string) {2994 return await this.collection.getToken(this.tokenId, blockHashAt);2995 }29962997 async getTop10Owners() {2998 return await this.collection.getTop10TokenOwners(this.tokenId);2999 }30003001 async getBalance(addressObj: ICrossAccountId) {3002 return await this.collection.getTokenBalance(this.tokenId, addressObj);3003 }30043005 async getTotalPieces() {3006 return await this.collection.getTokenTotalPieces(this.tokenId);3007 }30083009 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3010 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3011 }30123013 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3014 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3015 }30163017 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3018 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3019 }30203021 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3022 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3023 }30243025 async repartition(signer: TSigner, amount: bigint) {3026 return await this.collection.repartitionToken(signer, this.tokenId, amount);3027 }30283029 async burn(signer: TSigner, amount=1n) {3030 return await this.collection.burnToken(signer, this.tokenId, amount);3031 }30323033 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3034 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3035 }30363037 scheduleAt<T extends UniqueHelper>(3038 scheduledId: string,3039 executionBlockNumber: number,3040 options: ISchedulerOptions = {},3041 ) {3042 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3043 return new UniqueRFToken(this.tokenId, scheduledCollection);3044 }30453046 scheduleAfter<T extends UniqueHelper>(3047 scheduledId: string,3048 blocksBeforeExecution: number,3049 options: ISchedulerOptions = {},3050 ) {3051 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3052 return new UniqueRFToken(this.tokenId, scheduledCollection);3053 }30543055 getSudo<T extends UniqueHelper>() {3056 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3057 }3058}