difftreelog
feat use mixins for sudo/scheduler helpers
in: master
5 files changed
tests/src/eth/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/types.ts
+++ b/tests/src/eth/util/playgrounds/types.ts
@@ -1,3 +1,5 @@
+import {EthUniqueHelper} from './unique.dev';
+
export interface ContractImports {
solPath: string;
fsPath: string;
@@ -13,3 +15,5 @@
event: string,
args: { [key: string]: string }
};
+
+export type EthUniqueHelperConstructor = new (...args: any[]) => EthUniqueHelper;
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
@@ -18,7 +18,7 @@
import {DevUniqueHelper} from '../../../util/playgrounds/unique.dev';
-import {ContractImports, CompiledContract, NormalizedEvent} from './types';
+import {ContractImports, CompiledContract, NormalizedEvent, EthUniqueHelperConstructor} from './types';
// Native contracts ABI
import collectionHelpersAbi from '../../collectionHelpersAbi.json';
@@ -340,7 +340,6 @@
return '0x' + address.substring(address.length - 40);
}
}
-
export type EthUniqueHelperConstructor = new (...args: any[]) => EthUniqueHelper;
export class EthUniqueHelper extends DevUniqueHelper {
tests/src/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import {IKeyringPair} from '@polkadot/types/types';
+import {UniqueHelper} from './unique';
export interface IEvent {
section: string;
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -11,6 +11,7 @@
import {ICrossAccountId} from './types';
import {FrameSystemEventRecord} from '@polkadot/types/lookup';
import {VoidFn} from '@polkadot/api/types';
+import {FrameSystemEventRecord} from '@polkadot/types/lookup';
export class SilentLogger {
log(_msg: any, _level: any): void { }
@@ -496,13 +497,13 @@
async startCapture() {
this.stopCapture();
- this.unsubscribe = await this.helper.getApi().query.system.events(eventRecords => {
+ this.unsubscribe = (await this.helper.getApi().query.system.events((eventRecords: FrameSystemEventRecord[]) => {
const newEvents = eventRecords.filter(r => {
return r.event.section == this.eventSection && r.event.method == this.eventMethod;
});
this.events.push(...newEvents);
- });
+ })) as any;
}
stopCapture() {
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, ISchedulerOptions, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, IForeignAssetMetadata, TNetworks, MoonbeamAssetInfo, DemocracyStandardAccountVote, AcalaAssetMetadata} 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 }256257 static bigIntToDecimals(number: bigint, decimals = 18) {258 const numberStr = number.toString();259 const dotPos = numberStr.length - decimals;260 261 if (dotPos <= 0) {262 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;263 } else {264 const intPart = numberStr.substring(0, dotPos);265 const fractPart = numberStr.substring(dotPos);266 return intPart + '.' + fractPart;267 }268 }269}270271class UniqueEventHelper {272 private static extractIndex(index: any): [number, number] | string {273 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];274 return index.toJSON();275 }276277 private static extractSub(data: any, subTypes: any): {[key: string]: any} {278 let obj: any = {};279 let index = 0;280281 if (data.entries) {282 for(const [key, value] of data.entries()) {283 obj[key] = this.extractData(value, subTypes[index]);284 index++;285 }286 } else obj = data.toJSON();287288 return obj;289 }290 291 private static extractData(data: any, type: any): any {292 if(!type) return data.toHuman();293 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();294 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();295 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);296 return data.toHuman();297 }298299 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {300 const parsedEvents: IEvent[] = [];301302 events.forEach((record) => {303 const {event, phase} = record;304 const types = event.typeDef;305306 const eventData: IEvent = {307 section: event.section.toString(),308 method: event.method.toString(),309 index: this.extractIndex(event.index),310 data: [],311 phase: phase.toJSON(),312 };313314 event.data.forEach((val: any, index: number) => {315 eventData.data.push(this.extractData(val, types[index]));316 });317318 parsedEvents.push(eventData);319 });320321 return parsedEvents;322 }323}324325export class ChainHelperBase {326 helperBase: any;327328 transactionStatus = UniqueUtil.transactionStatus;329 chainLogType = UniqueUtil.chainLogType;330 util: typeof UniqueUtil;331 eventHelper: typeof UniqueEventHelper;332 logger: ILogger;333 api: ApiPromise | null;334 forcedNetwork: TNetworks | null;335 network: TNetworks | null;336 chainLog: IUniqueHelperLog[];337 children: ChainHelperBase[];338 address: AddressGroup;339 chain: ChainGroup;340341 constructor(logger?: ILogger, helperBase?: any) {342 this.helperBase = helperBase;343344 this.util = UniqueUtil;345 this.eventHelper = UniqueEventHelper;346 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();347 this.logger = logger;348 this.api = null;349 this.forcedNetwork = null;350 this.network = null;351 this.chainLog = [];352 this.children = [];353 this.address = new AddressGroup(this);354 this.chain = new ChainGroup(this);355 }356357 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {358 Object.setPrototypeOf(helperCls.prototype, this);359 const newHelper = new helperCls(this.logger, options);360361 newHelper.api = this.api;362 newHelper.network = this.network;363 newHelper.forceNetwork = this.forceNetwork;364365 this.children.push(newHelper);366367 return newHelper;368 }369370 getApi(): ApiPromise {371 if(this.api === null) throw Error('API not initialized');372 return this.api;373 }374375 clearChainLog(): void {376 this.chainLog = [];377 }378379 forceNetwork(value: TNetworks): void {380 this.forcedNetwork = value;381 }382383 async connect(wsEndpoint: string, listeners?: IApiListeners) {384 if (this.api !== null) throw Error('Already connected');385 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);386 this.api = api;387 this.network = network;388 }389390 async disconnect() {391 for (const child of this.children) {392 child.clearApi();393 }394395 if (this.api === null) return;396 await this.api.disconnect();397 this.clearApi();398 }399400 clearApi() {401 this.api = null;402 this.network = null;403 }404405 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {406 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;407 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];408409 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;410411 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;412 return 'opal';413 }414415 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {416 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});417 await api.isReady;418419 const network = await this.detectNetwork(api);420421 await api.disconnect();422423 return network;424 }425426 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{427 api: ApiPromise;428 network: TNetworks;429 }> {430 if(typeof network === 'undefined' || network === null) network = 'opal';431 const supportedRPC = {432 opal: {433 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,434 },435 quartz: {436 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,437 },438 unique: {439 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,440 },441 rococo: {},442 westend: {},443 moonbeam: {},444 moonriver: {},445 acala: {},446 karura: {},447 westmint: {},448 };449 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);450 const rpc = supportedRPC[network];451452 // TODO: investigate how to replace rpc in runtime453 // api._rpcCore.addUserInterfaces(rpc);454455 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});456457 await api.isReadyOrError;458459 if (typeof listeners === 'undefined') listeners = {};460 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {461 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;462 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);463 }464465 return {api, network};466 }467468 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {469 const {events, status} = data;470 if (status.isReady) {471 return this.transactionStatus.NOT_READY;472 }473 if (status.isBroadcast) {474 return this.transactionStatus.NOT_READY;475 }476 if (status.isInBlock || status.isFinalized) {477 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');478 if (errors.length > 0) {479 return this.transactionStatus.FAIL;480 }481 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {482 return this.transactionStatus.SUCCESS;483 }484 }485486 return this.transactionStatus.FAIL;487 }488489 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {490 const sign = (callback: any) => {491 if(options !== null) return transaction.signAndSend(sender, options, callback);492 return transaction.signAndSend(sender, callback);493 };494 // eslint-disable-next-line no-async-promise-executor495 return new Promise(async (resolve, reject) => {496 try {497 const unsub = await sign((result: any) => {498 const status = this.getTransactionStatus(result);499500 if (status === this.transactionStatus.SUCCESS) {501 this.logger.log(`${label} successful`);502 unsub();503 resolve({result, status});504 } else if (status === this.transactionStatus.FAIL) {505 let moduleError = null;506507 if (result.hasOwnProperty('dispatchError')) {508 const dispatchError = result['dispatchError'];509510 if (dispatchError) {511 if (dispatchError.isModule) {512 const modErr = dispatchError.asModule;513 const errorMeta = dispatchError.registry.findMetaError(modErr);514515 moduleError = `${errorMeta.section}.${errorMeta.name}`;516 } else {517 moduleError = dispatchError.toHuman();518 }519 } else {520 this.logger.log(result, this.logger.level.ERROR);521 }522 }523524 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);525 unsub();526 reject({status, moduleError, result});527 }528 });529 } catch (e) {530 this.logger.log(e, this.logger.level.ERROR);531 reject(e);532 }533 });534 }535536 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {537 const api = this.getApi();538 const signingInfo = await api.derive.tx.signingInfo(signer.address);539540 // We need to sign the tx because541 // unsigned transactions does not have an inclusion fee542 tx.sign(signer, {543 blockHash: api.genesisHash,544 genesisHash: api.genesisHash,545 runtimeVersion: api.runtimeVersion,546 nonce: signingInfo.nonce,547 });548549 if (len === null) {550 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;551 } else {552 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;553 }554 }555556 constructApiCall(apiCall: string, params: any[]) {557 if(this.api === null) throw Error('API not initialized');558 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);559 let call = this.getApi() as any;560 for(const part of apiCall.slice(4).split('.')) {561 call = call[part];562 }563 return call(...params);564 }565566 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {567 if(this.api === null) throw Error('API not initialized');568 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);569570 const startTime = (new Date()).getTime();571 let result: ITransactionResult;572 let events: IEvent[] = [];573 try {574 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;575 events = this.eventHelper.extractEvents(result.result.events);576 }577 catch(e) {578 if(!(e as object).hasOwnProperty('status')) throw e;579 result = e as ITransactionResult;580 }581582 const endTime = (new Date()).getTime();583584 const log = {585 executedAt: endTime,586 executionTime: endTime - startTime,587 type: this.chainLogType.EXTRINSIC,588 status: result.status,589 call: extrinsic,590 signer: this.getSignerAddress(sender),591 params,592 } as IUniqueHelperLog;593594 if(result.status !== this.transactionStatus.SUCCESS) {595 if (result.moduleError) log.moduleError = result.moduleError;596 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;597 }598 if(events.length > 0) log.events = events;599600 this.chainLog.push(log);601602 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {603 if (result.moduleError) throw Error(`${result.moduleError}`);604 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));605 }606 return result;607 }608609 async callRpc(rpc: string, params?: any[]) {610 if(typeof params === 'undefined') params = [];611 if(this.api === null) throw Error('API not initialized');612 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);613614 const startTime = (new Date()).getTime();615 let result;616 let error = null;617 const log = {618 type: this.chainLogType.RPC,619 call: rpc,620 params,621 } as IUniqueHelperLog;622623 try {624 result = await this.constructApiCall(rpc, params);625 }626 catch(e) {627 error = e;628 }629630 const endTime = (new Date()).getTime();631632 log.executedAt = endTime;633 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';634 log.executionTime = endTime - startTime;635636 this.chainLog.push(log);637638 if(error !== null) throw error;639640 return result;641 }642643 getSignerAddress(signer: IKeyringPair | string): string {644 if(typeof signer === 'string') return signer;645 return signer.address;646 }647648 fetchAllPalletNames(): string[] {649 if(this.api === null) throw Error('API not initialized');650 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());651 }652653 fetchMissingPalletNames(requiredPallets: string[]): string[] {654 const palletNames = this.fetchAllPalletNames();655 return requiredPallets.filter(p => !palletNames.includes(p));656 }657}658659660class HelperGroup<T extends ChainHelperBase> {661 helper: T;662663 constructor(uniqueHelper: T) {664 this.helper = uniqueHelper;665 }666}667668669class CollectionGroup extends HelperGroup<UniqueHelper> {670 /**671 * Get number of blocks when sponsored transaction is available.672 *673 * @param collectionId ID of collection674 * @param tokenId ID of token675 * @param addressObj address for which the sponsorship is checked676 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});677 * @returns number of blocks or null if sponsorship hasn't been set678 */679 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {680 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();681 }682683 /**684 * Get the number of created collections.685 *686 * @returns number of created collections687 */688 async getTotalCount(): Promise<number> {689 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();690 }691692 /**693 * Get information about the collection with additional data,694 * including the number of tokens it contains, its administrators,695 * the normalized address of the collection's owner, and decoded name and description.696 *697 * @param collectionId ID of collection698 * @example await getData(2)699 * @returns collection information object700 */701 async getData(collectionId: number): Promise<{702 id: number;703 name: string;704 description: string;705 tokensCount: number;706 admins: CrossAccountId[];707 normalizedOwner: TSubstrateAccount;708 raw: any709 } | null> {710 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);711 const humanCollection = collection.toHuman(), collectionData = {712 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],713 raw: humanCollection,714 } as any, jsonCollection = collection.toJSON();715 if (humanCollection === null) return null;716 collectionData.raw.limits = jsonCollection.limits;717 collectionData.raw.permissions = jsonCollection.permissions;718 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);719 for (const key of ['name', 'description']) {720 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);721 }722723 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))724 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)725 : 0;726 collectionData.admins = await this.getAdmins(collectionId);727728 return collectionData;729 }730731 /**732 * Get the addresses of the collection's administrators, optionally normalized.733 *734 * @param collectionId ID of collection735 * @param normalize whether to normalize the addresses to the default ss58 format736 * @example await getAdmins(1)737 * @returns array of administrators738 */739 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {740 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();741742 return normalize743 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())744 : admins;745 }746747 /**748 * Get the addresses added to the collection allow-list, optionally normalized.749 * @param collectionId ID of collection750 * @param normalize whether to normalize the addresses to the default ss58 format751 * @example await getAllowList(1)752 * @returns array of allow-listed addresses753 */754 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {755 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();756 return normalize757 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())758 : allowListed;759 }760761 /**762 * Get the effective limits of the collection instead of null for default values763 *764 * @param collectionId ID of collection765 * @example await getEffectiveLimits(2)766 * @returns object of collection limits767 */768 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {769 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();770 }771772 /**773 * Burns the collection if the signer has sufficient permissions and collection is empty.774 *775 * @param signer keyring of signer776 * @param collectionId ID of collection777 * @example await helper.collection.burn(aliceKeyring, 3);778 * @returns ```true``` if extrinsic success, otherwise ```false```779 */780 async burn(signer: TSigner, collectionId: number): Promise<boolean> {781 const result = await this.helper.executeExtrinsic(782 signer,783 'api.tx.unique.destroyCollection', [collectionId],784 true,785 );786787 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');788 }789790 /**791 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.792 *793 * @param signer keyring of signer794 * @param collectionId ID of collection795 * @param sponsorAddress Sponsor substrate address796 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")797 * @returns ```true``` if extrinsic success, otherwise ```false```798 */799 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {800 const result = await this.helper.executeExtrinsic(801 signer,802 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],803 true,804 );805806 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');807 }808809 /**810 * Confirms consent to sponsor the collection on behalf of the signer.811 *812 * @param signer keyring of signer813 * @param collectionId ID of collection814 * @example confirmSponsorship(aliceKeyring, 10)815 * @returns ```true``` if extrinsic success, otherwise ```false```816 */817 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {818 const result = await this.helper.executeExtrinsic(819 signer,820 'api.tx.unique.confirmSponsorship', [collectionId],821 true,822 );823824 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');825 }826827 /**828 * Removes the sponsor of a collection, regardless if it consented or not.829 *830 * @param signer keyring of signer831 * @param collectionId ID of collection832 * @example removeSponsor(aliceKeyring, 10)833 * @returns ```true``` if extrinsic success, otherwise ```false```834 */835 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {836 const result = await this.helper.executeExtrinsic(837 signer,838 'api.tx.unique.removeCollectionSponsor', [collectionId],839 true,840 );841842 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');843 }844845 /**846 * Sets the limits of the collection. At least one limit must be specified for a correct call.847 *848 * @param signer keyring of signer849 * @param collectionId ID of collection850 * @param limits collection limits object851 * @example852 * await setLimits(853 * aliceKeyring,854 * 10,855 * {856 * sponsorTransferTimeout: 0,857 * ownerCanDestroy: false858 * }859 * )860 * @returns ```true``` if extrinsic success, otherwise ```false```861 */862 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {863 const result = await this.helper.executeExtrinsic(864 signer,865 'api.tx.unique.setCollectionLimits', [collectionId, limits],866 true,867 );868869 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');870 }871872 /**873 * Changes the owner of the collection to the new Substrate address.874 *875 * @param signer keyring of signer876 * @param collectionId ID of collection877 * @param ownerAddress substrate address of new owner878 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")879 * @returns ```true``` if extrinsic success, otherwise ```false```880 */881 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {882 const result = await this.helper.executeExtrinsic(883 signer,884 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],885 true,886 );887888 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');889 }890891 /**892 * Adds a collection administrator.893 *894 * @param signer keyring of signer895 * @param collectionId ID of collection896 * @param adminAddressObj Administrator address (substrate or ethereum)897 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})898 * @returns ```true``` if extrinsic success, otherwise ```false```899 */900 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {901 const result = await this.helper.executeExtrinsic(902 signer,903 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],904 true,905 );906907 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');908 }909910 /**911 * Removes a collection administrator.912 *913 * @param signer keyring of signer914 * @param collectionId ID of collection915 * @param adminAddressObj Administrator address (substrate or ethereum)916 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})917 * @returns ```true``` if extrinsic success, otherwise ```false```918 */919 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {920 const result = await this.helper.executeExtrinsic(921 signer,922 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],923 true,924 );925926 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');927 }928929 /**930 * Check if user is in allow list.931 * 932 * @param collectionId ID of collection933 * @param user Account to check934 * @example await getAdmins(1)935 * @returns is user in allow list936 */937 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {938 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();939 }940941 /**942 * Adds an address to allow list943 * @param signer keyring of signer944 * @param collectionId ID of collection945 * @param addressObj address to add to the allow list946 * @returns ```true``` if extrinsic success, otherwise ```false```947 */948 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {949 const result = await this.helper.executeExtrinsic(950 signer,951 'api.tx.unique.addToAllowList', [collectionId, addressObj],952 true,953 );954955 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');956 }957958 /**959 * Removes an address from allow list960 *961 * @param signer keyring of signer962 * @param collectionId ID of collection963 * @param addressObj address to remove from the allow list964 * @returns ```true``` if extrinsic success, otherwise ```false```965 */966 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {967 const result = await this.helper.executeExtrinsic(968 signer,969 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],970 true,971 );972973 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');974 }975976 /**977 * Sets onchain permissions for selected collection.978 *979 * @param signer keyring of signer980 * @param collectionId ID of collection981 * @param permissions collection permissions object982 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});983 * @returns ```true``` if extrinsic success, otherwise ```false```984 */985 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {986 const result = await this.helper.executeExtrinsic(987 signer,988 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],989 true,990 );991992 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');993 }994995 /**996 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.997 *998 * @param signer keyring of signer999 * @param collectionId ID of collection1000 * @param permissions nesting permissions object1001 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1002 * @returns ```true``` if extrinsic success, otherwise ```false```1003 */1004 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1005 return await this.setPermissions(signer, collectionId, {nesting: permissions});1006 }10071008 /**1009 * Disables nesting for selected collection.1010 *1011 * @param signer keyring of signer1012 * @param collectionId ID of collection1013 * @example disableNesting(aliceKeyring, 10);1014 * @returns ```true``` if extrinsic success, otherwise ```false```1015 */1016 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1017 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1018 }10191020 /**1021 * Sets onchain properties to the collection.1022 *1023 * @param signer keyring of signer1024 * @param collectionId ID of collection1025 * @param properties array of property objects1026 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1027 * @returns ```true``` if extrinsic success, otherwise ```false```1028 */1029 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1030 const result = await this.helper.executeExtrinsic(1031 signer,1032 'api.tx.unique.setCollectionProperties', [collectionId, properties],1033 true,1034 );10351036 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1037 }10381039 /**1040 * Get collection properties.1041 * 1042 * @param collectionId ID of collection1043 * @param propertyKeys optionally filter the returned properties to only these keys1044 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1045 * @returns array of key-value pairs1046 */1047 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1048 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1049 }10501051 async getCollectionOptions(collectionId: number) {1052 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1053 }10541055 /**1056 * Deletes onchain properties from the collection.1057 *1058 * @param signer keyring of signer1059 * @param collectionId ID of collection1060 * @param propertyKeys array of property keys to delete1061 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1062 * @returns ```true``` if extrinsic success, otherwise ```false```1063 */1064 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1065 const result = await this.helper.executeExtrinsic(1066 signer,1067 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1068 true,1069 );10701071 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1072 }10731074 /**1075 * Changes the owner of the token.1076 *1077 * @param signer keyring of signer1078 * @param collectionId ID of collection1079 * @param tokenId ID of token1080 * @param addressObj address of a new owner1081 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1082 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1083 * @returns true if the token success, otherwise false1084 */1085 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1086 const result = await this.helper.executeExtrinsic(1087 signer,1088 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1089 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1090 );10911092 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1093 }10941095 /**1096 *1097 * Change ownership of a token(s) on behalf of the owner.1098 *1099 * @param signer keyring of signer1100 * @param collectionId ID of collection1101 * @param tokenId ID of token1102 * @param fromAddressObj address on behalf of which the token will be sent1103 * @param toAddressObj new token owner1104 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1105 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1106 * @returns true if the token success, otherwise false1107 */1108 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1109 const result = await this.helper.executeExtrinsic(1110 signer,1111 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1112 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1113 );1114 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1115 }11161117 /**1118 *1119 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1120 *1121 * @param signer keyring of signer1122 * @param collectionId ID of collection1123 * @param tokenId ID of token1124 * @param amount amount of tokens to be burned. For NFT must be set to 1n1125 * @example burnToken(aliceKeyring, 10, 5);1126 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1127 */1128 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1129 const burnResult = await this.helper.executeExtrinsic(1130 signer,1131 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1132 true, // `Unable to burn token for ${label}`,1133 );1134 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1135 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1136 return burnedTokens.success;1137 }11381139 /**1140 * Destroys a concrete instance of NFT on behalf of the owner1141 *1142 * @param signer keyring of signer1143 * @param collectionId ID of collection1144 * @param tokenId ID of token1145 * @param fromAddressObj address on behalf of which the token will be burnt1146 * @param amount amount of tokens to be burned. For NFT must be set to 1n1147 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1148 * @returns ```true``` if extrinsic success, otherwise ```false```1149 */1150 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1151 const burnResult = await this.helper.executeExtrinsic(1152 signer,1153 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1154 true, // `Unable to burn token from for ${label}`,1155 );1156 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1157 return burnedTokens.success && burnedTokens.tokens.length > 0;1158 }11591160 /**1161 * Set, change, or remove approved address to transfer the ownership of the NFT.1162 *1163 * @param signer keyring of signer1164 * @param collectionId ID of collection1165 * @param tokenId ID of token1166 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1167 * @param amount amount of token to be approved. For NFT must be set to 1n1168 * @returns ```true``` if extrinsic success, otherwise ```false```1169 */1170 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1171 const approveResult = await this.helper.executeExtrinsic(1172 signer,1173 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1174 true, // `Unable to approve token for ${label}`,1175 );11761177 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1178 }11791180 /**1181 * Get the amount of token pieces approved to transfer or burn. Normally 0.1182 *1183 * @param collectionId ID of collection1184 * @param tokenId ID of token1185 * @param toAccountObj address which is approved to use token pieces1186 * @param fromAccountObj address which may have allowed the use of its owned tokens1187 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1188 * @returns number of approved to transfer pieces1189 */1190 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1191 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1192 }11931194 /**1195 * Get the last created token ID in a collection1196 *1197 * @param collectionId ID of collection1198 * @example getLastTokenId(10);1199 * @returns id of the last created token1200 */1201 async getLastTokenId(collectionId: number): Promise<number> {1202 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1203 }12041205 /**1206 * Check if token exists1207 *1208 * @param collectionId ID of collection1209 * @param tokenId ID of token1210 * @example doesTokenExist(10, 20);1211 * @returns true if the token exists, otherwise false1212 */1213 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1214 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1215 }1216}12171218class NFTnRFT extends CollectionGroup {1219 /**1220 * Get tokens owned by account1221 *1222 * @param collectionId ID of collection1223 * @param addressObj tokens owner1224 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1225 * @returns array of token ids owned by account1226 */1227 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1228 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1229 }12301231 /**1232 * Get token data1233 *1234 * @param collectionId ID of collection1235 * @param tokenId ID of token1236 * @param propertyKeys optionally filter the token properties to only these keys1237 * @param blockHashAt optionally query the data at some block with this hash1238 * @example getToken(10, 5);1239 * @returns human readable token data1240 */1241 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1242 properties: IProperty[];1243 owner: CrossAccountId;1244 normalizedOwner: CrossAccountId;1245 }| null> {1246 let tokenData;1247 if(typeof blockHashAt === 'undefined') {1248 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1249 }1250 else {1251 if(propertyKeys.length == 0) {1252 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1253 if(!collection) return null;1254 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1255 }1256 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1257 }1258 tokenData = tokenData.toHuman();1259 if (tokenData === null || tokenData.owner === null) return null;1260 const owner = {} as any;1261 for (const key of Object.keys(tokenData.owner)) {1262 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1263 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1264 : tokenData.owner[key];1265 }1266 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1267 return tokenData;1268 }12691270 /**1271 * Set permissions to change token properties1272 *1273 * @param signer keyring of signer1274 * @param collectionId ID of collection1275 * @param permissions permissions to change a property by the collection admin or token owner1276 * @example setTokenPropertyPermissions(1277 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1278 * )1279 * @returns true if extrinsic success otherwise false1280 */1281 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1282 const result = await this.helper.executeExtrinsic(1283 signer,1284 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1285 true,1286 );12871288 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1289 }12901291 /**1292 * Get token property permissions.1293 * 1294 * @param collectionId ID of collection1295 * @param propertyKeys optionally filter the returned property permissions to only these keys1296 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1297 * @returns array of key-permission pairs1298 */1299 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1300 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1301 }13021303 /**1304 * Set token properties1305 *1306 * @param signer keyring of signer1307 * @param collectionId ID of collection1308 * @param tokenId ID of token1309 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1310 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1311 * @returns ```true``` if extrinsic success, otherwise ```false```1312 */1313 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1314 const result = await this.helper.executeExtrinsic(1315 signer,1316 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1317 true,1318 );13191320 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1321 }13221323 /**1324 * Get properties, metadata assigned to a token.1325 * 1326 * @param collectionId ID of collection1327 * @param tokenId ID of token1328 * @param propertyKeys optionally filter the returned properties to only these keys1329 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1330 * @returns array of key-value pairs1331 */1332 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1333 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1334 }13351336 /**1337 * Delete the provided properties of a token1338 * @param signer keyring of signer1339 * @param collectionId ID of collection1340 * @param tokenId ID of token1341 * @param propertyKeys property keys to be deleted1342 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1343 * @returns ```true``` if extrinsic success, otherwise ```false```1344 */1345 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1346 const result = await this.helper.executeExtrinsic(1347 signer,1348 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1349 true,1350 );13511352 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1353 }13541355 /**1356 * Mint new collection1357 *1358 * @param signer keyring of signer1359 * @param collectionOptions basic collection options and properties1360 * @param mode NFT or RFT type of a collection1361 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1362 * @returns object of the created collection1363 */1364 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1365 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1366 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1367 for (const key of ['name', 'description', 'tokenPrefix']) {1368 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);1369 }1370 const creationResult = await this.helper.executeExtrinsic(1371 signer,1372 'api.tx.unique.createCollectionEx', [collectionOptions],1373 true, // errorLabel,1374 );1375 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1376 }13771378 getCollectionObject(_collectionId: number): any {1379 return null;1380 }13811382 getTokenObject(_collectionId: number, _tokenId: number): any {1383 return null;1384 }1385}138613871388class NFTGroup extends NFTnRFT {1389 /**1390 * Get collection object1391 * @param collectionId ID of collection1392 * @example getCollectionObject(2);1393 * @returns instance of UniqueNFTCollection1394 */1395 getCollectionObject(collectionId: number): UniqueNFTCollection {1396 return new UniqueNFTCollection(collectionId, this.helper);1397 }13981399 /**1400 * Get token object1401 * @param collectionId ID of collection1402 * @param tokenId ID of token1403 * @example getTokenObject(10, 5);1404 * @returns instance of UniqueNFTToken1405 */1406 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1407 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1408 }14091410 /**1411 * Get token's owner1412 * @param collectionId ID of collection1413 * @param tokenId ID of token1414 * @param blockHashAt optionally query the data at the block with this hash1415 * @example getTokenOwner(10, 5);1416 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1417 */1418 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1419 let owner;1420 if (typeof blockHashAt === 'undefined') {1421 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1422 } else {1423 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1424 }1425 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1426 }14271428 /**1429 * Is token approved to transfer1430 * @param collectionId ID of collection1431 * @param tokenId ID of token1432 * @param toAccountObj address to be approved1433 * @returns ```true``` if extrinsic success, otherwise ```false```1434 */1435 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1436 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1437 }14381439 /**1440 * Changes the owner of the token.1441 *1442 * @param signer keyring of signer1443 * @param collectionId ID of collection1444 * @param tokenId ID of token1445 * @param addressObj address of a new owner1446 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1447 * @returns ```true``` if extrinsic success, otherwise ```false```1448 */1449 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1450 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1451 }14521453 /**1454 *1455 * Change ownership of a NFT on behalf of the owner.1456 *1457 * @param signer keyring of signer1458 * @param collectionId ID of collection1459 * @param tokenId ID of token1460 * @param fromAddressObj address on behalf of which the token will be sent1461 * @param toAddressObj new token owner1462 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1463 * @returns ```true``` if extrinsic success, otherwise ```false```1464 */1465 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1466 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1467 }14681469 /**1470 * Recursively find the address that owns the token1471 * @param collectionId ID of collection1472 * @param tokenId ID of token1473 * @param blockHashAt1474 * @example getTokenTopmostOwner(10, 5);1475 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1476 */1477 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1478 let owner;1479 if (typeof blockHashAt === 'undefined') {1480 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1481 } else {1482 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1483 }14841485 if (owner === null) return null;14861487 return owner.toHuman();1488 }14891490 /**1491 * Get tokens nested in the provided token1492 * @param collectionId ID of collection1493 * @param tokenId ID of token1494 * @param blockHashAt optionally query the data at the block with this hash1495 * @example getTokenChildren(10, 5);1496 * @returns tokens whose depth of nesting is <= 51497 */1498 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1499 let children;1500 if(typeof blockHashAt === 'undefined') {1501 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1502 } else {1503 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1504 }15051506 return children.toJSON().map((x: any) => {1507 return {collectionId: x.collection, tokenId: x.token};1508 });1509 }15101511 /**1512 * Nest one token into another1513 * @param signer keyring of signer1514 * @param tokenObj token to be nested1515 * @param rootTokenObj token to be parent1516 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1517 * @returns ```true``` if extrinsic success, otherwise ```false```1518 */1519 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1520 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1521 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1522 if(!result) {1523 throw Error('Unable to nest token!');1524 }1525 return result;1526 }15271528 /**1529 * Remove token from nested state1530 * @param signer keyring of signer1531 * @param tokenObj token to unnest1532 * @param rootTokenObj parent of a token1533 * @param toAddressObj address of a new token owner1534 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1535 * @returns ```true``` if extrinsic success, otherwise ```false```1536 */1537 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1538 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1539 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1540 if(!result) {1541 throw Error('Unable to unnest token!');1542 }1543 return result;1544 }15451546 /**1547 * Mint new collection1548 * @param signer keyring of signer1549 * @param collectionOptions Collection options1550 * @example1551 * mintCollection(aliceKeyring, {1552 * name: 'New',1553 * description: 'New collection',1554 * tokenPrefix: 'NEW',1555 * })1556 * @returns object of the created collection1557 */1558 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1559 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1560 }15611562 /**1563 * Mint new token1564 * @param signer keyring of signer1565 * @param data token data1566 * @returns created token object1567 */1568 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1569 const creationResult = await this.helper.executeExtrinsic(1570 signer,1571 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1572 nft: {1573 properties: data.properties,1574 },1575 }],1576 true,1577 );1578 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1579 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1580 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1581 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1582 }15831584 /**1585 * Mint multiple NFT tokens1586 * @param signer keyring of signer1587 * @param collectionId ID of collection1588 * @param tokens array of tokens with owner and properties1589 * @example1590 * mintMultipleTokens(aliceKeyring, 10, [{1591 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1592 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1593 * },{1594 * owner: {Ethereum: "0x9F0583DbB855d..."},1595 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1596 * }]);1597 * @returns ```true``` if extrinsic success, otherwise ```false```1598 */1599 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1600 const creationResult = await this.helper.executeExtrinsic(1601 signer,1602 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1603 true,1604 );1605 const collection = this.getCollectionObject(collectionId);1606 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1607 }16081609 /**1610 * Mint multiple NFT tokens with one owner1611 * @param signer keyring of signer1612 * @param collectionId ID of collection1613 * @param owner tokens owner1614 * @param tokens array of tokens with owner and properties1615 * @example1616 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1617 * properties: [{1618 * key: "gender",1619 * value: "female",1620 * },{1621 * key: "age",1622 * value: "33",1623 * }],1624 * }]);1625 * @returns array of newly created tokens1626 */1627 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1628 const rawTokens = [];1629 for (const token of tokens) {1630 const raw = {NFT: {properties: token.properties}};1631 rawTokens.push(raw);1632 }1633 const creationResult = await this.helper.executeExtrinsic(1634 signer,1635 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1636 true,1637 );1638 const collection = this.getCollectionObject(collectionId);1639 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1640 }16411642 /**1643 * Set, change, or remove approved address to transfer the ownership of the NFT.1644 *1645 * @param signer keyring of signer1646 * @param collectionId ID of collection1647 * @param tokenId ID of token1648 * @param toAddressObj address to approve1649 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1650 * @returns ```true``` if extrinsic success, otherwise ```false```1651 */1652 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1653 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1654 }1655}165616571658class RFTGroup extends NFTnRFT {1659 /**1660 * Get collection object1661 * @param collectionId ID of collection1662 * @example getCollectionObject(2);1663 * @returns instance of UniqueRFTCollection1664 */1665 getCollectionObject(collectionId: number): UniqueRFTCollection {1666 return new UniqueRFTCollection(collectionId, this.helper);1667 }16681669 /**1670 * Get token object1671 * @param collectionId ID of collection1672 * @param tokenId ID of token1673 * @example getTokenObject(10, 5);1674 * @returns instance of UniqueNFTToken1675 */1676 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1677 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1678 }16791680 /**1681 * Get top 10 token owners with the largest number of pieces1682 * @param collectionId ID of collection1683 * @param tokenId ID of token1684 * @example getTokenTop10Owners(10, 5);1685 * @returns array of top 10 owners1686 */1687 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1688 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1689 }16901691 /**1692 * Get number of pieces owned by address1693 * @param collectionId ID of collection1694 * @param tokenId ID of token1695 * @param addressObj address token owner1696 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1697 * @returns number of pieces ownerd by address1698 */1699 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1700 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1701 }17021703 /**1704 * Transfer pieces of token to another address1705 * @param signer keyring of signer1706 * @param collectionId ID of collection1707 * @param tokenId ID of token1708 * @param addressObj address of a new owner1709 * @param amount number of pieces to be transfered1710 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1711 * @returns ```true``` if extrinsic success, otherwise ```false```1712 */1713 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1714 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1715 }17161717 /**1718 * Change ownership of some pieces of RFT on behalf of the owner.1719 * @param signer keyring of signer1720 * @param collectionId ID of collection1721 * @param tokenId ID of token1722 * @param fromAddressObj address on behalf of which the token will be sent1723 * @param toAddressObj new token owner1724 * @param amount number of pieces to be transfered1725 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1726 * @returns ```true``` if extrinsic success, otherwise ```false```1727 */1728 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1729 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1730 }17311732 /**1733 * Mint new collection1734 * @param signer keyring of signer1735 * @param collectionOptions Collection options1736 * @example1737 * mintCollection(aliceKeyring, {1738 * name: 'New',1739 * description: 'New collection',1740 * tokenPrefix: 'NEW',1741 * })1742 * @returns object of the created collection1743 */1744 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1745 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1746 }17471748 /**1749 * Mint new token1750 * @param signer keyring of signer1751 * @param data token data1752 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1753 * @returns created token object1754 */1755 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1756 const creationResult = await this.helper.executeExtrinsic(1757 signer,1758 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1759 refungible: {1760 pieces: data.pieces,1761 properties: data.properties,1762 },1763 }],1764 true,1765 );1766 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1767 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1768 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1769 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1770 }17711772 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1773 throw Error('Not implemented');1774 const creationResult = await this.helper.executeExtrinsic(1775 signer,1776 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1777 true, // `Unable to mint RFT tokens for ${label}`,1778 );1779 const collection = this.getCollectionObject(collectionId);1780 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1781 }17821783 /**1784 * Mint multiple RFT tokens with one owner1785 * @param signer keyring of signer1786 * @param collectionId ID of collection1787 * @param owner tokens owner1788 * @param tokens array of tokens with properties and pieces1789 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1790 * @returns array of newly created RFT tokens1791 */1792 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1793 const rawTokens = [];1794 for (const token of tokens) {1795 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1796 rawTokens.push(raw);1797 }1798 const creationResult = await this.helper.executeExtrinsic(1799 signer,1800 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1801 true,1802 );1803 const collection = this.getCollectionObject(collectionId);1804 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1805 }18061807 /**1808 * Destroys a concrete instance of RFT.1809 * @param signer keyring of signer1810 * @param collectionId ID of collection1811 * @param tokenId ID of token1812 * @param amount number of pieces to be burnt1813 * @example burnToken(aliceKeyring, 10, 5);1814 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1815 */1816 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1817 return await super.burnToken(signer, collectionId, tokenId, amount);1818 }18191820 /**1821 * Destroys a concrete instance of RFT on behalf of the owner.1822 * @param signer keyring of signer1823 * @param collectionId ID of collection1824 * @param tokenId ID of token1825 * @param fromAddressObj address on behalf of which the token will be burnt1826 * @param amount number of pieces to be burnt1827 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1828 * @returns ```true``` if extrinsic success, otherwise ```false```1829 */1830 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1831 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1832 }18331834 /**1835 * Set, change, or remove approved address to transfer the ownership of the RFT.1836 *1837 * @param signer keyring of signer1838 * @param collectionId ID of collection1839 * @param tokenId ID of token1840 * @param toAddressObj address to approve1841 * @param amount number of pieces to be approved1842 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1843 * @returns true if the token success, otherwise false1844 */1845 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1846 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1847 }18481849 /**1850 * Get total number of pieces1851 * @param collectionId ID of collection1852 * @param tokenId ID of token1853 * @example getTokenTotalPieces(10, 5);1854 * @returns number of pieces1855 */1856 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1857 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1858 }18591860 /**1861 * Change number of token pieces. Signer must be the owner of all token pieces.1862 * @param signer keyring of signer1863 * @param collectionId ID of collection1864 * @param tokenId ID of token1865 * @param amount new number of pieces1866 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1867 * @returns true if the repartion was success, otherwise false1868 */1869 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1870 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1871 const repartitionResult = await this.helper.executeExtrinsic(1872 signer,1873 'api.tx.unique.repartition', [collectionId, tokenId, amount],1874 true,1875 );1876 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1877 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1878 }1879}188018811882class FTGroup extends CollectionGroup {1883 /**1884 * Get collection object1885 * @param collectionId ID of collection1886 * @example getCollectionObject(2);1887 * @returns instance of UniqueFTCollection1888 */1889 getCollectionObject(collectionId: number): UniqueFTCollection {1890 return new UniqueFTCollection(collectionId, this.helper);1891 }18921893 /**1894 * Mint new fungible collection1895 * @param signer keyring of signer1896 * @param collectionOptions Collection options1897 * @param decimalPoints number of token decimals1898 * @example1899 * mintCollection(aliceKeyring, {1900 * name: 'New',1901 * description: 'New collection',1902 * tokenPrefix: 'NEW',1903 * }, 18)1904 * @returns newly created fungible collection1905 */1906 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1907 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1908 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1909 collectionOptions.mode = {fungible: decimalPoints};1910 for (const key of ['name', 'description', 'tokenPrefix']) {1911 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);1912 }1913 const creationResult = await this.helper.executeExtrinsic(1914 signer,1915 'api.tx.unique.createCollectionEx', [collectionOptions],1916 true,1917 );1918 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1919 }19201921 /**1922 * Mint tokens1923 * @param signer keyring of signer1924 * @param collectionId ID of collection1925 * @param owner address owner of new tokens1926 * @param amount amount of tokens to be meanted1927 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1928 * @returns ```true``` if extrinsic success, otherwise ```false```1929 */1930 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1931 const creationResult = await this.helper.executeExtrinsic(1932 signer,1933 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1934 fungible: {1935 value: amount,1936 },1937 }],1938 true, // `Unable to mint fungible tokens for ${label}`,1939 );1940 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1941 }19421943 /**1944 * Mint multiple Fungible tokens with one owner1945 * @param signer keyring of signer1946 * @param collectionId ID of collection1947 * @param owner tokens owner1948 * @param tokens array of tokens with properties and pieces1949 * @returns ```true``` if extrinsic success, otherwise ```false```1950 */1951 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1952 const rawTokens = [];1953 for (const token of tokens) {1954 const raw = {Fungible: {Value: token.value}};1955 rawTokens.push(raw);1956 }1957 const creationResult = await this.helper.executeExtrinsic(1958 signer,1959 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1960 true,1961 );1962 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1963 }19641965 /**1966 * Get the top 10 owners with the largest balance for the Fungible collection1967 * @param collectionId ID of collection1968 * @example getTop10Owners(10);1969 * @returns array of ```ICrossAccountId```1970 */1971 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1972 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1973 }19741975 /**1976 * Get account balance1977 * @param collectionId ID of collection1978 * @param addressObj address of owner1979 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1980 * @returns amount of fungible tokens owned by address1981 */1982 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1983 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1984 }19851986 /**1987 * Transfer tokens to address1988 * @param signer keyring of signer1989 * @param collectionId ID of collection1990 * @param toAddressObj address recipient1991 * @param amount amount of tokens to be sent1992 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1993 * @returns ```true``` if extrinsic success, otherwise ```false```1994 */1995 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1996 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1997 }19981999 /**2000 * Transfer some tokens on behalf of the owner.2001 * @param signer keyring of signer2002 * @param collectionId ID of collection2003 * @param fromAddressObj address on behalf of which tokens will be sent2004 * @param toAddressObj address where token to be sent2005 * @param amount number of tokens to be sent2006 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2007 * @returns ```true``` if extrinsic success, otherwise ```false```2008 */2009 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2010 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2011 }20122013 /**2014 * Destroy some amount of tokens2015 * @param signer keyring of signer2016 * @param collectionId ID of collection2017 * @param amount amount of tokens to be destroyed2018 * @example burnTokens(aliceKeyring, 10, 1000n);2019 * @returns ```true``` if extrinsic success, otherwise ```false```2020 */2021 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2022 return await super.burnToken(signer, collectionId, 0, amount);2023 }20242025 /**2026 * Burn some tokens on behalf of the owner.2027 * @param signer keyring of signer2028 * @param collectionId ID of collection2029 * @param fromAddressObj address on behalf of which tokens will be burnt2030 * @param amount amount of tokens to be burnt2031 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2032 * @returns ```true``` if extrinsic success, otherwise ```false```2033 */2034 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2035 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2036 }20372038 /**2039 * Get total collection supply2040 * @param collectionId2041 * @returns2042 */2043 async getTotalPieces(collectionId: number): Promise<bigint> {2044 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2045 }20462047 /**2048 * Set, change, or remove approved address to transfer tokens.2049 *2050 * @param signer keyring of signer2051 * @param collectionId ID of collection2052 * @param toAddressObj address to be approved2053 * @param amount amount of tokens to be approved2054 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2055 * @returns ```true``` if extrinsic success, otherwise ```false```2056 */2057 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2058 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2059 }20602061 /**2062 * Get amount of fungible tokens approved to transfer2063 * @param collectionId ID of collection2064 * @param fromAddressObj owner of tokens2065 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2066 * @returns number of tokens approved for the transfer2067 */2068 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2069 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2070 }2071}207220732074class ChainGroup extends HelperGroup<ChainHelperBase> {2075 /**2076 * Get system properties of a chain2077 * @example getChainProperties();2078 * @returns ss58Format, token decimals, and token symbol2079 */2080 getChainProperties(): IChainProperties {2081 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2082 return {2083 ss58Format: properties.ss58Format.toJSON(),2084 tokenDecimals: properties.tokenDecimals.toJSON(),2085 tokenSymbol: properties.tokenSymbol.toJSON(),2086 };2087 }20882089 /**2090 * Get chain header2091 * @example getLatestBlockNumber();2092 * @returns the number of the last block2093 */2094 async getLatestBlockNumber(): Promise<number> {2095 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2096 }20972098 /**2099 * Get block hash by block number2100 * @param blockNumber number of block2101 * @example getBlockHashByNumber(12345);2102 * @returns hash of a block2103 */2104 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2105 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2106 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2107 return blockHash;2108 }21092110 // TODO add docs2111 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2112 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2113 if (!blockHash) return null;2114 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2115 }21162117 /**2118 * Get account nonce2119 * @param address substrate address2120 * @example getNonce("5GrwvaEF5zXb26Fz...");2121 * @returns number, account's nonce2122 */2123 async getNonce(address: TSubstrateAccount): Promise<number> {2124 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2125 }2126}21272128class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2129 /**2130 * Get substrate address balance2131 * @param address substrate address2132 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2133 * @returns amount of tokens on address2134 */2135 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2136 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2137 }21382139 /**2140 * Transfer tokens to substrate address2141 * @param signer keyring of signer2142 * @param address substrate address of a recipient2143 * @param amount amount of tokens to be transfered2144 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2145 * @returns ```true``` if extrinsic success, otherwise ```false```2146 */2147 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2148 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}`*/);21492150 let transfer = {from: null, to: null, amount: 0n} as any;2151 result.result.events.forEach(({event: {data, method, section}}) => {2152 if ((section === 'balances') && (method === 'Transfer')) {2153 transfer = {2154 from: this.helper.address.normalizeSubstrate(data[0]),2155 to: this.helper.address.normalizeSubstrate(data[1]),2156 amount: BigInt(data[2]),2157 };2158 }2159 });2160 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2161 && this.helper.address.normalizeSubstrate(address) === transfer.to 2162 && BigInt(amount) === transfer.amount;2163 return isSuccess;2164 }21652166 /**2167 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2168 * @param address substrate address2169 * @returns2170 */2171 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2172 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2173 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2174 }2175}21762177class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2178 /**2179 * Get ethereum address balance2180 * @param address ethereum address2181 * @example getEthereum("0x9F0583DbB855d...")2182 * @returns amount of tokens on address2183 */2184 async getEthereum(address: TEthereumAccount): Promise<bigint> {2185 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2186 }21872188 /**2189 * Transfer tokens to address2190 * @param signer keyring of signer2191 * @param address Ethereum address of a recipient2192 * @param amount amount of tokens to be transfered2193 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2194 * @returns ```true``` if extrinsic success, otherwise ```false```2195 */2196 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2197 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);21982199 let transfer = {from: null, to: null, amount: 0n} as any;2200 result.result.events.forEach(({event: {data, method, section}}) => {2201 if ((section === 'balances') && (method === 'Transfer')) {2202 transfer = {2203 from: data[0].toString(),2204 to: data[1].toString(),2205 amount: BigInt(data[2]),2206 };2207 }2208 });2209 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from 2210 && address === transfer.to 2211 && BigInt(amount) === transfer.amount;2212 return isSuccess;2213 }2214}22152216class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2217 subBalanceGroup: SubstrateBalanceGroup<T>;2218 ethBalanceGroup: EthereumBalanceGroup<T>;22192220 constructor(helper: T) {2221 super(helper);2222 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2223 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2224 }22252226 getCollectionCreationPrice(): bigint {2227 return 2n * this.getOneTokenNominal();2228 }2229 /**2230 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2231 * @example getOneTokenNominal()2232 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2233 */2234 getOneTokenNominal(): bigint {2235 const chainProperties = this.helper.chain.getChainProperties();2236 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2237 }22382239 /**2240 * Get substrate address balance2241 * @param address substrate address2242 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2243 * @returns amount of tokens on address2244 */2245 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2246 return this.subBalanceGroup.getSubstrate(address);2247 }22482249 /**2250 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2251 * @param address substrate address2252 * @returns2253 */2254 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2255 return this.subBalanceGroup.getSubstrateFull(address);2256 }22572258 /**2259 * Get ethereum address balance2260 * @param address ethereum address2261 * @example getEthereum("0x9F0583DbB855d...")2262 * @returns amount of tokens on address2263 */2264 async getEthereum(address: TEthereumAccount): Promise<bigint> {2265 return this.ethBalanceGroup.getEthereum(address);2266 }22672268 /**2269 * Transfer tokens to substrate address2270 * @param signer keyring of signer2271 * @param address substrate address of a recipient2272 * @param amount amount of tokens to be transfered2273 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2274 * @returns ```true``` if extrinsic success, otherwise ```false```2275 */2276 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2277 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2278 }22792280 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2281 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);22822283 let transfer = {from: null, to: null, amount: 0n} as any;2284 result.result.events.forEach(({event: {data, method, section}}) => {2285 if ((section === 'balances') && (method === 'Transfer')) {2286 transfer = {2287 from: this.helper.address.normalizeSubstrate(data[0]),2288 to: this.helper.address.normalizeSubstrate(data[1]),2289 amount: BigInt(data[2]),2290 };2291 }2292 });2293 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2294 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2295 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2296 return isSuccess;2297 }2298}22992300class AddressGroup extends HelperGroup<ChainHelperBase> {2301 /**2302 * Normalizes the address to the specified ss58 format, by default ```42```.2303 * @param address substrate address2304 * @param ss58Format format for address conversion, by default ```42```2305 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2306 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2307 */2308 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2309 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2310 }23112312 /**2313 * Get address in the connected chain format2314 * @param address substrate address2315 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2316 * @returns address in chain format2317 */2318 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2319 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2320 }23212322 /**2323 * Get substrate mirror of an ethereum address2324 * @param ethAddress ethereum address2325 * @param toChainFormat false for normalized account2326 * @example ethToSubstrate('0x9F0583DbB855d...')2327 * @returns substrate mirror of a provided ethereum address2328 */2329 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2330 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2331 }23322333 /**2334 * Get ethereum mirror of a substrate address2335 * @param subAddress substrate account2336 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2337 * @returns ethereum mirror of a provided substrate address2338 */2339 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2340 return CrossAccountId.translateSubToEth(subAddress);2341 }23422343 paraSiblingSovereignAccount(paraid: number) {2344 // We are getting a *sibling* parachain sovereign account,2345 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2346 const siblingPrefix = '0x7369626c';23472348 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2349 const suffix = '000000000000000000000000000000000000000000000000';23502351 return siblingPrefix + encodedParaId + suffix;2352 }2353}23542355class StakingGroup extends HelperGroup<UniqueHelper> {2356 /**2357 * Stake tokens for App Promotion2358 * @param signer keyring of signer2359 * @param amountToStake amount of tokens to stake2360 * @param label extra label for log2361 * @returns2362 */2363 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2364 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2365 const _stakeResult = await this.helper.executeExtrinsic(2366 signer, 'api.tx.appPromotion.stake',2367 [amountToStake], true,2368 );2369 // TODO extract info from stakeResult2370 return true;2371 }23722373 /**2374 * Unstake tokens for App Promotion2375 * @param signer keyring of signer2376 * @param amountToUnstake amount of tokens to unstake2377 * @param label extra label for log2378 * @returns block number where balances will be unlocked2379 */2380 async unstake(signer: TSigner, label?: string): Promise<number> {2381 if(typeof label === 'undefined') label = `${signer.address}`;2382 const _unstakeResult = await this.helper.executeExtrinsic(2383 signer, 'api.tx.appPromotion.unstake',2384 [], true,2385 );2386 // TODO extract block number fron events2387 return 1;2388 }23892390 /**2391 * Get total staked amount for address2392 * @param address substrate or ethereum address2393 * @returns total staked amount2394 */2395 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2396 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2397 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2398 }23992400 /**2401 * Get total staked per block2402 * @param address substrate or ethereum address2403 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2404 */2405 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2406 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2407 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2408 return { 2409 block: block.toBigInt(),2410 amount: amount.toBigInt(),2411 };2412 });2413 }24142415 /**2416 * Get total pending unstake amount for address2417 * @param address substrate or ethereum address2418 * @returns total pending unstake amount2419 */2420 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2421 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2422 }24232424 /**2425 * Get pending unstake amount per block for address2426 * @param address substrate or ethereum address2427 * @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 block2428 */2429 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2430 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2431 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2432 return {2433 block: block.toBigInt(),2434 amount: amount.toBigInt(),2435 };2436 });2437 return result;2438 }2439}24402441class SchedulerGroup extends HelperGroup<UniqueHelper> {2442 async cancelScheduled(signer: TSigner, scheduledId: string) {2443 return this.helper.executeExtrinsic(2444 signer,2445 'api.tx.scheduler.cancelNamed',2446 [scheduledId],2447 true,2448 );2449 }24502451 async changePriority(signer: TSigner, scheduledId: string, priority: number) {2452 return this.helper.executeExtrinsic(2453 signer,2454 'api.tx.scheduler.changeNamedPriority',2455 [scheduledId, priority],2456 true,2457 );2458 }24592460 scheduleAt<T extends UniqueHelper>(2461 scheduledId: string,2462 executionBlockNumber: number,2463 options: ISchedulerOptions = {},2464 ) {2465 return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2466 }24672468 scheduleAfter<T extends UniqueHelper>(2469 scheduledId: string,2470 blocksBeforeExecution: number,2471 options: ISchedulerOptions = {},2472 ) {2473 return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2474 }24752476 schedule<T extends UniqueHelper>(2477 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2478 scheduledId: string,2479 blocksNum: number,2480 options: ISchedulerOptions = {},2481 ) {2482 // eslint-disable-next-line @typescript-eslint/naming-convention2483 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2484 return this.helper.clone(ScheduledHelperType, {2485 scheduleFn,2486 scheduledId,2487 blocksNum,2488 options,2489 }) as T;2490 }2491}24922493class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2494 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2495 await this.helper.executeExtrinsic(2496 signer,2497 'api.tx.foreignAssets.registerForeignAsset',2498 [ownerAddress, location, metadata],2499 true,2500 );2501 }25022503 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2504 await this.helper.executeExtrinsic(2505 signer,2506 'api.tx.foreignAssets.updateForeignAsset',2507 [foreignAssetId, location, metadata],2508 true,2509 );2510 }2511}25122513class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2514 palletName: string;25152516 constructor(helper: T, palletName: string) {2517 super(helper);25182519 this.palletName = palletName;2520 }25212522 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2523 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2524 }2525}25262527class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2528 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2529 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2530 }25312532 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2533 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2534 }25352536 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2537 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2538 }2539}25402541class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2542 async accounts(address: string, currencyId: any) {2543 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2544 return BigInt(free);2545 }2546}25472548class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2549 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2550 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2551 }25522553 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2554 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2555 }25562557 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2558 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2559 }25602561 async account(assetId: string | number, address: string) {2562 const accountAsset = (2563 await this.helper.callRpc('api.query.assets.account', [assetId, address])2564 ).toJSON()! as any;25652566 if (accountAsset !== null) {2567 return BigInt(accountAsset['balance']);2568 } else {2569 return null;2570 }2571 }2572}25732574class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2575 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2576 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2577 }2578}25792580class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2581 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2582 const apiPrefix = 'api.tx.assetManager.';25832584 const registerTx = this.helper.constructApiCall(2585 apiPrefix + 'registerForeignAsset',2586 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2587 );25882589 const setUnitsTx = this.helper.constructApiCall(2590 apiPrefix + 'setAssetUnitsPerSecond',2591 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2592 );25932594 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2595 const encodedProposal = batchCall?.method.toHex() || '';2596 return encodedProposal;2597 }25982599 async assetTypeId(location: any) {2600 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2601 }2602}26032604class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2605 async notePreimage(signer: TSigner, encodedProposal: string) {2606 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2607 }26082609 externalProposeMajority(proposalHash: string) {2610 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2611 }26122613 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2614 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2615 }26162617 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2618 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2619 }2620}26212622class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2623 collective: string;26242625 constructor(helper: MoonbeamHelper, collective: string) {2626 super(helper);26272628 this.collective = collective;2629 }26302631 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2632 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2633 }26342635 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2636 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2637 }26382639 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2640 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2641 }26422643 async proposalCount() {2644 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2645 }2646}26472648export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2649export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;26502651export class UniqueHelper extends ChainHelperBase {2652 balance: BalanceGroup<UniqueHelper>;2653 collection: CollectionGroup;2654 nft: NFTGroup;2655 rft: RFTGroup;2656 ft: FTGroup;2657 staking: StakingGroup;2658 scheduler: SchedulerGroup;2659 foreignAssets: ForeignAssetsGroup;2660 xcm: XcmGroup<UniqueHelper>;2661 xTokens: XTokensGroup<UniqueHelper>;2662 tokens: TokensGroup<UniqueHelper>;26632664 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2665 super(logger, options.helperBase ?? UniqueHelper);26662667 this.balance = new BalanceGroup(this);2668 this.collection = new CollectionGroup(this);2669 this.nft = new NFTGroup(this);2670 this.rft = new RFTGroup(this);2671 this.ft = new FTGroup(this);2672 this.staking = new StakingGroup(this);2673 this.scheduler = new SchedulerGroup(this);2674 this.foreignAssets = new ForeignAssetsGroup(this);2675 this.xcm = new XcmGroup(this, 'polkadotXcm');2676 this.xTokens = new XTokensGroup(this);2677 this.tokens = new TokensGroup(this);2678 }26792680 getSudo<T extends UniqueHelper>() {2681 // eslint-disable-next-line @typescript-eslint/naming-convention2682 const SudoHelperType = SudoHelper(this.helperBase);2683 return this.clone(SudoHelperType) as T;2684 }2685}26862687export class XcmChainHelper extends ChainHelperBase {2688 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2689 const wsProvider = new WsProvider(wsEndpoint);2690 this.api = new ApiPromise({2691 provider: wsProvider,2692 });2693 await this.api.isReadyOrError;2694 this.network = await UniqueHelper.detectNetwork(this.api);2695 }2696}26972698export class RelayHelper extends XcmChainHelper {2699 xcm: XcmGroup<RelayHelper>;27002701 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2702 super(logger, options.helperBase ?? RelayHelper);27032704 this.xcm = new XcmGroup(this, 'xcmPallet');2705 }2706}27072708export class WestmintHelper extends XcmChainHelper {2709 balance: SubstrateBalanceGroup<WestmintHelper>;2710 xcm: XcmGroup<WestmintHelper>;2711 assets: AssetsGroup<WestmintHelper>;2712 xTokens: XTokensGroup<WestmintHelper>;27132714 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2715 super(logger, options.helperBase ?? WestmintHelper);27162717 this.balance = new SubstrateBalanceGroup(this);2718 this.xcm = new XcmGroup(this, 'polkadotXcm');2719 this.assets = new AssetsGroup(this);2720 this.xTokens = new XTokensGroup(this);2721 }2722}27232724export class MoonbeamHelper extends XcmChainHelper {2725 balance: EthereumBalanceGroup<MoonbeamHelper>;2726 assetManager: MoonbeamAssetManagerGroup;2727 assets: AssetsGroup<MoonbeamHelper>;2728 xTokens: XTokensGroup<MoonbeamHelper>;2729 democracy: MoonbeamDemocracyGroup;2730 collective: {2731 council: MoonbeamCollectiveGroup,2732 techCommittee: MoonbeamCollectiveGroup,2733 };27342735 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2736 super(logger, options.helperBase ?? MoonbeamHelper);27372738 this.balance = new EthereumBalanceGroup(this);2739 this.assetManager = new MoonbeamAssetManagerGroup(this);2740 this.assets = new AssetsGroup(this);2741 this.xTokens = new XTokensGroup(this);2742 this.democracy = new MoonbeamDemocracyGroup(this);2743 this.collective = {2744 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2745 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2746 };2747 }2748}27492750export class AcalaHelper extends XcmChainHelper {2751 balance: SubstrateBalanceGroup<AcalaHelper>;2752 assetRegistry: AcalaAssetRegistryGroup;2753 xTokens: XTokensGroup<AcalaHelper>;2754 tokens: TokensGroup<AcalaHelper>;27552756 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2757 super(logger, options.helperBase ?? AcalaHelper);27582759 this.balance = new SubstrateBalanceGroup(this);2760 this.assetRegistry = new AcalaAssetRegistryGroup(this);2761 this.xTokens = new XTokensGroup(this);2762 this.tokens = new TokensGroup(this);2763 }27642765 getSudo<T extends AcalaHelper>() {2766 // eslint-disable-next-line @typescript-eslint/naming-convention2767 const SudoHelperType = SudoHelper(this.helperBase);2768 return this.clone(SudoHelperType) as T;2769 }2770}27712772// eslint-disable-next-line @typescript-eslint/naming-convention2773function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2774 return class extends Base {2775 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2776 scheduledId: string;2777 blocksNum: number;2778 options: ISchedulerOptions;27792780 constructor(...args: any[]) {2781 const logger = args[0] as ILogger;2782 const options = args[1] as {2783 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2784 scheduledId: string,2785 blocksNum: number,2786 options: ISchedulerOptions2787 };27882789 super(logger);27902791 this.scheduleFn = options.scheduleFn;2792 this.scheduledId = options.scheduledId;2793 this.blocksNum = options.blocksNum;2794 this.options = options.options;2795 }27962797 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2798 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2799 const extrinsic = 'api.tx.scheduler.' + this.scheduleFn;28002801 return super.executeExtrinsic(2802 sender,2803 extrinsic,2804 [2805 this.scheduledId,2806 this.blocksNum,2807 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2808 this.options.priority ?? null,2809 {Value: scheduledTx},2810 ],2811 expectSuccess,2812 );2813 }2814 };2815}28162817// eslint-disable-next-line @typescript-eslint/naming-convention2818function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2819 return class extends Base {2820 constructor(...args: any[]) {2821 super(...args);2822 }28232824 executeExtrinsic (2825 sender: IKeyringPair,2826 extrinsic: string,2827 params: any[],2828 expectSuccess?: boolean,2829 ): Promise<ITransactionResult> {2830 const call = this.constructApiCall(extrinsic, params);28312832 return super.executeExtrinsic(2833 sender,2834 'api.tx.sudo.sudo',2835 [call],2836 expectSuccess,2837 );2838 }2839 };2840}28412842export class UniqueBaseCollection {2843 helper: UniqueHelper;2844 collectionId: number;28452846 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2847 this.collectionId = collectionId;2848 this.helper = uniqueHelper;2849 }28502851 async getData() {2852 return await this.helper.collection.getData(this.collectionId);2853 }28542855 async getLastTokenId() {2856 return await this.helper.collection.getLastTokenId(this.collectionId);2857 }28582859 async doesTokenExist(tokenId: number) {2860 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2861 }28622863 async getAdmins() {2864 return await this.helper.collection.getAdmins(this.collectionId);2865 }28662867 async getAllowList() {2868 return await this.helper.collection.getAllowList(this.collectionId);2869 }28702871 async getEffectiveLimits() {2872 return await this.helper.collection.getEffectiveLimits(this.collectionId);2873 }28742875 async getProperties(propertyKeys?: string[] | null) {2876 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2877 }28782879 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2880 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2881 }28822883 async getOptions() {2884 return await this.helper.collection.getCollectionOptions(this.collectionId);2885 }28862887 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2888 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2889 }28902891 async confirmSponsorship(signer: TSigner) {2892 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2893 }28942895 async removeSponsor(signer: TSigner) {2896 return await this.helper.collection.removeSponsor(signer, this.collectionId);2897 }28982899 async setLimits(signer: TSigner, limits: ICollectionLimits) {2900 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2901 }29022903 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2904 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2905 }29062907 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2908 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2909 }29102911 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2912 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2913 }29142915 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2916 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2917 }29182919 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2920 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2921 }29222923 async setProperties(signer: TSigner, properties: IProperty[]) {2924 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2925 }29262927 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2928 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2929 }29302931 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2932 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2933 }29342935 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2936 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2937 }29382939 async disableNesting(signer: TSigner) {2940 return await this.helper.collection.disableNesting(signer, this.collectionId);2941 }29422943 async burn(signer: TSigner) {2944 return await this.helper.collection.burn(signer, this.collectionId);2945 }29462947 scheduleAt<T extends UniqueHelper>(2948 scheduledId: string,2949 executionBlockNumber: number,2950 options: ISchedulerOptions = {},2951 ) {2952 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2953 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2954 }29552956 scheduleAfter<T extends UniqueHelper>(2957 scheduledId: string,2958 blocksBeforeExecution: number,2959 options: ISchedulerOptions = {},2960 ) {2961 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2962 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2963 }29642965 getSudo<T extends UniqueHelper>() {2966 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2967 }29682969 getSudo() {2970 return new UniqueCollectionBase(this.collectionId, this.helper.getSudo());2971 }2972}297329742975export class UniqueNFTCollection extends UniqueBaseCollection {2976 getTokenObject(tokenId: number) {2977 return new UniqueNFToken(tokenId, this);2978 }29792980 async getTokensByAddress(addressObj: ICrossAccountId) {2981 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2982 }29832984 async getToken(tokenId: number, blockHashAt?: string) {2985 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2986 }29872988 async getTokenOwner(tokenId: number, blockHashAt?: string) {2989 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2990 }29912992 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2993 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2994 }29952996 async getTokenChildren(tokenId: number, blockHashAt?: string) {2997 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2998 }29993000 async getPropertyPermissions(propertyKeys: string[] | null = null) {3001 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3002 }30033004 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3005 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3006 }30073008 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3009 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3010 }30113012 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3013 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3014 }30153016 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3017 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3018 }30193020 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3021 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3022 }30233024 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3025 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3026 }30273028 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3029 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3030 }30313032 async burnToken(signer: TSigner, tokenId: number) {3033 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3034 }30353036 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3037 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3038 }30393040 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3041 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3042 }30433044 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3045 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3046 }30473048 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3049 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3050 }30513052 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3053 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3054 }30553056 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3057 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3058 }30593060 scheduleAt<T extends UniqueHelper>(3061 scheduledId: string,3062 executionBlockNumber: number,3063 options: ISchedulerOptions = {},3064 ) {3065 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3066 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3067 }30683069 scheduleAfter<T extends UniqueHelper>(3070 scheduledId: string,3071 blocksBeforeExecution: number,3072 options: ISchedulerOptions = {},3073 ) {3074 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3075 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3076 }30773078 getSudo<T extends UniqueHelper>() {3079 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3080 }3081}308230833084export class UniqueRFTCollection extends UniqueBaseCollection {3085 getTokenObject(tokenId: number) {3086 return new UniqueRFToken(tokenId, this);3087 }30883089 async getToken(tokenId: number, blockHashAt?: string) {3090 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3091 }30923093 async getTokensByAddress(addressObj: ICrossAccountId) {3094 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3095 }30963097 async getTop10TokenOwners(tokenId: number) {3098 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3099 }31003101 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3102 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3103 }31043105 async getTokenTotalPieces(tokenId: number) {3106 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3107 }31083109 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3110 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3111 }31123113 async getPropertyPermissions(propertyKeys: string[] | null = null) {3114 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3115 }31163117 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3118 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3119 }31203121 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3122 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3123 }31243125 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3126 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3127 }31283129 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3130 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3131 }31323133 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3134 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3135 }31363137 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3138 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3139 }31403141 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3142 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3143 }31443145 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3146 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3147 }31483149 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3150 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3151 }31523153 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3154 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3155 }31563157 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3158 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3159 }31603161 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3162 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3163 }31643165 scheduleAt<T extends UniqueHelper>(3166 scheduledId: string,3167 executionBlockNumber: number,3168 options: ISchedulerOptions = {},3169 ) {3170 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3171 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3172 }31733174 scheduleAfter<T extends UniqueHelper>(3175 scheduledId: string,3176 blocksBeforeExecution: number,3177 options: ISchedulerOptions = {},3178 ) {3179 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3180 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3181 }31823183 getSudo<T extends UniqueHelper>() {3184 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3185 }3186}318731883189export class UniqueFTCollection extends UniqueBaseCollection {3190 async getBalance(addressObj: ICrossAccountId) {3191 return await this.helper.ft.getBalance(this.collectionId, addressObj);3192 }31933194 async getTotalPieces() {3195 return await this.helper.ft.getTotalPieces(this.collectionId);3196 }31973198 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3199 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3200 }32013202 async getTop10Owners() {3203 return await this.helper.ft.getTop10Owners(this.collectionId);3204 }32053206 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3207 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3208 }32093210 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3211 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3212 }32133214 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3215 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3216 }32173218 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3219 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3220 }32213222 async burnTokens(signer: TSigner, amount=1n) {3223 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3224 }32253226 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3227 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3228 }32293230 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3231 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3232 }32333234 scheduleAt<T extends UniqueHelper>(3235 scheduledId: string,3236 executionBlockNumber: number,3237 options: ISchedulerOptions = {},3238 ) {3239 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3240 return new UniqueFTCollection(this.collectionId, scheduledHelper);3241 }32423243 scheduleAfter<T extends UniqueHelper>(3244 scheduledId: string,3245 blocksBeforeExecution: number,3246 options: ISchedulerOptions = {},3247 ) {3248 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3249 return new UniqueFTCollection(this.collectionId, scheduledHelper);3250 }32513252 getSudo<T extends UniqueHelper>() {3253 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3254 }3255}325632573258export class UniqueBaseToken {3259 collection: UniqueNFTCollection | UniqueRFTCollection;3260 collectionId: number;3261 tokenId: number;32623263 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3264 this.collection = collection;3265 this.collectionId = collection.collectionId;3266 this.tokenId = tokenId;3267 }32683269 async getNextSponsored(addressObj: ICrossAccountId) {3270 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3271 }32723273 async getProperties(propertyKeys?: string[] | null) {3274 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3275 }32763277 async setProperties(signer: TSigner, properties: IProperty[]) {3278 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3279 }32803281 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3282 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3283 }32843285 async doesExist() {3286 return await this.collection.doesTokenExist(this.tokenId);3287 }32883289 nestingAccount() {3290 return this.collection.helper.util.getTokenAccount(this);3291 }32923293 scheduleAt<T extends UniqueHelper>(3294 scheduledId: string,3295 executionBlockNumber: number,3296 options: ISchedulerOptions = {},3297 ) {3298 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3299 return new UniqueBaseToken(this.tokenId, scheduledCollection);3300 }33013302 scheduleAfter<T extends UniqueHelper>(3303 scheduledId: string,3304 blocksBeforeExecution: number,3305 options: ISchedulerOptions = {},3306 ) {3307 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3308 return new UniqueBaseToken(this.tokenId, scheduledCollection);3309 }33103311 getSudo<T extends UniqueHelper>() {3312 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3313 }3314}331533163317export class UniqueNFToken extends UniqueBaseToken {3318 collection: UniqueNFTCollection;33193320 constructor(tokenId: number, collection: UniqueNFTCollection) {3321 super(tokenId, collection);3322 this.collection = collection;3323 }33243325 async getData(blockHashAt?: string) {3326 return await this.collection.getToken(this.tokenId, blockHashAt);3327 }33283329 async getOwner(blockHashAt?: string) {3330 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3331 }33323333 async getTopmostOwner(blockHashAt?: string) {3334 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3335 }33363337 async getChildren(blockHashAt?: string) {3338 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3339 }33403341 async nest(signer: TSigner, toTokenObj: IToken) {3342 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3343 }33443345 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3346 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3347 }33483349 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3350 return await this.collection.transferToken(signer, this.tokenId, addressObj);3351 }33523353 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3354 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3355 }33563357 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3358 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3359 }33603361 async isApproved(toAddressObj: ICrossAccountId) {3362 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3363 }33643365 async burn(signer: TSigner) {3366 return await this.collection.burnToken(signer, this.tokenId);3367 }33683369 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3370 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3371 }33723373 scheduleAt<T extends UniqueHelper>(3374 scheduledId: string,3375 executionBlockNumber: number,3376 options: ISchedulerOptions = {},3377 ) {3378 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3379 return new UniqueNFToken(this.tokenId, scheduledCollection);3380 }33813382 scheduleAfter<T extends UniqueHelper>(3383 scheduledId: string,3384 blocksBeforeExecution: number,3385 options: ISchedulerOptions = {},3386 ) {3387 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3388 return new UniqueNFToken(this.tokenId, scheduledCollection);3389 }33903391 getSudo<T extends UniqueHelper>() {3392 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3393 }3394}33953396export class UniqueRFToken extends UniqueBaseToken {3397 collection: UniqueRFTCollection;33983399 constructor(tokenId: number, collection: UniqueRFTCollection) {3400 super(tokenId, collection);3401 this.collection = collection;3402 }34033404 async getData(blockHashAt?: string) {3405 return await this.collection.getToken(this.tokenId, blockHashAt);3406 }34073408 async getTop10Owners() {3409 return await this.collection.getTop10TokenOwners(this.tokenId);3410 }34113412 async getBalance(addressObj: ICrossAccountId) {3413 return await this.collection.getTokenBalance(this.tokenId, addressObj);3414 }34153416 async getTotalPieces() {3417 return await this.collection.getTokenTotalPieces(this.tokenId);3418 }34193420 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3421 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3422 }34233424 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3425 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3426 }34273428 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3429 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3430 }34313432 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3433 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3434 }34353436 async repartition(signer: TSigner, amount: bigint) {3437 return await this.collection.repartitionToken(signer, this.tokenId, amount);3438 }34393440 async burn(signer: TSigner, amount=1n) {3441 return await this.collection.burnToken(signer, this.tokenId, amount);3442 }34433444 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3445 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3446 }34473448 scheduleAt<T extends UniqueHelper>(3449 scheduledId: string,3450 executionBlockNumber: number,3451 options: ISchedulerOptions = {},3452 ) {3453 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3454 return new UniqueRFToken(this.tokenId, scheduledCollection);3455 }34563457 scheduleAfter<T extends UniqueHelper>(3458 scheduledId: string,3459 blocksBeforeExecution: number,3460 options: ISchedulerOptions = {},3461 ) {3462 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3463 return new UniqueRFToken(this.tokenId, scheduledCollection);3464 }34653466 getSudo<T extends UniqueHelper>() {3467 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3468 }3469}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, IForeignAssetMetadata, TNetworks, MoonbeamAssetInfo, DemocracyStandardAccountVote, AcalaAssetMetadata} 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 }256257 static bigIntToDecimals(number: bigint, decimals = 18) {258 const numberStr = number.toString();259 const dotPos = numberStr.length - decimals;260 261 if (dotPos <= 0) {262 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;263 } else {264 const intPart = numberStr.substring(0, dotPos);265 const fractPart = numberStr.substring(dotPos);266 return intPart + '.' + fractPart;267 }268 }269}270271class UniqueEventHelper {272 private static extractIndex(index: any): [number, number] | string {273 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];274 return index.toJSON();275 }276277 private static extractSub(data: any, subTypes: any): {[key: string]: any} {278 let obj: any = {};279 let index = 0;280281 if (data.entries) {282 for(const [key, value] of data.entries()) {283 obj[key] = this.extractData(value, subTypes[index]);284 index++;285 }286 } else obj = data.toJSON();287288 return obj;289 }290 291 private static extractData(data: any, type: any): any {292 if(!type) return data.toHuman();293 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();294 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();295 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);296 return data.toHuman();297 }298299 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {300 const parsedEvents: IEvent[] = [];301302 events.forEach((record) => {303 const {event, phase} = record;304 const types = event.typeDef;305306 const eventData: IEvent = {307 section: event.section.toString(),308 method: event.method.toString(),309 index: this.extractIndex(event.index),310 data: [],311 phase: phase.toJSON(),312 };313314 event.data.forEach((val: any, index: number) => {315 eventData.data.push(this.extractData(val, types[index]));316 });317318 parsedEvents.push(eventData);319 });320321 return parsedEvents;322 }323}324325export class ChainHelperBase {326 helperBase: any;327328 transactionStatus = UniqueUtil.transactionStatus;329 chainLogType = UniqueUtil.chainLogType;330 util: typeof UniqueUtil;331 eventHelper: typeof UniqueEventHelper;332 logger: ILogger;333 api: ApiPromise | null;334 forcedNetwork: TNetworks | null;335 network: TNetworks | null;336 chainLog: IUniqueHelperLog[];337 children: ChainHelperBase[];338 address: AddressGroup;339 chain: ChainGroup;340341 constructor(logger?: ILogger, helperBase?: any) {342 this.helperBase = helperBase;343344 this.util = UniqueUtil;345 this.eventHelper = UniqueEventHelper;346 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();347 this.logger = logger;348 this.api = null;349 this.forcedNetwork = null;350 this.network = null;351 this.chainLog = [];352 this.children = [];353 this.address = new AddressGroup(this);354 this.chain = new ChainGroup(this);355 }356357 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {358 Object.setPrototypeOf(helperCls.prototype, this);359 const newHelper = new helperCls(this.logger, options);360361 newHelper.api = this.api;362 newHelper.network = this.network;363 newHelper.forceNetwork = this.forceNetwork;364365 this.children.push(newHelper);366367 return newHelper;368 }369370 getApi(): ApiPromise {371 if(this.api === null) throw Error('API not initialized');372 return this.api;373 }374375 clearChainLog(): void {376 this.chainLog = [];377 }378379 forceNetwork(value: TNetworks): void {380 this.forcedNetwork = value;381 }382383 async connect(wsEndpoint: string, listeners?: IApiListeners) {384 if (this.api !== null) throw Error('Already connected');385 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);386 this.api = api;387 this.network = network;388 }389390 async disconnect() {391 for (const child of this.children) {392 child.clearApi();393 }394395 if (this.api === null) return;396 await this.api.disconnect();397 this.clearApi();398 }399400 clearApi() {401 this.api = null;402 this.network = null;403 }404405 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {406 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;407 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];408409 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;410411 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;412 return 'opal';413 }414415 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {416 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});417 await api.isReady;418419 const network = await this.detectNetwork(api);420421 await api.disconnect();422423 return network;424 }425426 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{427 api: ApiPromise;428 network: TNetworks;429 }> {430 if(typeof network === 'undefined' || network === null) network = 'opal';431 const supportedRPC = {432 opal: {433 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,434 },435 quartz: {436 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,437 },438 unique: {439 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,440 },441 rococo: {},442 westend: {},443 moonbeam: {},444 moonriver: {},445 acala: {},446 karura: {},447 westmint: {},448 };449 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);450 const rpc = supportedRPC[network];451452 // TODO: investigate how to replace rpc in runtime453 // api._rpcCore.addUserInterfaces(rpc);454455 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});456457 await api.isReadyOrError;458459 if (typeof listeners === 'undefined') listeners = {};460 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {461 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;462 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);463 }464465 return {api, network};466 }467468 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {469 const {events, status} = data;470 if (status.isReady) {471 return this.transactionStatus.NOT_READY;472 }473 if (status.isBroadcast) {474 return this.transactionStatus.NOT_READY;475 }476 if (status.isInBlock || status.isFinalized) {477 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');478 if (errors.length > 0) {479 return this.transactionStatus.FAIL;480 }481 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {482 return this.transactionStatus.SUCCESS;483 }484 }485486 return this.transactionStatus.FAIL;487 }488489 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {490 const sign = (callback: any) => {491 if(options !== null) return transaction.signAndSend(sender, options, callback);492 return transaction.signAndSend(sender, callback);493 };494 // eslint-disable-next-line no-async-promise-executor495 return new Promise(async (resolve, reject) => {496 try {497 const unsub = await sign((result: any) => {498 const status = this.getTransactionStatus(result);499500 if (status === this.transactionStatus.SUCCESS) {501 this.logger.log(`${label} successful`);502 unsub();503 resolve({result, status});504 } else if (status === this.transactionStatus.FAIL) {505 let moduleError = null;506507 if (result.hasOwnProperty('dispatchError')) {508 const dispatchError = result['dispatchError'];509510 if (dispatchError) {511 if (dispatchError.isModule) {512 const modErr = dispatchError.asModule;513 const errorMeta = dispatchError.registry.findMetaError(modErr);514515 moduleError = `${errorMeta.section}.${errorMeta.name}`;516 } else {517 moduleError = dispatchError.toHuman();518 }519 } else {520 this.logger.log(result, this.logger.level.ERROR);521 }522 }523524 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);525 unsub();526 reject({status, moduleError, result});527 }528 });529 } catch (e) {530 this.logger.log(e, this.logger.level.ERROR);531 reject(e);532 }533 });534 }535536 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {537 const api = this.getApi();538 const signingInfo = await api.derive.tx.signingInfo(signer.address);539540 // We need to sign the tx because541 // unsigned transactions does not have an inclusion fee542 tx.sign(signer, {543 blockHash: api.genesisHash,544 genesisHash: api.genesisHash,545 runtimeVersion: api.runtimeVersion,546 nonce: signingInfo.nonce,547 });548549 if (len === null) {550 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;551 } else {552 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;553 }554 }555556 constructApiCall(apiCall: string, params: any[]) {557 if(this.api === null) throw Error('API not initialized');558 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);559 let call = this.getApi() as any;560 for(const part of apiCall.slice(4).split('.')) {561 call = call[part];562 }563 return call(...params);564 }565566 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {567 if(this.api === null) throw Error('API not initialized');568 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);569570 const startTime = (new Date()).getTime();571 let result: ITransactionResult;572 let events: IEvent[] = [];573 try {574 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;575 events = this.eventHelper.extractEvents(result.result.events);576 }577 catch(e) {578 if(!(e as object).hasOwnProperty('status')) throw e;579 result = e as ITransactionResult;580 }581582 const endTime = (new Date()).getTime();583584 const log = {585 executedAt: endTime,586 executionTime: endTime - startTime,587 type: this.chainLogType.EXTRINSIC,588 status: result.status,589 call: extrinsic,590 signer: this.getSignerAddress(sender),591 params,592 } as IUniqueHelperLog;593594 if(result.status !== this.transactionStatus.SUCCESS) {595 if (result.moduleError) log.moduleError = result.moduleError;596 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;597 }598 if(events.length > 0) log.events = events;599600 this.chainLog.push(log);601602 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {603 if (result.moduleError) throw Error(`${result.moduleError}`);604 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));605 }606 return result;607 }608609 async callRpc(rpc: string, params?: any[]) {610 if(typeof params === 'undefined') params = [];611 if(this.api === null) throw Error('API not initialized');612 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);613614 const startTime = (new Date()).getTime();615 let result;616 let error = null;617 const log = {618 type: this.chainLogType.RPC,619 call: rpc,620 params,621 } as IUniqueHelperLog;622623 try {624 result = await this.constructApiCall(rpc, params);625 }626 catch(e) {627 error = e;628 }629630 const endTime = (new Date()).getTime();631632 log.executedAt = endTime;633 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';634 log.executionTime = endTime - startTime;635636 this.chainLog.push(log);637638 if(error !== null) throw error;639640 return result;641 }642643 getSignerAddress(signer: IKeyringPair | string): string {644 if(typeof signer === 'string') return signer;645 return signer.address;646 }647648 fetchAllPalletNames(): string[] {649 if(this.api === null) throw Error('API not initialized');650 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());651 }652653 fetchMissingPalletNames(requiredPallets: string[]): string[] {654 const palletNames = this.fetchAllPalletNames();655 return requiredPallets.filter(p => !palletNames.includes(p));656 }657}658659660class HelperGroup<T extends ChainHelperBase> {661 helper: T;662663 constructor(uniqueHelper: T) {664 this.helper = uniqueHelper;665 }666}667668669class CollectionGroup extends HelperGroup<UniqueHelper> {670 /**671 * Get number of blocks when sponsored transaction is available.672 *673 * @param collectionId ID of collection674 * @param tokenId ID of token675 * @param addressObj address for which the sponsorship is checked676 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});677 * @returns number of blocks or null if sponsorship hasn't been set678 */679 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {680 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();681 }682683 /**684 * Get the number of created collections.685 *686 * @returns number of created collections687 */688 async getTotalCount(): Promise<number> {689 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();690 }691692 /**693 * Get information about the collection with additional data,694 * including the number of tokens it contains, its administrators,695 * the normalized address of the collection's owner, and decoded name and description.696 *697 * @param collectionId ID of collection698 * @example await getData(2)699 * @returns collection information object700 */701 async getData(collectionId: number): Promise<{702 id: number;703 name: string;704 description: string;705 tokensCount: number;706 admins: CrossAccountId[];707 normalizedOwner: TSubstrateAccount;708 raw: any709 } | null> {710 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);711 const humanCollection = collection.toHuman(), collectionData = {712 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],713 raw: humanCollection,714 } as any, jsonCollection = collection.toJSON();715 if (humanCollection === null) return null;716 collectionData.raw.limits = jsonCollection.limits;717 collectionData.raw.permissions = jsonCollection.permissions;718 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);719 for (const key of ['name', 'description']) {720 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);721 }722723 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))724 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)725 : 0;726 collectionData.admins = await this.getAdmins(collectionId);727728 return collectionData;729 }730731 /**732 * Get the addresses of the collection's administrators, optionally normalized.733 *734 * @param collectionId ID of collection735 * @param normalize whether to normalize the addresses to the default ss58 format736 * @example await getAdmins(1)737 * @returns array of administrators738 */739 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {740 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();741742 return normalize743 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())744 : admins;745 }746747 /**748 * Get the addresses added to the collection allow-list, optionally normalized.749 * @param collectionId ID of collection750 * @param normalize whether to normalize the addresses to the default ss58 format751 * @example await getAllowList(1)752 * @returns array of allow-listed addresses753 */754 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {755 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();756 return normalize757 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())758 : allowListed;759 }760761 /**762 * Get the effective limits of the collection instead of null for default values763 *764 * @param collectionId ID of collection765 * @example await getEffectiveLimits(2)766 * @returns object of collection limits767 */768 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {769 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();770 }771772 /**773 * Burns the collection if the signer has sufficient permissions and collection is empty.774 *775 * @param signer keyring of signer776 * @param collectionId ID of collection777 * @example await helper.collection.burn(aliceKeyring, 3);778 * @returns ```true``` if extrinsic success, otherwise ```false```779 */780 async burn(signer: TSigner, collectionId: number): Promise<boolean> {781 const result = await this.helper.executeExtrinsic(782 signer,783 'api.tx.unique.destroyCollection', [collectionId],784 true,785 );786787 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');788 }789790 /**791 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.792 *793 * @param signer keyring of signer794 * @param collectionId ID of collection795 * @param sponsorAddress Sponsor substrate address796 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")797 * @returns ```true``` if extrinsic success, otherwise ```false```798 */799 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {800 const result = await this.helper.executeExtrinsic(801 signer,802 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],803 true,804 );805806 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');807 }808809 /**810 * Confirms consent to sponsor the collection on behalf of the signer.811 *812 * @param signer keyring of signer813 * @param collectionId ID of collection814 * @example confirmSponsorship(aliceKeyring, 10)815 * @returns ```true``` if extrinsic success, otherwise ```false```816 */817 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {818 const result = await this.helper.executeExtrinsic(819 signer,820 'api.tx.unique.confirmSponsorship', [collectionId],821 true,822 );823824 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');825 }826827 /**828 * Removes the sponsor of a collection, regardless if it consented or not.829 *830 * @param signer keyring of signer831 * @param collectionId ID of collection832 * @example removeSponsor(aliceKeyring, 10)833 * @returns ```true``` if extrinsic success, otherwise ```false```834 */835 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {836 const result = await this.helper.executeExtrinsic(837 signer,838 'api.tx.unique.removeCollectionSponsor', [collectionId],839 true,840 );841842 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');843 }844845 /**846 * Sets the limits of the collection. At least one limit must be specified for a correct call.847 *848 * @param signer keyring of signer849 * @param collectionId ID of collection850 * @param limits collection limits object851 * @example852 * await setLimits(853 * aliceKeyring,854 * 10,855 * {856 * sponsorTransferTimeout: 0,857 * ownerCanDestroy: false858 * }859 * )860 * @returns ```true``` if extrinsic success, otherwise ```false```861 */862 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {863 const result = await this.helper.executeExtrinsic(864 signer,865 'api.tx.unique.setCollectionLimits', [collectionId, limits],866 true,867 );868869 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');870 }871872 /**873 * Changes the owner of the collection to the new Substrate address.874 *875 * @param signer keyring of signer876 * @param collectionId ID of collection877 * @param ownerAddress substrate address of new owner878 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")879 * @returns ```true``` if extrinsic success, otherwise ```false```880 */881 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {882 const result = await this.helper.executeExtrinsic(883 signer,884 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],885 true,886 );887888 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');889 }890891 /**892 * Adds a collection administrator.893 *894 * @param signer keyring of signer895 * @param collectionId ID of collection896 * @param adminAddressObj Administrator address (substrate or ethereum)897 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})898 * @returns ```true``` if extrinsic success, otherwise ```false```899 */900 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {901 const result = await this.helper.executeExtrinsic(902 signer,903 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],904 true,905 );906907 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');908 }909910 /**911 * Removes a collection administrator.912 *913 * @param signer keyring of signer914 * @param collectionId ID of collection915 * @param adminAddressObj Administrator address (substrate or ethereum)916 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})917 * @returns ```true``` if extrinsic success, otherwise ```false```918 */919 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {920 const result = await this.helper.executeExtrinsic(921 signer,922 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],923 true,924 );925926 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');927 }928929 /**930 * Check if user is in allow list.931 * 932 * @param collectionId ID of collection933 * @param user Account to check934 * @example await getAdmins(1)935 * @returns is user in allow list936 */937 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {938 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();939 }940941 /**942 * Adds an address to allow list943 * @param signer keyring of signer944 * @param collectionId ID of collection945 * @param addressObj address to add to the allow list946 * @returns ```true``` if extrinsic success, otherwise ```false```947 */948 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {949 const result = await this.helper.executeExtrinsic(950 signer,951 'api.tx.unique.addToAllowList', [collectionId, addressObj],952 true,953 );954955 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');956 }957958 /**959 * Removes an address from allow list960 *961 * @param signer keyring of signer962 * @param collectionId ID of collection963 * @param addressObj address to remove from the allow list964 * @returns ```true``` if extrinsic success, otherwise ```false```965 */966 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {967 const result = await this.helper.executeExtrinsic(968 signer,969 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],970 true,971 );972973 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');974 }975976 /**977 * Sets onchain permissions for selected collection.978 *979 * @param signer keyring of signer980 * @param collectionId ID of collection981 * @param permissions collection permissions object982 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});983 * @returns ```true``` if extrinsic success, otherwise ```false```984 */985 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {986 const result = await this.helper.executeExtrinsic(987 signer,988 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],989 true,990 );991992 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');993 }994995 /**996 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.997 *998 * @param signer keyring of signer999 * @param collectionId ID of collection1000 * @param permissions nesting permissions object1001 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1002 * @returns ```true``` if extrinsic success, otherwise ```false```1003 */1004 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1005 return await this.setPermissions(signer, collectionId, {nesting: permissions});1006 }10071008 /**1009 * Disables nesting for selected collection.1010 *1011 * @param signer keyring of signer1012 * @param collectionId ID of collection1013 * @example disableNesting(aliceKeyring, 10);1014 * @returns ```true``` if extrinsic success, otherwise ```false```1015 */1016 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1017 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1018 }10191020 /**1021 * Sets onchain properties to the collection.1022 *1023 * @param signer keyring of signer1024 * @param collectionId ID of collection1025 * @param properties array of property objects1026 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1027 * @returns ```true``` if extrinsic success, otherwise ```false```1028 */1029 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1030 const result = await this.helper.executeExtrinsic(1031 signer,1032 'api.tx.unique.setCollectionProperties', [collectionId, properties],1033 true,1034 );10351036 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1037 }10381039 /**1040 * Get collection properties.1041 * 1042 * @param collectionId ID of collection1043 * @param propertyKeys optionally filter the returned properties to only these keys1044 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1045 * @returns array of key-value pairs1046 */1047 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1048 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1049 }10501051 async getCollectionOptions(collectionId: number) {1052 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1053 }10541055 /**1056 * Deletes onchain properties from the collection.1057 *1058 * @param signer keyring of signer1059 * @param collectionId ID of collection1060 * @param propertyKeys array of property keys to delete1061 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1062 * @returns ```true``` if extrinsic success, otherwise ```false```1063 */1064 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1065 const result = await this.helper.executeExtrinsic(1066 signer,1067 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1068 true,1069 );10701071 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1072 }10731074 /**1075 * Changes the owner of the token.1076 *1077 * @param signer keyring of signer1078 * @param collectionId ID of collection1079 * @param tokenId ID of token1080 * @param addressObj address of a new owner1081 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1082 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1083 * @returns true if the token success, otherwise false1084 */1085 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1086 const result = await this.helper.executeExtrinsic(1087 signer,1088 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1089 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1090 );10911092 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1093 }10941095 /**1096 *1097 * Change ownership of a token(s) on behalf of the owner.1098 *1099 * @param signer keyring of signer1100 * @param collectionId ID of collection1101 * @param tokenId ID of token1102 * @param fromAddressObj address on behalf of which the token will be sent1103 * @param toAddressObj new token owner1104 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1105 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1106 * @returns true if the token success, otherwise false1107 */1108 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1109 const result = await this.helper.executeExtrinsic(1110 signer,1111 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1112 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1113 );1114 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1115 }11161117 /**1118 *1119 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1120 *1121 * @param signer keyring of signer1122 * @param collectionId ID of collection1123 * @param tokenId ID of token1124 * @param amount amount of tokens to be burned. For NFT must be set to 1n1125 * @example burnToken(aliceKeyring, 10, 5);1126 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1127 */1128 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1129 const burnResult = await this.helper.executeExtrinsic(1130 signer,1131 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1132 true, // `Unable to burn token for ${label}`,1133 );1134 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1135 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1136 return burnedTokens.success;1137 }11381139 /**1140 * Destroys a concrete instance of NFT on behalf of the owner1141 *1142 * @param signer keyring of signer1143 * @param collectionId ID of collection1144 * @param tokenId ID of token1145 * @param fromAddressObj address on behalf of which the token will be burnt1146 * @param amount amount of tokens to be burned. For NFT must be set to 1n1147 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1148 * @returns ```true``` if extrinsic success, otherwise ```false```1149 */1150 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1151 const burnResult = await this.helper.executeExtrinsic(1152 signer,1153 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1154 true, // `Unable to burn token from for ${label}`,1155 );1156 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1157 return burnedTokens.success && burnedTokens.tokens.length > 0;1158 }11591160 /**1161 * Set, change, or remove approved address to transfer the ownership of the NFT.1162 *1163 * @param signer keyring of signer1164 * @param collectionId ID of collection1165 * @param tokenId ID of token1166 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1167 * @param amount amount of token to be approved. For NFT must be set to 1n1168 * @returns ```true``` if extrinsic success, otherwise ```false```1169 */1170 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1171 const approveResult = await this.helper.executeExtrinsic(1172 signer,1173 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1174 true, // `Unable to approve token for ${label}`,1175 );11761177 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1178 }11791180 /**1181 * Get the amount of token pieces approved to transfer or burn. Normally 0.1182 *1183 * @param collectionId ID of collection1184 * @param tokenId ID of token1185 * @param toAccountObj address which is approved to use token pieces1186 * @param fromAccountObj address which may have allowed the use of its owned tokens1187 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1188 * @returns number of approved to transfer pieces1189 */1190 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1191 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1192 }11931194 /**1195 * Get the last created token ID in a collection1196 *1197 * @param collectionId ID of collection1198 * @example getLastTokenId(10);1199 * @returns id of the last created token1200 */1201 async getLastTokenId(collectionId: number): Promise<number> {1202 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1203 }12041205 /**1206 * Check if token exists1207 *1208 * @param collectionId ID of collection1209 * @param tokenId ID of token1210 * @example doesTokenExist(10, 20);1211 * @returns true if the token exists, otherwise false1212 */1213 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1214 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1215 }1216}12171218class NFTnRFT extends CollectionGroup {1219 /**1220 * Get tokens owned by account1221 *1222 * @param collectionId ID of collection1223 * @param addressObj tokens owner1224 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1225 * @returns array of token ids owned by account1226 */1227 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1228 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1229 }12301231 /**1232 * Get token data1233 *1234 * @param collectionId ID of collection1235 * @param tokenId ID of token1236 * @param propertyKeys optionally filter the token properties to only these keys1237 * @param blockHashAt optionally query the data at some block with this hash1238 * @example getToken(10, 5);1239 * @returns human readable token data1240 */1241 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1242 properties: IProperty[];1243 owner: CrossAccountId;1244 normalizedOwner: CrossAccountId;1245 }| null> {1246 let tokenData;1247 if(typeof blockHashAt === 'undefined') {1248 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1249 }1250 else {1251 if(propertyKeys.length == 0) {1252 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1253 if(!collection) return null;1254 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1255 }1256 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1257 }1258 tokenData = tokenData.toHuman();1259 if (tokenData === null || tokenData.owner === null) return null;1260 const owner = {} as any;1261 for (const key of Object.keys(tokenData.owner)) {1262 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1263 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1264 : tokenData.owner[key];1265 }1266 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1267 return tokenData;1268 }12691270 /**1271 * Set permissions to change token properties1272 *1273 * @param signer keyring of signer1274 * @param collectionId ID of collection1275 * @param permissions permissions to change a property by the collection admin or token owner1276 * @example setTokenPropertyPermissions(1277 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1278 * )1279 * @returns true if extrinsic success otherwise false1280 */1281 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1282 const result = await this.helper.executeExtrinsic(1283 signer,1284 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1285 true,1286 );12871288 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1289 }12901291 /**1292 * Get token property permissions.1293 * 1294 * @param collectionId ID of collection1295 * @param propertyKeys optionally filter the returned property permissions to only these keys1296 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1297 * @returns array of key-permission pairs1298 */1299 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1300 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1301 }13021303 /**1304 * Set token properties1305 *1306 * @param signer keyring of signer1307 * @param collectionId ID of collection1308 * @param tokenId ID of token1309 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1310 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1311 * @returns ```true``` if extrinsic success, otherwise ```false```1312 */1313 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1314 const result = await this.helper.executeExtrinsic(1315 signer,1316 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1317 true,1318 );13191320 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1321 }13221323 /**1324 * Get properties, metadata assigned to a token.1325 * 1326 * @param collectionId ID of collection1327 * @param tokenId ID of token1328 * @param propertyKeys optionally filter the returned properties to only these keys1329 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1330 * @returns array of key-value pairs1331 */1332 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1333 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1334 }13351336 /**1337 * Delete the provided properties of a token1338 * @param signer keyring of signer1339 * @param collectionId ID of collection1340 * @param tokenId ID of token1341 * @param propertyKeys property keys to be deleted1342 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1343 * @returns ```true``` if extrinsic success, otherwise ```false```1344 */1345 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1346 const result = await this.helper.executeExtrinsic(1347 signer,1348 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1349 true,1350 );13511352 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1353 }13541355 /**1356 * Mint new collection1357 *1358 * @param signer keyring of signer1359 * @param collectionOptions basic collection options and properties1360 * @param mode NFT or RFT type of a collection1361 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1362 * @returns object of the created collection1363 */1364 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1365 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1366 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1367 for (const key of ['name', 'description', 'tokenPrefix']) {1368 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);1369 }1370 const creationResult = await this.helper.executeExtrinsic(1371 signer,1372 'api.tx.unique.createCollectionEx', [collectionOptions],1373 true, // errorLabel,1374 );1375 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1376 }13771378 getCollectionObject(_collectionId: number): any {1379 return null;1380 }13811382 getTokenObject(_collectionId: number, _tokenId: number): any {1383 return null;1384 }1385}138613871388class NFTGroup extends NFTnRFT {1389 /**1390 * Get collection object1391 * @param collectionId ID of collection1392 * @example getCollectionObject(2);1393 * @returns instance of UniqueNFTCollection1394 */1395 getCollectionObject(collectionId: number): UniqueNFTCollection {1396 return new UniqueNFTCollection(collectionId, this.helper);1397 }13981399 /**1400 * Get token object1401 * @param collectionId ID of collection1402 * @param tokenId ID of token1403 * @example getTokenObject(10, 5);1404 * @returns instance of UniqueNFTToken1405 */1406 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1407 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1408 }14091410 /**1411 * Get token's owner1412 * @param collectionId ID of collection1413 * @param tokenId ID of token1414 * @param blockHashAt optionally query the data at the block with this hash1415 * @example getTokenOwner(10, 5);1416 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1417 */1418 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1419 let owner;1420 if (typeof blockHashAt === 'undefined') {1421 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1422 } else {1423 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1424 }1425 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1426 }14271428 /**1429 * Is token approved to transfer1430 * @param collectionId ID of collection1431 * @param tokenId ID of token1432 * @param toAccountObj address to be approved1433 * @returns ```true``` if extrinsic success, otherwise ```false```1434 */1435 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1436 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1437 }14381439 /**1440 * Changes the owner of the token.1441 *1442 * @param signer keyring of signer1443 * @param collectionId ID of collection1444 * @param tokenId ID of token1445 * @param addressObj address of a new owner1446 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1447 * @returns ```true``` if extrinsic success, otherwise ```false```1448 */1449 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1450 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1451 }14521453 /**1454 *1455 * Change ownership of a NFT on behalf of the owner.1456 *1457 * @param signer keyring of signer1458 * @param collectionId ID of collection1459 * @param tokenId ID of token1460 * @param fromAddressObj address on behalf of which the token will be sent1461 * @param toAddressObj new token owner1462 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1463 * @returns ```true``` if extrinsic success, otherwise ```false```1464 */1465 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1466 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1467 }14681469 /**1470 * Recursively find the address that owns the token1471 * @param collectionId ID of collection1472 * @param tokenId ID of token1473 * @param blockHashAt1474 * @example getTokenTopmostOwner(10, 5);1475 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1476 */1477 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1478 let owner;1479 if (typeof blockHashAt === 'undefined') {1480 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1481 } else {1482 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1483 }14841485 if (owner === null) return null;14861487 return owner.toHuman();1488 }14891490 /**1491 * Get tokens nested in the provided token1492 * @param collectionId ID of collection1493 * @param tokenId ID of token1494 * @param blockHashAt optionally query the data at the block with this hash1495 * @example getTokenChildren(10, 5);1496 * @returns tokens whose depth of nesting is <= 51497 */1498 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1499 let children;1500 if(typeof blockHashAt === 'undefined') {1501 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1502 } else {1503 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1504 }15051506 return children.toJSON().map((x: any) => {1507 return {collectionId: x.collection, tokenId: x.token};1508 });1509 }15101511 /**1512 * Nest one token into another1513 * @param signer keyring of signer1514 * @param tokenObj token to be nested1515 * @param rootTokenObj token to be parent1516 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1517 * @returns ```true``` if extrinsic success, otherwise ```false```1518 */1519 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1520 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1521 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1522 if(!result) {1523 throw Error('Unable to nest token!');1524 }1525 return result;1526 }15271528 /**1529 * Remove token from nested state1530 * @param signer keyring of signer1531 * @param tokenObj token to unnest1532 * @param rootTokenObj parent of a token1533 * @param toAddressObj address of a new token owner1534 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1535 * @returns ```true``` if extrinsic success, otherwise ```false```1536 */1537 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1538 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1539 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1540 if(!result) {1541 throw Error('Unable to unnest token!');1542 }1543 return result;1544 }15451546 /**1547 * Mint new collection1548 * @param signer keyring of signer1549 * @param collectionOptions Collection options1550 * @example1551 * mintCollection(aliceKeyring, {1552 * name: 'New',1553 * description: 'New collection',1554 * tokenPrefix: 'NEW',1555 * })1556 * @returns object of the created collection1557 */1558 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1559 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1560 }15611562 /**1563 * Mint new token1564 * @param signer keyring of signer1565 * @param data token data1566 * @returns created token object1567 */1568 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1569 const creationResult = await this.helper.executeExtrinsic(1570 signer,1571 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1572 nft: {1573 properties: data.properties,1574 },1575 }],1576 true,1577 );1578 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1579 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1580 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1581 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1582 }15831584 /**1585 * Mint multiple NFT tokens1586 * @param signer keyring of signer1587 * @param collectionId ID of collection1588 * @param tokens array of tokens with owner and properties1589 * @example1590 * mintMultipleTokens(aliceKeyring, 10, [{1591 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1592 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1593 * },{1594 * owner: {Ethereum: "0x9F0583DbB855d..."},1595 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1596 * }]);1597 * @returns ```true``` if extrinsic success, otherwise ```false```1598 */1599 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1600 const creationResult = await this.helper.executeExtrinsic(1601 signer,1602 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1603 true,1604 );1605 const collection = this.getCollectionObject(collectionId);1606 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1607 }16081609 /**1610 * Mint multiple NFT tokens with one owner1611 * @param signer keyring of signer1612 * @param collectionId ID of collection1613 * @param owner tokens owner1614 * @param tokens array of tokens with owner and properties1615 * @example1616 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1617 * properties: [{1618 * key: "gender",1619 * value: "female",1620 * },{1621 * key: "age",1622 * value: "33",1623 * }],1624 * }]);1625 * @returns array of newly created tokens1626 */1627 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1628 const rawTokens = [];1629 for (const token of tokens) {1630 const raw = {NFT: {properties: token.properties}};1631 rawTokens.push(raw);1632 }1633 const creationResult = await this.helper.executeExtrinsic(1634 signer,1635 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1636 true,1637 );1638 const collection = this.getCollectionObject(collectionId);1639 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1640 }16411642 /**1643 * Set, change, or remove approved address to transfer the ownership of the NFT.1644 *1645 * @param signer keyring of signer1646 * @param collectionId ID of collection1647 * @param tokenId ID of token1648 * @param toAddressObj address to approve1649 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1650 * @returns ```true``` if extrinsic success, otherwise ```false```1651 */1652 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1653 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1654 }1655}165616571658class RFTGroup extends NFTnRFT {1659 /**1660 * Get collection object1661 * @param collectionId ID of collection1662 * @example getCollectionObject(2);1663 * @returns instance of UniqueRFTCollection1664 */1665 getCollectionObject(collectionId: number): UniqueRFTCollection {1666 return new UniqueRFTCollection(collectionId, this.helper);1667 }16681669 /**1670 * Get token object1671 * @param collectionId ID of collection1672 * @param tokenId ID of token1673 * @example getTokenObject(10, 5);1674 * @returns instance of UniqueNFTToken1675 */1676 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1677 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1678 }16791680 /**1681 * Get top 10 token owners with the largest number of pieces1682 * @param collectionId ID of collection1683 * @param tokenId ID of token1684 * @example getTokenTop10Owners(10, 5);1685 * @returns array of top 10 owners1686 */1687 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1688 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1689 }16901691 /**1692 * Get number of pieces owned by address1693 * @param collectionId ID of collection1694 * @param tokenId ID of token1695 * @param addressObj address token owner1696 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1697 * @returns number of pieces ownerd by address1698 */1699 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1700 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1701 }17021703 /**1704 * Transfer pieces of token to another address1705 * @param signer keyring of signer1706 * @param collectionId ID of collection1707 * @param tokenId ID of token1708 * @param addressObj address of a new owner1709 * @param amount number of pieces to be transfered1710 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1711 * @returns ```true``` if extrinsic success, otherwise ```false```1712 */1713 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1714 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1715 }17161717 /**1718 * Change ownership of some pieces of RFT on behalf of the owner.1719 * @param signer keyring of signer1720 * @param collectionId ID of collection1721 * @param tokenId ID of token1722 * @param fromAddressObj address on behalf of which the token will be sent1723 * @param toAddressObj new token owner1724 * @param amount number of pieces to be transfered1725 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1726 * @returns ```true``` if extrinsic success, otherwise ```false```1727 */1728 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1729 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1730 }17311732 /**1733 * Mint new collection1734 * @param signer keyring of signer1735 * @param collectionOptions Collection options1736 * @example1737 * mintCollection(aliceKeyring, {1738 * name: 'New',1739 * description: 'New collection',1740 * tokenPrefix: 'NEW',1741 * })1742 * @returns object of the created collection1743 */1744 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1745 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1746 }17471748 /**1749 * Mint new token1750 * @param signer keyring of signer1751 * @param data token data1752 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1753 * @returns created token object1754 */1755 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1756 const creationResult = await this.helper.executeExtrinsic(1757 signer,1758 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1759 refungible: {1760 pieces: data.pieces,1761 properties: data.properties,1762 },1763 }],1764 true,1765 );1766 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1767 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1768 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1769 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1770 }17711772 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1773 throw Error('Not implemented');1774 const creationResult = await this.helper.executeExtrinsic(1775 signer,1776 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1777 true, // `Unable to mint RFT tokens for ${label}`,1778 );1779 const collection = this.getCollectionObject(collectionId);1780 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1781 }17821783 /**1784 * Mint multiple RFT tokens with one owner1785 * @param signer keyring of signer1786 * @param collectionId ID of collection1787 * @param owner tokens owner1788 * @param tokens array of tokens with properties and pieces1789 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1790 * @returns array of newly created RFT tokens1791 */1792 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1793 const rawTokens = [];1794 for (const token of tokens) {1795 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1796 rawTokens.push(raw);1797 }1798 const creationResult = await this.helper.executeExtrinsic(1799 signer,1800 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1801 true,1802 );1803 const collection = this.getCollectionObject(collectionId);1804 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1805 }18061807 /**1808 * Destroys a concrete instance of RFT.1809 * @param signer keyring of signer1810 * @param collectionId ID of collection1811 * @param tokenId ID of token1812 * @param amount number of pieces to be burnt1813 * @example burnToken(aliceKeyring, 10, 5);1814 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1815 */1816 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1817 return await super.burnToken(signer, collectionId, tokenId, amount);1818 }18191820 /**1821 * Destroys a concrete instance of RFT on behalf of the owner.1822 * @param signer keyring of signer1823 * @param collectionId ID of collection1824 * @param tokenId ID of token1825 * @param fromAddressObj address on behalf of which the token will be burnt1826 * @param amount number of pieces to be burnt1827 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1828 * @returns ```true``` if extrinsic success, otherwise ```false```1829 */1830 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1831 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1832 }18331834 /**1835 * Set, change, or remove approved address to transfer the ownership of the RFT.1836 *1837 * @param signer keyring of signer1838 * @param collectionId ID of collection1839 * @param tokenId ID of token1840 * @param toAddressObj address to approve1841 * @param amount number of pieces to be approved1842 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1843 * @returns true if the token success, otherwise false1844 */1845 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1846 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1847 }18481849 /**1850 * Get total number of pieces1851 * @param collectionId ID of collection1852 * @param tokenId ID of token1853 * @example getTokenTotalPieces(10, 5);1854 * @returns number of pieces1855 */1856 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1857 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1858 }18591860 /**1861 * Change number of token pieces. Signer must be the owner of all token pieces.1862 * @param signer keyring of signer1863 * @param collectionId ID of collection1864 * @param tokenId ID of token1865 * @param amount new number of pieces1866 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1867 * @returns true if the repartion was success, otherwise false1868 */1869 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1870 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1871 const repartitionResult = await this.helper.executeExtrinsic(1872 signer,1873 'api.tx.unique.repartition', [collectionId, tokenId, amount],1874 true,1875 );1876 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1877 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1878 }1879}188018811882class FTGroup extends CollectionGroup {1883 /**1884 * Get collection object1885 * @param collectionId ID of collection1886 * @example getCollectionObject(2);1887 * @returns instance of UniqueFTCollection1888 */1889 getCollectionObject(collectionId: number): UniqueFTCollection {1890 return new UniqueFTCollection(collectionId, this.helper);1891 }18921893 /**1894 * Mint new fungible collection1895 * @param signer keyring of signer1896 * @param collectionOptions Collection options1897 * @param decimalPoints number of token decimals1898 * @example1899 * mintCollection(aliceKeyring, {1900 * name: 'New',1901 * description: 'New collection',1902 * tokenPrefix: 'NEW',1903 * }, 18)1904 * @returns newly created fungible collection1905 */1906 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1907 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1908 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1909 collectionOptions.mode = {fungible: decimalPoints};1910 for (const key of ['name', 'description', 'tokenPrefix']) {1911 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);1912 }1913 const creationResult = await this.helper.executeExtrinsic(1914 signer,1915 'api.tx.unique.createCollectionEx', [collectionOptions],1916 true,1917 );1918 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1919 }19201921 /**1922 * Mint tokens1923 * @param signer keyring of signer1924 * @param collectionId ID of collection1925 * @param owner address owner of new tokens1926 * @param amount amount of tokens to be meanted1927 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1928 * @returns ```true``` if extrinsic success, otherwise ```false```1929 */1930 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1931 const creationResult = await this.helper.executeExtrinsic(1932 signer,1933 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1934 fungible: {1935 value: amount,1936 },1937 }],1938 true, // `Unable to mint fungible tokens for ${label}`,1939 );1940 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1941 }19421943 /**1944 * Mint multiple Fungible tokens with one owner1945 * @param signer keyring of signer1946 * @param collectionId ID of collection1947 * @param owner tokens owner1948 * @param tokens array of tokens with properties and pieces1949 * @returns ```true``` if extrinsic success, otherwise ```false```1950 */1951 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1952 const rawTokens = [];1953 for (const token of tokens) {1954 const raw = {Fungible: {Value: token.value}};1955 rawTokens.push(raw);1956 }1957 const creationResult = await this.helper.executeExtrinsic(1958 signer,1959 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1960 true,1961 );1962 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1963 }19641965 /**1966 * Get the top 10 owners with the largest balance for the Fungible collection1967 * @param collectionId ID of collection1968 * @example getTop10Owners(10);1969 * @returns array of ```ICrossAccountId```1970 */1971 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1972 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1973 }19741975 /**1976 * Get account balance1977 * @param collectionId ID of collection1978 * @param addressObj address of owner1979 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1980 * @returns amount of fungible tokens owned by address1981 */1982 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1983 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1984 }19851986 /**1987 * Transfer tokens to address1988 * @param signer keyring of signer1989 * @param collectionId ID of collection1990 * @param toAddressObj address recipient1991 * @param amount amount of tokens to be sent1992 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1993 * @returns ```true``` if extrinsic success, otherwise ```false```1994 */1995 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1996 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1997 }19981999 /**2000 * Transfer some tokens on behalf of the owner.2001 * @param signer keyring of signer2002 * @param collectionId ID of collection2003 * @param fromAddressObj address on behalf of which tokens will be sent2004 * @param toAddressObj address where token to be sent2005 * @param amount number of tokens to be sent2006 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2007 * @returns ```true``` if extrinsic success, otherwise ```false```2008 */2009 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2010 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2011 }20122013 /**2014 * Destroy some amount of tokens2015 * @param signer keyring of signer2016 * @param collectionId ID of collection2017 * @param amount amount of tokens to be destroyed2018 * @example burnTokens(aliceKeyring, 10, 1000n);2019 * @returns ```true``` if extrinsic success, otherwise ```false```2020 */2021 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2022 return await super.burnToken(signer, collectionId, 0, amount);2023 }20242025 /**2026 * Burn some tokens on behalf of the owner.2027 * @param signer keyring of signer2028 * @param collectionId ID of collection2029 * @param fromAddressObj address on behalf of which tokens will be burnt2030 * @param amount amount of tokens to be burnt2031 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2032 * @returns ```true``` if extrinsic success, otherwise ```false```2033 */2034 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2035 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2036 }20372038 /**2039 * Get total collection supply2040 * @param collectionId2041 * @returns2042 */2043 async getTotalPieces(collectionId: number): Promise<bigint> {2044 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2045 }20462047 /**2048 * Set, change, or remove approved address to transfer tokens.2049 *2050 * @param signer keyring of signer2051 * @param collectionId ID of collection2052 * @param toAddressObj address to be approved2053 * @param amount amount of tokens to be approved2054 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2055 * @returns ```true``` if extrinsic success, otherwise ```false```2056 */2057 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2058 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2059 }20602061 /**2062 * Get amount of fungible tokens approved to transfer2063 * @param collectionId ID of collection2064 * @param fromAddressObj owner of tokens2065 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2066 * @returns number of tokens approved for the transfer2067 */2068 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2069 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2070 }2071}207220732074class ChainGroup extends HelperGroup<ChainHelperBase> {2075 /**2076 * Get system properties of a chain2077 * @example getChainProperties();2078 * @returns ss58Format, token decimals, and token symbol2079 */2080 getChainProperties(): IChainProperties {2081 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2082 return {2083 ss58Format: properties.ss58Format.toJSON(),2084 tokenDecimals: properties.tokenDecimals.toJSON(),2085 tokenSymbol: properties.tokenSymbol.toJSON(),2086 };2087 }20882089 /**2090 * Get chain header2091 * @example getLatestBlockNumber();2092 * @returns the number of the last block2093 */2094 async getLatestBlockNumber(): Promise<number> {2095 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2096 }20972098 /**2099 * Get block hash by block number2100 * @param blockNumber number of block2101 * @example getBlockHashByNumber(12345);2102 * @returns hash of a block2103 */2104 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2105 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2106 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2107 return blockHash;2108 }21092110 // TODO add docs2111 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2112 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2113 if (!blockHash) return null;2114 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2115 }21162117 /**2118 * Get account nonce2119 * @param address substrate address2120 * @example getNonce("5GrwvaEF5zXb26Fz...");2121 * @returns number, account's nonce2122 */2123 async getNonce(address: TSubstrateAccount): Promise<number> {2124 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2125 }2126}21272128class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2129 /**2130 * Get substrate address balance2131 * @param address substrate address2132 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2133 * @returns amount of tokens on address2134 */2135 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2136 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2137 }21382139 /**2140 * Transfer tokens to substrate address2141 * @param signer keyring of signer2142 * @param address substrate address of a recipient2143 * @param amount amount of tokens to be transfered2144 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2145 * @returns ```true``` if extrinsic success, otherwise ```false```2146 */2147 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2148 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}`*/);21492150 let transfer = {from: null, to: null, amount: 0n} as any;2151 result.result.events.forEach(({event: {data, method, section}}) => {2152 if ((section === 'balances') && (method === 'Transfer')) {2153 transfer = {2154 from: this.helper.address.normalizeSubstrate(data[0]),2155 to: this.helper.address.normalizeSubstrate(data[1]),2156 amount: BigInt(data[2]),2157 };2158 }2159 });2160 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2161 && this.helper.address.normalizeSubstrate(address) === transfer.to 2162 && BigInt(amount) === transfer.amount;2163 return isSuccess;2164 }21652166 /**2167 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2168 * @param address substrate address2169 * @returns2170 */2171 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2172 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2173 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2174 }2175}21762177class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2178 /**2179 * Get ethereum address balance2180 * @param address ethereum address2181 * @example getEthereum("0x9F0583DbB855d...")2182 * @returns amount of tokens on address2183 */2184 async getEthereum(address: TEthereumAccount): Promise<bigint> {2185 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2186 }21872188 /**2189 * Transfer tokens to address2190 * @param signer keyring of signer2191 * @param address Ethereum address of a recipient2192 * @param amount amount of tokens to be transfered2193 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2194 * @returns ```true``` if extrinsic success, otherwise ```false```2195 */2196 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2197 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);21982199 let transfer = {from: null, to: null, amount: 0n} as any;2200 result.result.events.forEach(({event: {data, method, section}}) => {2201 if ((section === 'balances') && (method === 'Transfer')) {2202 transfer = {2203 from: data[0].toString(),2204 to: data[1].toString(),2205 amount: BigInt(data[2]),2206 };2207 }2208 });2209 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from 2210 && address === transfer.to 2211 && BigInt(amount) === transfer.amount;2212 return isSuccess;2213 }2214}22152216class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2217 subBalanceGroup: SubstrateBalanceGroup<T>;2218 ethBalanceGroup: EthereumBalanceGroup<T>;22192220 constructor(helper: T) {2221 super(helper);2222 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2223 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2224 }22252226 getCollectionCreationPrice(): bigint {2227 return 2n * this.getOneTokenNominal();2228 }2229 /**2230 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2231 * @example getOneTokenNominal()2232 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2233 */2234 getOneTokenNominal(): bigint {2235 const chainProperties = this.helper.chain.getChainProperties();2236 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2237 }22382239 /**2240 * Get substrate address balance2241 * @param address substrate address2242 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2243 * @returns amount of tokens on address2244 */2245 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2246 return this.subBalanceGroup.getSubstrate(address);2247 }22482249 /**2250 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2251 * @param address substrate address2252 * @returns2253 */2254 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2255 return this.subBalanceGroup.getSubstrateFull(address);2256 }22572258 /**2259 * Get ethereum address balance2260 * @param address ethereum address2261 * @example getEthereum("0x9F0583DbB855d...")2262 * @returns amount of tokens on address2263 */2264 async getEthereum(address: TEthereumAccount): Promise<bigint> {2265 return this.ethBalanceGroup.getEthereum(address);2266 }22672268 /**2269 * Transfer tokens to substrate address2270 * @param signer keyring of signer2271 * @param address substrate address of a recipient2272 * @param amount amount of tokens to be transfered2273 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2274 * @returns ```true``` if extrinsic success, otherwise ```false```2275 */2276 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2277 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2278 }22792280 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2281 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);22822283 let transfer = {from: null, to: null, amount: 0n} as any;2284 result.result.events.forEach(({event: {data, method, section}}) => {2285 if ((section === 'balances') && (method === 'Transfer')) {2286 transfer = {2287 from: this.helper.address.normalizeSubstrate(data[0]),2288 to: this.helper.address.normalizeSubstrate(data[1]),2289 amount: BigInt(data[2]),2290 };2291 }2292 });2293 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2294 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2295 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2296 return isSuccess;2297 }2298}22992300class AddressGroup extends HelperGroup<ChainHelperBase> {2301 /**2302 * Normalizes the address to the specified ss58 format, by default ```42```.2303 * @param address substrate address2304 * @param ss58Format format for address conversion, by default ```42```2305 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2306 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2307 */2308 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2309 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2310 }23112312 /**2313 * Get address in the connected chain format2314 * @param address substrate address2315 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2316 * @returns address in chain format2317 */2318 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2319 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2320 }23212322 /**2323 * Get substrate mirror of an ethereum address2324 * @param ethAddress ethereum address2325 * @param toChainFormat false for normalized account2326 * @example ethToSubstrate('0x9F0583DbB855d...')2327 * @returns substrate mirror of a provided ethereum address2328 */2329 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2330 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2331 }23322333 /**2334 * Get ethereum mirror of a substrate address2335 * @param subAddress substrate account2336 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2337 * @returns ethereum mirror of a provided substrate address2338 */2339 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2340 return CrossAccountId.translateSubToEth(subAddress);2341 }23422343 paraSiblingSovereignAccount(paraid: number) {2344 // We are getting a *sibling* parachain sovereign account,2345 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2346 const siblingPrefix = '0x7369626c';23472348 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2349 const suffix = '000000000000000000000000000000000000000000000000';23502351 return siblingPrefix + encodedParaId + suffix;2352 }2353}23542355class StakingGroup extends HelperGroup<UniqueHelper> {2356 /**2357 * Stake tokens for App Promotion2358 * @param signer keyring of signer2359 * @param amountToStake amount of tokens to stake2360 * @param label extra label for log2361 * @returns2362 */2363 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2364 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2365 const _stakeResult = await this.helper.executeExtrinsic(2366 signer, 'api.tx.appPromotion.stake',2367 [amountToStake], true,2368 );2369 // TODO extract info from stakeResult2370 return true;2371 }23722373 /**2374 * Unstake tokens for App Promotion2375 * @param signer keyring of signer2376 * @param amountToUnstake amount of tokens to unstake2377 * @param label extra label for log2378 * @returns block number where balances will be unlocked2379 */2380 async unstake(signer: TSigner, label?: string): Promise<number> {2381 if(typeof label === 'undefined') label = `${signer.address}`;2382 const _unstakeResult = await this.helper.executeExtrinsic(2383 signer, 'api.tx.appPromotion.unstake',2384 [], true,2385 );2386 // TODO extract block number fron events2387 return 1;2388 }23892390 /**2391 * Get total staked amount for address2392 * @param address substrate or ethereum address2393 * @returns total staked amount2394 */2395 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2396 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2397 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2398 }23992400 /**2401 * Get total staked per block2402 * @param address substrate or ethereum address2403 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2404 */2405 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2406 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2407 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2408 return { 2409 block: block.toBigInt(),2410 amount: amount.toBigInt(),2411 };2412 });2413 }24142415 /**2416 * Get total pending unstake amount for address2417 * @param address substrate or ethereum address2418 * @returns total pending unstake amount2419 */2420 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2421 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2422 }24232424 /**2425 * Get pending unstake amount per block for address2426 * @param address substrate or ethereum address2427 * @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 block2428 */2429 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2430 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2431 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2432 return {2433 block: block.toBigInt(),2434 amount: amount.toBigInt(),2435 };2436 });2437 return result;2438 }2439}24402441class SchedulerGroup extends HelperGroup<UniqueHelper> {2442 constructor(helper: UniqueHelper) {2443 super(helper);2444 }24452446 async cancelScheduled(signer: TSigner, scheduledId: string) {2447 return this.helper.executeExtrinsic(2448 signer,2449 'api.tx.scheduler.cancelNamed',2450 [scheduledId],2451 true,2452 );2453 }24542455 async changePriority(signer: TSigner, scheduledId: string, priority: number) {2456 return this.helper.executeExtrinsic(2457 signer,2458 'api.tx.scheduler.changeNamedPriority',2459 [scheduledId, priority],2460 true,2461 );2462 }24632464 scheduleAt<T extends UniqueHelper>(2465 scheduledId: string,2466 executionBlockNumber: number,2467 options: ISchedulerOptions = {},2468 ) {2469 return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2470 }24712472 scheduleAfter<T extends UniqueHelper>(2473 scheduledId: string,2474 blocksBeforeExecution: number,2475 options: ISchedulerOptions = {},2476 ) {2477 return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2478 }24792480 schedule<T extends UniqueHelper>(2481 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2482 scheduledId: string,2483 blocksNum: number,2484 options: ISchedulerOptions = {},2485 ) {2486 // eslint-disable-next-line @typescript-eslint/naming-convention2487 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2488 return this.helper.clone(ScheduledHelperType, {2489 scheduleFn,2490 scheduledId,2491 blocksNum,2492 options,2493 }) as T;2494 }2495}24962497class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2498 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2499 await this.helper.executeExtrinsic(2500 signer,2501 'api.tx.foreignAssets.registerForeignAsset',2502 [ownerAddress, location, metadata],2503 true,2504 );2505 }25062507 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2508 await this.helper.executeExtrinsic(2509 signer,2510 'api.tx.foreignAssets.updateForeignAsset',2511 [foreignAssetId, location, metadata],2512 true,2513 );2514 }2515}25162517class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2518 palletName: string;25192520 constructor(helper: T, palletName: string) {2521 super(helper);25222523 this.palletName = palletName;2524 }25252526 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2527 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2528 }2529}25302531class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2532 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2533 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2534 }25352536 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2537 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2538 }25392540 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2541 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2542 }2543}25442545class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2546 async accounts(address: string, currencyId: any) {2547 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2548 return BigInt(free);2549 }2550}25512552class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2553 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2554 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2555 }25562557 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2558 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2559 }25602561 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2562 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2563 }25642565 async account(assetId: string | number, address: string) {2566 const accountAsset = (2567 await this.helper.callRpc('api.query.assets.account', [assetId, address])2568 ).toJSON()! as any;25692570 if (accountAsset !== null) {2571 return BigInt(accountAsset['balance']);2572 } else {2573 return null;2574 }2575 }2576}25772578class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2579 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2580 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2581 }2582}25832584class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2585 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2586 const apiPrefix = 'api.tx.assetManager.';25872588 const registerTx = this.helper.constructApiCall(2589 apiPrefix + 'registerForeignAsset',2590 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2591 );25922593 const setUnitsTx = this.helper.constructApiCall(2594 apiPrefix + 'setAssetUnitsPerSecond',2595 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2596 );25972598 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2599 const encodedProposal = batchCall?.method.toHex() || '';2600 return encodedProposal;2601 }26022603 async assetTypeId(location: any) {2604 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2605 }2606}26072608class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2609 async notePreimage(signer: TSigner, encodedProposal: string) {2610 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2611 }26122613 externalProposeMajority(proposalHash: string) {2614 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2615 }26162617 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2618 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2619 }26202621 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2622 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2623 }2624}26252626class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2627 collective: string;26282629 constructor(helper: MoonbeamHelper, collective: string) {2630 super(helper);26312632 this.collective = collective;2633 }26342635 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2636 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2637 }26382639 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2640 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2641 }26422643 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2644 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2645 }26462647 async proposalCount() {2648 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2649 }2650}26512652export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2653export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;26542655export class UniqueHelper extends ChainHelperBase {2656 balance: BalanceGroup<UniqueHelper>;2657 collection: CollectionGroup;2658 nft: NFTGroup;2659 rft: RFTGroup;2660 ft: FTGroup;2661 staking: StakingGroup;2662 scheduler: SchedulerGroup;2663 foreignAssets: ForeignAssetsGroup;2664 xcm: XcmGroup<UniqueHelper>;2665 xTokens: XTokensGroup<UniqueHelper>;2666 tokens: TokensGroup<UniqueHelper>;26672668 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2669 super(logger, options.helperBase ?? UniqueHelper);26702671 this.balance = new BalanceGroup(this);2672 this.collection = new CollectionGroup(this);2673 this.nft = new NFTGroup(this);2674 this.rft = new RFTGroup(this);2675 this.ft = new FTGroup(this);2676 this.staking = new StakingGroup(this);2677 this.scheduler = new SchedulerGroup(this);2678 this.foreignAssets = new ForeignAssetsGroup(this);2679 this.xcm = new XcmGroup(this, 'polkadotXcm');2680 this.xTokens = new XTokensGroup(this);2681 this.tokens = new TokensGroup(this);2682 }26832684 getSudo<T extends UniqueHelper>() {2685 // eslint-disable-next-line @typescript-eslint/naming-convention2686 const SudoHelperType = SudoHelper(this.helperBase);2687 return this.clone(SudoHelperType) as T;2688 }2689}26902691export class XcmChainHelper extends ChainHelperBase {2692 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2693 const wsProvider = new WsProvider(wsEndpoint);2694 this.api = new ApiPromise({2695 provider: wsProvider,2696 });2697 await this.api.isReadyOrError;2698 this.network = await UniqueHelper.detectNetwork(this.api);2699 }2700}27012702export class RelayHelper extends XcmChainHelper {2703 xcm: XcmGroup<RelayHelper>;27042705 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2706 super(logger, options.helperBase ?? RelayHelper);27072708 this.xcm = new XcmGroup(this, 'xcmPallet');2709 }2710}27112712export class WestmintHelper extends XcmChainHelper {2713 balance: SubstrateBalanceGroup<WestmintHelper>;2714 xcm: XcmGroup<WestmintHelper>;2715 assets: AssetsGroup<WestmintHelper>;2716 xTokens: XTokensGroup<WestmintHelper>;27172718 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2719 super(logger, options.helperBase ?? WestmintHelper);27202721 this.balance = new SubstrateBalanceGroup(this);2722 this.xcm = new XcmGroup(this, 'polkadotXcm');2723 this.assets = new AssetsGroup(this);2724 this.xTokens = new XTokensGroup(this);2725 }2726}27272728export class MoonbeamHelper extends XcmChainHelper {2729 balance: EthereumBalanceGroup<MoonbeamHelper>;2730 assetManager: MoonbeamAssetManagerGroup;2731 assets: AssetsGroup<MoonbeamHelper>;2732 xTokens: XTokensGroup<MoonbeamHelper>;2733 democracy: MoonbeamDemocracyGroup;2734 collective: {2735 council: MoonbeamCollectiveGroup,2736 techCommittee: MoonbeamCollectiveGroup,2737 };27382739 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2740 super(logger, options.helperBase ?? MoonbeamHelper);27412742 this.balance = new EthereumBalanceGroup(this);2743 this.assetManager = new MoonbeamAssetManagerGroup(this);2744 this.assets = new AssetsGroup(this);2745 this.xTokens = new XTokensGroup(this);2746 this.democracy = new MoonbeamDemocracyGroup(this);2747 this.collective = {2748 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2749 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2750 };2751 }2752}27532754export class AcalaHelper extends XcmChainHelper {2755 balance: SubstrateBalanceGroup<AcalaHelper>;2756 assetRegistry: AcalaAssetRegistryGroup;2757 xTokens: XTokensGroup<AcalaHelper>;2758 tokens: TokensGroup<AcalaHelper>;27592760 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2761 super(logger, options.helperBase ?? AcalaHelper);27622763 this.balance = new SubstrateBalanceGroup(this);2764 this.assetRegistry = new AcalaAssetRegistryGroup(this);2765 this.xTokens = new XTokensGroup(this);2766 this.tokens = new TokensGroup(this);2767 }27682769 getSudo<T extends AcalaHelper>() {2770 // eslint-disable-next-line @typescript-eslint/naming-convention2771 const SudoHelperType = SudoHelper(this.helperBase);2772 return this.clone(SudoHelperType) as T;2773 }2774}27752776// eslint-disable-next-line @typescript-eslint/naming-convention2777function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2778 return class extends Base {2779 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2780 scheduledId: string;2781 blocksNum: number;2782 options: ISchedulerOptions;27832784 constructor(...args: any[]) {2785 const logger = args[0] as ILogger;2786 const options = args[1] as {2787 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2788 scheduledId: string,2789 blocksNum: number,2790 options: ISchedulerOptions2791 };27922793 super(logger);27942795 this.scheduleFn = options.scheduleFn;2796 this.scheduledId = options.scheduledId;2797 this.blocksNum = options.blocksNum;2798 this.options = options.options;2799 }28002801 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2802 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2803 const extrinsic = 'api.tx.scheduler.' + this.scheduleFn;28042805 return super.executeExtrinsic(2806 sender,2807 extrinsic,2808 [2809 this.scheduledId,2810 this.blocksNum,2811 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2812 this.options.priority ?? null,2813 {Value: scheduledTx},2814 ],2815 expectSuccess,2816 );2817 }2818 };2819}28202821// eslint-disable-next-line @typescript-eslint/naming-convention2822function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2823 return class extends Base {2824 constructor(...args: any[]) {2825 super(...args);2826 }28272828 executeExtrinsic (2829 sender: IKeyringPair,2830 extrinsic: string,2831 params: any[],2832 expectSuccess?: boolean,2833 ): Promise<ITransactionResult> {2834 const call = this.constructApiCall(extrinsic, params);2835 return super.executeExtrinsic(2836 sender,2837 'api.tx.sudo.sudo',2838 [call],2839 expectSuccess,2840 );2841 }2842 };2843}28442845export class UniqueBaseCollection {2846 helper: UniqueHelper;2847 collectionId: number;28482849 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2850 this.collectionId = collectionId;2851 this.helper = uniqueHelper;2852 }28532854 async getData() {2855 return await this.helper.collection.getData(this.collectionId);2856 }28572858 async getLastTokenId() {2859 return await this.helper.collection.getLastTokenId(this.collectionId);2860 }28612862 async doesTokenExist(tokenId: number) {2863 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2864 }28652866 async getAdmins() {2867 return await this.helper.collection.getAdmins(this.collectionId);2868 }28692870 async getAllowList() {2871 return await this.helper.collection.getAllowList(this.collectionId);2872 }28732874 async getEffectiveLimits() {2875 return await this.helper.collection.getEffectiveLimits(this.collectionId);2876 }28772878 async getProperties(propertyKeys?: string[] | null) {2879 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2880 }28812882 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2883 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2884 }28852886 async getOptions() {2887 return await this.helper.collection.getCollectionOptions(this.collectionId);2888 }28892890 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2891 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2892 }28932894 async confirmSponsorship(signer: TSigner) {2895 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2896 }28972898 async removeSponsor(signer: TSigner) {2899 return await this.helper.collection.removeSponsor(signer, this.collectionId);2900 }29012902 async setLimits(signer: TSigner, limits: ICollectionLimits) {2903 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2904 }29052906 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2907 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2908 }29092910 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2911 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2912 }29132914 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2915 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2916 }29172918 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2919 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2920 }29212922 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2923 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2924 }29252926 async setProperties(signer: TSigner, properties: IProperty[]) {2927 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2928 }29292930 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2931 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2932 }29332934 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2935 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2936 }29372938 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2939 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2940 }29412942 async disableNesting(signer: TSigner) {2943 return await this.helper.collection.disableNesting(signer, this.collectionId);2944 }29452946 async burn(signer: TSigner) {2947 return await this.helper.collection.burn(signer, this.collectionId);2948 }29492950 scheduleAt<T extends UniqueHelper>(2951 scheduledId: string,2952 executionBlockNumber: number,2953 options: ISchedulerOptions = {},2954 ) {2955 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2956 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2957 }29582959 scheduleAfter<T extends UniqueHelper>(2960 scheduledId: string,2961 blocksBeforeExecution: number,2962 options: ISchedulerOptions = {},2963 ) {2964 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2965 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2966 }29672968 getSudo<T extends UniqueHelper>() {2969 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2970 }2971}297229732974export class UniqueNFTCollection extends UniqueBaseCollection {2975 getTokenObject(tokenId: number) {2976 return new UniqueNFToken(tokenId, this);2977 }29782979 async getTokensByAddress(addressObj: ICrossAccountId) {2980 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2981 }29822983 async getToken(tokenId: number, blockHashAt?: string) {2984 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2985 }29862987 async getTokenOwner(tokenId: number, blockHashAt?: string) {2988 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2989 }29902991 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2992 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2993 }29942995 async getTokenChildren(tokenId: number, blockHashAt?: string) {2996 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2997 }29982999 async getPropertyPermissions(propertyKeys: string[] | null = null) {3000 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3001 }30023003 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3004 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3005 }30063007 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3008 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3009 }30103011 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3012 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3013 }30143015 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3016 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3017 }30183019 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3020 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3021 }30223023 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3024 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3025 }30263027 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3028 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3029 }30303031 async burnToken(signer: TSigner, tokenId: number) {3032 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3033 }30343035 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3036 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3037 }30383039 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3040 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3041 }30423043 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3044 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3045 }30463047 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3048 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3049 }30503051 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3052 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3053 }30543055 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3056 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3057 }30583059 scheduleAt<T extends UniqueHelper>(3060 scheduledId: string,3061 executionBlockNumber: number,3062 options: ISchedulerOptions = {},3063 ) {3064 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3065 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3066 }30673068 scheduleAfter<T extends UniqueHelper>(3069 scheduledId: string,3070 blocksBeforeExecution: number,3071 options: ISchedulerOptions = {},3072 ) {3073 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3074 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3075 }30763077 getSudo<T extends UniqueHelper>() {3078 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3079 }3080}308130823083export class UniqueRFTCollection extends UniqueBaseCollection {3084 getTokenObject(tokenId: number) {3085 return new UniqueRFToken(tokenId, this);3086 }30873088 async getToken(tokenId: number, blockHashAt?: string) {3089 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3090 }30913092 async getTokensByAddress(addressObj: ICrossAccountId) {3093 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3094 }30953096 async getTop10TokenOwners(tokenId: number) {3097 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3098 }30993100 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3101 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3102 }31033104 async getTokenTotalPieces(tokenId: number) {3105 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3106 }31073108 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3109 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3110 }31113112 async getPropertyPermissions(propertyKeys: string[] | null = null) {3113 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3114 }31153116 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3117 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3118 }31193120 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3121 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3122 }31233124 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3125 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3126 }31273128 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3129 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3130 }31313132 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3133 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3134 }31353136 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3137 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3138 }31393140 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3141 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3142 }31433144 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3145 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3146 }31473148 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3149 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3150 }31513152 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3153 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3154 }31553156 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3157 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3158 }31593160 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3161 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3162 }31633164 scheduleAt<T extends UniqueHelper>(3165 scheduledId: string,3166 executionBlockNumber: number,3167 options: ISchedulerOptions = {},3168 ) {3169 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3170 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3171 }31723173 scheduleAfter<T extends UniqueHelper>(3174 scheduledId: string,3175 blocksBeforeExecution: number,3176 options: ISchedulerOptions = {},3177 ) {3178 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3179 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3180 }31813182 getSudo<T extends UniqueHelper>() {3183 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3184 }3185}318631873188export class UniqueFTCollection extends UniqueBaseCollection {3189 async getBalance(addressObj: ICrossAccountId) {3190 return await this.helper.ft.getBalance(this.collectionId, addressObj);3191 }31923193 async getTotalPieces() {3194 return await this.helper.ft.getTotalPieces(this.collectionId);3195 }31963197 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3198 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3199 }32003201 async getTop10Owners() {3202 return await this.helper.ft.getTop10Owners(this.collectionId);3203 }32043205 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3206 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3207 }32083209 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3210 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3211 }32123213 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3214 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3215 }32163217 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3218 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3219 }32203221 async burnTokens(signer: TSigner, amount=1n) {3222 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3223 }32243225 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3226 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3227 }32283229 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3230 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3231 }32323233 scheduleAt<T extends UniqueHelper>(3234 scheduledId: string,3235 executionBlockNumber: number,3236 options: ISchedulerOptions = {},3237 ) {3238 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3239 return new UniqueFTCollection(this.collectionId, scheduledHelper);3240 }32413242 scheduleAfter<T extends UniqueHelper>(3243 scheduledId: string,3244 blocksBeforeExecution: number,3245 options: ISchedulerOptions = {},3246 ) {3247 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3248 return new UniqueFTCollection(this.collectionId, scheduledHelper);3249 }32503251 getSudo<T extends UniqueHelper>() {3252 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3253 }3254}325532563257export class UniqueBaseToken {3258 collection: UniqueNFTCollection | UniqueRFTCollection;3259 collectionId: number;3260 tokenId: number;32613262 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3263 this.collection = collection;3264 this.collectionId = collection.collectionId;3265 this.tokenId = tokenId;3266 }32673268 async getNextSponsored(addressObj: ICrossAccountId) {3269 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3270 }32713272 async getProperties(propertyKeys?: string[] | null) {3273 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3274 }32753276 async setProperties(signer: TSigner, properties: IProperty[]) {3277 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3278 }32793280 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3281 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3282 }32833284 async doesExist() {3285 return await this.collection.doesTokenExist(this.tokenId);3286 }32873288 nestingAccount() {3289 return this.collection.helper.util.getTokenAccount(this);3290 }32913292 scheduleAt<T extends UniqueHelper>(3293 scheduledId: string,3294 executionBlockNumber: number,3295 options: ISchedulerOptions = {},3296 ) {3297 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3298 return new UniqueBaseToken(this.tokenId, scheduledCollection);3299 }33003301 scheduleAfter<T extends UniqueHelper>(3302 scheduledId: string,3303 blocksBeforeExecution: number,3304 options: ISchedulerOptions = {},3305 ) {3306 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3307 return new UniqueBaseToken(this.tokenId, scheduledCollection);3308 }33093310 getSudo<T extends UniqueHelper>() {3311 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3312 }3313}331433153316export class UniqueNFToken extends UniqueBaseToken {3317 collection: UniqueNFTCollection;33183319 constructor(tokenId: number, collection: UniqueNFTCollection) {3320 super(tokenId, collection);3321 this.collection = collection;3322 }33233324 async getData(blockHashAt?: string) {3325 return await this.collection.getToken(this.tokenId, blockHashAt);3326 }33273328 async getOwner(blockHashAt?: string) {3329 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3330 }33313332 async getTopmostOwner(blockHashAt?: string) {3333 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3334 }33353336 async getChildren(blockHashAt?: string) {3337 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3338 }33393340 async nest(signer: TSigner, toTokenObj: IToken) {3341 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3342 }33433344 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3345 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3346 }33473348 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3349 return await this.collection.transferToken(signer, this.tokenId, addressObj);3350 }33513352 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3353 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3354 }33553356 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3357 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3358 }33593360 async isApproved(toAddressObj: ICrossAccountId) {3361 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3362 }33633364 async burn(signer: TSigner) {3365 return await this.collection.burnToken(signer, this.tokenId);3366 }33673368 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3369 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3370 }33713372 scheduleAt<T extends UniqueHelper>(3373 scheduledId: string,3374 executionBlockNumber: number,3375 options: ISchedulerOptions = {},3376 ) {3377 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3378 return new UniqueNFToken(this.tokenId, scheduledCollection);3379 }33803381 scheduleAfter<T extends UniqueHelper>(3382 scheduledId: string,3383 blocksBeforeExecution: number,3384 options: ISchedulerOptions = {},3385 ) {3386 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3387 return new UniqueNFToken(this.tokenId, scheduledCollection);3388 }33893390 getSudo<T extends UniqueHelper>() {3391 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3392 }3393}33943395export class UniqueRFToken extends UniqueBaseToken {3396 collection: UniqueRFTCollection;33973398 constructor(tokenId: number, collection: UniqueRFTCollection) {3399 super(tokenId, collection);3400 this.collection = collection;3401 }34023403 async getData(blockHashAt?: string) {3404 return await this.collection.getToken(this.tokenId, blockHashAt);3405 }34063407 async getTop10Owners() {3408 return await this.collection.getTop10TokenOwners(this.tokenId);3409 }34103411 async getBalance(addressObj: ICrossAccountId) {3412 return await this.collection.getTokenBalance(this.tokenId, addressObj);3413 }34143415 async getTotalPieces() {3416 return await this.collection.getTokenTotalPieces(this.tokenId);3417 }34183419 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3420 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3421 }34223423 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3424 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3425 }34263427 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3428 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3429 }34303431 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3432 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3433 }34343435 async repartition(signer: TSigner, amount: bigint) {3436 return await this.collection.repartitionToken(signer, this.tokenId, amount);3437 }34383439 async burn(signer: TSigner, amount=1n) {3440 return await this.collection.burnToken(signer, this.tokenId, amount);3441 }34423443 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3444 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3445 }34463447 scheduleAt<T extends UniqueHelper>(3448 scheduledId: string,3449 executionBlockNumber: number,3450 options: ISchedulerOptions = {},3451 ) {3452 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3453 return new UniqueRFToken(this.tokenId, scheduledCollection);3454 }34553456 scheduleAfter<T extends UniqueHelper>(3457 scheduledId: string,3458 blocksBeforeExecution: number,3459 options: ISchedulerOptions = {},3460 ) {3461 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3462 return new UniqueRFToken(this.tokenId, scheduledCollection);3463 }34643465 getSudo<T extends UniqueHelper>() {3466 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3467 }3468}