difftreelog
feat add sudo/scheduler support to playgrounds, several minor additions
in: master
2 files changed
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -10,6 +10,7 @@
import {EventRecord} from '@polkadot/types/interfaces';
import {ICrossAccountId} from './types';
import {FrameSystemEventRecord} from '@polkadot/types/lookup';
+import {VoidFn} from '@polkadot/api/types';
export class SilentLogger {
log(_msg: any, _level: any): void { }
@@ -154,6 +155,8 @@
class ArrangeGroup {
helper: DevUniqueHelper;
+ scheduledIdSlider = 0;
+
constructor(helper: DevUniqueHelper) {
this.helper = helper;
}
@@ -297,6 +300,39 @@
const address = stringToU8a(('modl' + palletId).padEnd(32, '\0'));
return encodeAddress(address);
}
+
+ async makeScheduledIds(num: number): Promise<string[]> {
+ await this.helper.wait.noScheduledTasks();
+
+ function makeId(slider: number) {
+ const scheduledIdSize = 32;
+ const hexId = slider.toString(16);
+ const prefixSize = scheduledIdSize - hexId.length;
+
+ const scheduledId = '0x' + '0'.repeat(prefixSize) + hexId;
+
+ return scheduledId;
+ }
+
+ const ids = [];
+ for (let i = 0; i < num; i++) {
+ ids.push(makeId(this.scheduledIdSlider));
+ this.scheduledIdSlider += 1;
+ }
+
+ return ids;
+ }
+
+ async makeScheduledId(): Promise<string> {
+ return (await this.makeScheduledIds(1))[0];
+ }
+
+ async captureEvents(eventSection: string, eventMethod: string): Promise<EventCapture> {
+ const capture = new EventCapture(this.helper, eventSection, eventMethod);
+ await capture.startCapture();
+
+ return capture;
+ }
}
class MoonbeamAccountGroup {
@@ -389,6 +425,24 @@
});
}
+ async noScheduledTasks() {
+ const api = this.helper.getApi();
+
+ // eslint-disable-next-line no-async-promise-executor
+ const promise = new Promise<void>(async resolve => {
+ const unsubscribe = await api.rpc.chain.subscribeNewHeads(async () => {
+ const areThereScheduledTasks = await api.query.scheduler.lookup.entries();
+
+ if(areThereScheduledTasks.length == 0) {
+ unsubscribe();
+ resolve();
+ }
+ });
+ });
+
+ return promise;
+ }
+
async event(maxBlocksToWait: number, eventSection: string, eventMethod: string) {
// eslint-disable-next-line no-async-promise-executor
const promise = new Promise<EventRecord | null>(async (resolve) => {
@@ -414,7 +468,6 @@
maxBlocksToWait--;
} else {
this.helper.logger.log(`Event \`${eventIdStr}\` is NOT found`);
-
unsubscribe();
resolve(null);
}
@@ -424,6 +477,45 @@
}
}
+class EventCapture {
+ helper: DevUniqueHelper;
+ eventSection: string;
+ eventMethod: string;
+ events: EventRecord[] = [];
+ unsubscribe: VoidFn | null = null;
+
+ constructor(
+ helper: DevUniqueHelper,
+ eventSection: string,
+ eventMethod: string,
+ ) {
+ this.helper = helper;
+ this.eventSection = eventSection;
+ this.eventMethod = eventMethod;
+ }
+
+ async startCapture() {
+ this.stopCapture();
+ this.unsubscribe = await this.helper.getApi().query.system.events(eventRecords => {
+ const newEvents = eventRecords.filter(r => {
+ return r.event.section == this.eventSection && r.event.method == this.eventMethod;
+ });
+
+ this.events.push(...newEvents);
+ });
+ }
+
+ stopCapture() {
+ if (this.unsubscribe !== null) {
+ this.unsubscribe();
+ }
+ }
+
+ extractCapturedEvents() {
+ return this.events;
+ }
+}
+
class AdminGroup {
helper: UniqueHelper;
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 signingInfo = await this.api!.derive.tx.signingInfo(signer.address);538539 // We need to sign the tx because540 // unsigned transactions does not have an inclusion fee541 tx.sign(signer, {542 blockHash: this.api!.genesisHash,543 genesisHash: this.api!.genesisHash,544 runtimeVersion: this.api!.runtimeVersion,545 nonce: signingInfo.nonce,546 });547548 if (len === null) {549 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;550 } else {551 return (await this.api!.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;552 }553 }554555 constructApiCall(apiCall: string, params: any[]) {556 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);557 let call = this.getApi() as any;558 for(const part of apiCall.slice(4).split('.')) {559 call = call[part];560 }561 return call(...params);562 }563564 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {565 if(this.api === null) throw Error('API not initialized');566 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);567568 const startTime = (new Date()).getTime();569 let result: ITransactionResult;570 let events: IEvent[] = [];571 try {572 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;573 events = this.eventHelper.extractEvents(result.result.events);574 }575 catch(e) {576 if(!(e as object).hasOwnProperty('status')) throw e;577 result = e as ITransactionResult;578 }579580 const endTime = (new Date()).getTime();581582 const log = {583 executedAt: endTime,584 executionTime: endTime - startTime,585 type: this.chainLogType.EXTRINSIC,586 status: result.status,587 call: extrinsic,588 signer: this.getSignerAddress(sender),589 params,590 } as IUniqueHelperLog;591592 if(result.status !== this.transactionStatus.SUCCESS) {593 if (result.moduleError) log.moduleError = result.moduleError;594 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;595 }596 if(events.length > 0) log.events = events;597598 this.chainLog.push(log);599600 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {601 if (result.moduleError) throw Error(`${result.moduleError}`);602 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));603 }604 return result;605 }606607 async callRpc(rpc: string, params?: any[]) {608 if(typeof params === 'undefined') params = [];609 if(this.api === null) throw Error('API not initialized');610 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);611612 const startTime = (new Date()).getTime();613 let result;614 let error = null;615 const log = {616 type: this.chainLogType.RPC,617 call: rpc,618 params,619 } as IUniqueHelperLog;620621 try {622 result = await this.constructApiCall(rpc, params);623 }624 catch(e) {625 error = e;626 }627628 const endTime = (new Date()).getTime();629630 log.executedAt = endTime;631 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';632 log.executionTime = endTime - startTime;633634 this.chainLog.push(log);635636 if(error !== null) throw error;637638 return result;639 }640641 getSignerAddress(signer: IKeyringPair | string): string {642 if(typeof signer === 'string') return signer;643 return signer.address;644 }645646 fetchAllPalletNames(): string[] {647 if(this.api === null) throw Error('API not initialized');648 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());649 }650651 fetchMissingPalletNames(requiredPallets: string[]): string[] {652 const palletNames = this.fetchAllPalletNames();653 return requiredPallets.filter(p => !palletNames.includes(p));654 }655}656657658class HelperGroup<T extends ChainHelperBase> {659 helper: T;660661 constructor(uniqueHelper: T) {662 this.helper = uniqueHelper;663 }664}665666667class CollectionGroup extends HelperGroup<UniqueHelper> {668 /**669 * Get number of blocks when sponsored transaction is available.670 *671 * @param collectionId ID of collection672 * @param tokenId ID of token673 * @param addressObj address for which the sponsorship is checked674 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});675 * @returns number of blocks or null if sponsorship hasn't been set676 */677 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {678 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();679 }680681 /**682 * Get the number of created collections.683 *684 * @returns number of created collections685 */686 async getTotalCount(): Promise<number> {687 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();688 }689690 /**691 * Get information about the collection with additional data,692 * including the number of tokens it contains, its administrators,693 * the normalized address of the collection's owner, and decoded name and description.694 *695 * @param collectionId ID of collection696 * @example await getData(2)697 * @returns collection information object698 */699 async getData(collectionId: number): Promise<{700 id: number;701 name: string;702 description: string;703 tokensCount: number;704 admins: CrossAccountId[];705 normalizedOwner: TSubstrateAccount;706 raw: any707 } | null> {708 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);709 const humanCollection = collection.toHuman(), collectionData = {710 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],711 raw: humanCollection,712 } as any, jsonCollection = collection.toJSON();713 if (humanCollection === null) return null;714 collectionData.raw.limits = jsonCollection.limits;715 collectionData.raw.permissions = jsonCollection.permissions;716 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);717 for (const key of ['name', 'description']) {718 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);719 }720721 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))722 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)723 : 0;724 collectionData.admins = await this.getAdmins(collectionId);725726 return collectionData;727 }728729 /**730 * Get the addresses of the collection's administrators, optionally normalized.731 *732 * @param collectionId ID of collection733 * @param normalize whether to normalize the addresses to the default ss58 format734 * @example await getAdmins(1)735 * @returns array of administrators736 */737 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {738 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();739740 return normalize741 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())742 : admins;743 }744745 /**746 * Get the addresses added to the collection allow-list, optionally normalized.747 * @param collectionId ID of collection748 * @param normalize whether to normalize the addresses to the default ss58 format749 * @example await getAllowList(1)750 * @returns array of allow-listed addresses751 */752 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {753 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();754 return normalize755 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())756 : allowListed;757 }758759 /**760 * Get the effective limits of the collection instead of null for default values761 *762 * @param collectionId ID of collection763 * @example await getEffectiveLimits(2)764 * @returns object of collection limits765 */766 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {767 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();768 }769770 /**771 * Burns the collection if the signer has sufficient permissions and collection is empty.772 *773 * @param signer keyring of signer774 * @param collectionId ID of collection775 * @example await helper.collection.burn(aliceKeyring, 3);776 * @returns ```true``` if extrinsic success, otherwise ```false```777 */778 async burn(signer: TSigner, collectionId: number): Promise<boolean> {779 const result = await this.helper.executeExtrinsic(780 signer,781 'api.tx.unique.destroyCollection', [collectionId],782 true,783 );784785 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');786 }787788 /**789 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.790 *791 * @param signer keyring of signer792 * @param collectionId ID of collection793 * @param sponsorAddress Sponsor substrate address794 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")795 * @returns ```true``` if extrinsic success, otherwise ```false```796 */797 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {798 const result = await this.helper.executeExtrinsic(799 signer,800 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],801 true,802 );803804 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');805 }806807 /**808 * Confirms consent to sponsor the collection on behalf of the signer.809 *810 * @param signer keyring of signer811 * @param collectionId ID of collection812 * @example confirmSponsorship(aliceKeyring, 10)813 * @returns ```true``` if extrinsic success, otherwise ```false```814 */815 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {816 const result = await this.helper.executeExtrinsic(817 signer,818 'api.tx.unique.confirmSponsorship', [collectionId],819 true,820 );821822 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');823 }824825 /**826 * Removes the sponsor of a collection, regardless if it consented or not.827 *828 * @param signer keyring of signer829 * @param collectionId ID of collection830 * @example removeSponsor(aliceKeyring, 10)831 * @returns ```true``` if extrinsic success, otherwise ```false```832 */833 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {834 const result = await this.helper.executeExtrinsic(835 signer,836 'api.tx.unique.removeCollectionSponsor', [collectionId],837 true,838 );839840 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');841 }842843 /**844 * Sets the limits of the collection. At least one limit must be specified for a correct call.845 *846 * @param signer keyring of signer847 * @param collectionId ID of collection848 * @param limits collection limits object849 * @example850 * await setLimits(851 * aliceKeyring,852 * 10,853 * {854 * sponsorTransferTimeout: 0,855 * ownerCanDestroy: false856 * }857 * )858 * @returns ```true``` if extrinsic success, otherwise ```false```859 */860 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {861 const result = await this.helper.executeExtrinsic(862 signer,863 'api.tx.unique.setCollectionLimits', [collectionId, limits],864 true,865 );866867 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');868 }869870 /**871 * Changes the owner of the collection to the new Substrate address.872 *873 * @param signer keyring of signer874 * @param collectionId ID of collection875 * @param ownerAddress substrate address of new owner876 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")877 * @returns ```true``` if extrinsic success, otherwise ```false```878 */879 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {880 const result = await this.helper.executeExtrinsic(881 signer,882 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],883 true,884 );885886 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');887 }888889 /**890 * Adds a collection administrator.891 *892 * @param signer keyring of signer893 * @param collectionId ID of collection894 * @param adminAddressObj Administrator address (substrate or ethereum)895 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})896 * @returns ```true``` if extrinsic success, otherwise ```false```897 */898 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {899 const result = await this.helper.executeExtrinsic(900 signer,901 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],902 true,903 );904905 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');906 }907908 /**909 * Removes a collection administrator.910 *911 * @param signer keyring of signer912 * @param collectionId ID of collection913 * @param adminAddressObj Administrator address (substrate or ethereum)914 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})915 * @returns ```true``` if extrinsic success, otherwise ```false```916 */917 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {918 const result = await this.helper.executeExtrinsic(919 signer,920 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],921 true,922 );923924 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');925 }926927 /**928 * Check if user is in allow list.929 * 930 * @param collectionId ID of collection931 * @param user Account to check932 * @example await getAdmins(1)933 * @returns is user in allow list934 */935 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {936 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();937 }938939 /**940 * Adds an address to allow list941 * @param signer keyring of signer942 * @param collectionId ID of collection943 * @param addressObj address to add to the allow list944 * @returns ```true``` if extrinsic success, otherwise ```false```945 */946 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {947 const result = await this.helper.executeExtrinsic(948 signer,949 'api.tx.unique.addToAllowList', [collectionId, addressObj],950 true,951 );952953 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');954 }955956 /**957 * Removes an address from allow list958 *959 * @param signer keyring of signer960 * @param collectionId ID of collection961 * @param addressObj address to remove from the allow list962 * @returns ```true``` if extrinsic success, otherwise ```false```963 */964 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {965 const result = await this.helper.executeExtrinsic(966 signer,967 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],968 true,969 );970971 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');972 }973974 /**975 * Sets onchain permissions for selected collection.976 *977 * @param signer keyring of signer978 * @param collectionId ID of collection979 * @param permissions collection permissions object980 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});981 * @returns ```true``` if extrinsic success, otherwise ```false```982 */983 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {984 const result = await this.helper.executeExtrinsic(985 signer,986 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],987 true,988 );989990 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');991 }992993 /**994 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.995 *996 * @param signer keyring of signer997 * @param collectionId ID of collection998 * @param permissions nesting permissions object999 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1000 * @returns ```true``` if extrinsic success, otherwise ```false```1001 */1002 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1003 return await this.setPermissions(signer, collectionId, {nesting: permissions});1004 }10051006 /**1007 * Disables nesting for selected collection.1008 *1009 * @param signer keyring of signer1010 * @param collectionId ID of collection1011 * @example disableNesting(aliceKeyring, 10);1012 * @returns ```true``` if extrinsic success, otherwise ```false```1013 */1014 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1015 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1016 }10171018 /**1019 * Sets onchain properties to the collection.1020 *1021 * @param signer keyring of signer1022 * @param collectionId ID of collection1023 * @param properties array of property objects1024 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1025 * @returns ```true``` if extrinsic success, otherwise ```false```1026 */1027 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1028 const result = await this.helper.executeExtrinsic(1029 signer,1030 'api.tx.unique.setCollectionProperties', [collectionId, properties],1031 true,1032 );10331034 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1035 }10361037 /**1038 * Get collection properties.1039 * 1040 * @param collectionId ID of collection1041 * @param propertyKeys optionally filter the returned properties to only these keys1042 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1043 * @returns array of key-value pairs1044 */1045 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1046 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1047 }10481049 async getCollectionOptions(collectionId: number) {1050 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1051 }10521053 /**1054 * Deletes onchain properties from the collection.1055 *1056 * @param signer keyring of signer1057 * @param collectionId ID of collection1058 * @param propertyKeys array of property keys to delete1059 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1060 * @returns ```true``` if extrinsic success, otherwise ```false```1061 */1062 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1063 const result = await this.helper.executeExtrinsic(1064 signer,1065 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1066 true,1067 );10681069 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1070 }10711072 /**1073 * Changes the owner of the token.1074 *1075 * @param signer keyring of signer1076 * @param collectionId ID of collection1077 * @param tokenId ID of token1078 * @param addressObj address of a new owner1079 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1080 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1081 * @returns true if the token success, otherwise false1082 */1083 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1084 const result = await this.helper.executeExtrinsic(1085 signer,1086 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1087 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1088 );10891090 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1091 }10921093 /**1094 *1095 * Change ownership of a token(s) on behalf of the owner.1096 *1097 * @param signer keyring of signer1098 * @param collectionId ID of collection1099 * @param tokenId ID of token1100 * @param fromAddressObj address on behalf of which the token will be sent1101 * @param toAddressObj new token owner1102 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1103 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1104 * @returns true if the token success, otherwise false1105 */1106 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1107 const result = await this.helper.executeExtrinsic(1108 signer,1109 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1110 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1111 );1112 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1113 }11141115 /**1116 *1117 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1118 *1119 * @param signer keyring of signer1120 * @param collectionId ID of collection1121 * @param tokenId ID of token1122 * @param amount amount of tokens to be burned. For NFT must be set to 1n1123 * @example burnToken(aliceKeyring, 10, 5);1124 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1125 */1126 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1127 const burnResult = await this.helper.executeExtrinsic(1128 signer,1129 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1130 true, // `Unable to burn token for ${label}`,1131 );1132 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1133 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1134 return burnedTokens.success;1135 }11361137 /**1138 * Destroys a concrete instance of NFT on behalf of the owner1139 *1140 * @param signer keyring of signer1141 * @param collectionId ID of collection1142 * @param tokenId ID of token1143 * @param fromAddressObj address on behalf of which the token will be burnt1144 * @param amount amount of tokens to be burned. For NFT must be set to 1n1145 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1146 * @returns ```true``` if extrinsic success, otherwise ```false```1147 */1148 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1149 const burnResult = await this.helper.executeExtrinsic(1150 signer,1151 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1152 true, // `Unable to burn token from for ${label}`,1153 );1154 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1155 return burnedTokens.success && burnedTokens.tokens.length > 0;1156 }11571158 /**1159 * Set, change, or remove approved address to transfer the ownership of the NFT.1160 *1161 * @param signer keyring of signer1162 * @param collectionId ID of collection1163 * @param tokenId ID of token1164 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1165 * @param amount amount of token to be approved. For NFT must be set to 1n1166 * @returns ```true``` if extrinsic success, otherwise ```false```1167 */1168 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1169 const approveResult = await this.helper.executeExtrinsic(1170 signer,1171 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1172 true, // `Unable to approve token for ${label}`,1173 );11741175 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1176 }11771178 /**1179 * Get the amount of token pieces approved to transfer or burn. Normally 0.1180 *1181 * @param collectionId ID of collection1182 * @param tokenId ID of token1183 * @param toAccountObj address which is approved to use token pieces1184 * @param fromAccountObj address which may have allowed the use of its owned tokens1185 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1186 * @returns number of approved to transfer pieces1187 */1188 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1189 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1190 }11911192 /**1193 * Get the last created token ID in a collection1194 *1195 * @param collectionId ID of collection1196 * @example getLastTokenId(10);1197 * @returns id of the last created token1198 */1199 async getLastTokenId(collectionId: number): Promise<number> {1200 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1201 }12021203 /**1204 * Check if token exists1205 *1206 * @param collectionId ID of collection1207 * @param tokenId ID of token1208 * @example doesTokenExist(10, 20);1209 * @returns true if the token exists, otherwise false1210 */1211 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1212 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1213 }1214}12151216class NFTnRFT extends CollectionGroup {1217 /**1218 * Get tokens owned by account1219 *1220 * @param collectionId ID of collection1221 * @param addressObj tokens owner1222 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1223 * @returns array of token ids owned by account1224 */1225 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1226 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1227 }12281229 /**1230 * Get token data1231 *1232 * @param collectionId ID of collection1233 * @param tokenId ID of token1234 * @param propertyKeys optionally filter the token properties to only these keys1235 * @param blockHashAt optionally query the data at some block with this hash1236 * @example getToken(10, 5);1237 * @returns human readable token data1238 */1239 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1240 properties: IProperty[];1241 owner: CrossAccountId;1242 normalizedOwner: CrossAccountId;1243 }| null> {1244 let tokenData;1245 if(typeof blockHashAt === 'undefined') {1246 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1247 }1248 else {1249 if(propertyKeys.length == 0) {1250 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1251 if(!collection) return null;1252 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1253 }1254 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1255 }1256 tokenData = tokenData.toHuman();1257 if (tokenData === null || tokenData.owner === null) return null;1258 const owner = {} as any;1259 for (const key of Object.keys(tokenData.owner)) {1260 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1261 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1262 : tokenData.owner[key];1263 }1264 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1265 return tokenData;1266 }12671268 /**1269 * Set permissions to change token properties1270 *1271 * @param signer keyring of signer1272 * @param collectionId ID of collection1273 * @param permissions permissions to change a property by the collection admin or token owner1274 * @example setTokenPropertyPermissions(1275 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1276 * )1277 * @returns true if extrinsic success otherwise false1278 */1279 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1280 const result = await this.helper.executeExtrinsic(1281 signer,1282 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1283 true,1284 );12851286 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1287 }12881289 /**1290 * Get token property permissions.1291 * 1292 * @param collectionId ID of collection1293 * @param propertyKeys optionally filter the returned property permissions to only these keys1294 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1295 * @returns array of key-permission pairs1296 */1297 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1298 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1299 }13001301 /**1302 * Set token properties1303 *1304 * @param signer keyring of signer1305 * @param collectionId ID of collection1306 * @param tokenId ID of token1307 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1308 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1309 * @returns ```true``` if extrinsic success, otherwise ```false```1310 */1311 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1312 const result = await this.helper.executeExtrinsic(1313 signer,1314 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1315 true,1316 );13171318 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1319 }13201321 /**1322 * Get properties, metadata assigned to a token.1323 * 1324 * @param collectionId ID of collection1325 * @param tokenId ID of token1326 * @param propertyKeys optionally filter the returned properties to only these keys1327 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1328 * @returns array of key-value pairs1329 */1330 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1331 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1332 }13331334 /**1335 * Delete the provided properties of a token1336 * @param signer keyring of signer1337 * @param collectionId ID of collection1338 * @param tokenId ID of token1339 * @param propertyKeys property keys to be deleted1340 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1341 * @returns ```true``` if extrinsic success, otherwise ```false```1342 */1343 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1344 const result = await this.helper.executeExtrinsic(1345 signer,1346 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1347 true,1348 );13491350 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1351 }13521353 /**1354 * Mint new collection1355 *1356 * @param signer keyring of signer1357 * @param collectionOptions basic collection options and properties1358 * @param mode NFT or RFT type of a collection1359 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1360 * @returns object of the created collection1361 */1362 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1363 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1364 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1365 for (const key of ['name', 'description', 'tokenPrefix']) {1366 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);1367 }1368 const creationResult = await this.helper.executeExtrinsic(1369 signer,1370 'api.tx.unique.createCollectionEx', [collectionOptions],1371 true, // errorLabel,1372 );1373 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1374 }13751376 getCollectionObject(_collectionId: number): any {1377 return null;1378 }13791380 getTokenObject(_collectionId: number, _tokenId: number): any {1381 return null;1382 }1383}138413851386class NFTGroup extends NFTnRFT {1387 /**1388 * Get collection object1389 * @param collectionId ID of collection1390 * @example getCollectionObject(2);1391 * @returns instance of UniqueNFTCollection1392 */1393 getCollectionObject(collectionId: number): UniqueNFTCollection {1394 return new UniqueNFTCollection(collectionId, this.helper);1395 }13961397 /**1398 * Get token object1399 * @param collectionId ID of collection1400 * @param tokenId ID of token1401 * @example getTokenObject(10, 5);1402 * @returns instance of UniqueNFTToken1403 */1404 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1405 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1406 }14071408 /**1409 * Get token's owner1410 * @param collectionId ID of collection1411 * @param tokenId ID of token1412 * @param blockHashAt optionally query the data at the block with this hash1413 * @example getTokenOwner(10, 5);1414 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1415 */1416 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1417 let owner;1418 if (typeof blockHashAt === 'undefined') {1419 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1420 } else {1421 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1422 }1423 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1424 }14251426 /**1427 * Is token approved to transfer1428 * @param collectionId ID of collection1429 * @param tokenId ID of token1430 * @param toAccountObj address to be approved1431 * @returns ```true``` if extrinsic success, otherwise ```false```1432 */1433 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1434 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1435 }14361437 /**1438 * Changes the owner of the token.1439 *1440 * @param signer keyring of signer1441 * @param collectionId ID of collection1442 * @param tokenId ID of token1443 * @param addressObj address of a new owner1444 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1445 * @returns ```true``` if extrinsic success, otherwise ```false```1446 */1447 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1448 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1449 }14501451 /**1452 *1453 * Change ownership of a NFT on behalf of the owner.1454 *1455 * @param signer keyring of signer1456 * @param collectionId ID of collection1457 * @param tokenId ID of token1458 * @param fromAddressObj address on behalf of which the token will be sent1459 * @param toAddressObj new token owner1460 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1461 * @returns ```true``` if extrinsic success, otherwise ```false```1462 */1463 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1464 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1465 }14661467 /**1468 * Recursively find the address that owns the token1469 * @param collectionId ID of collection1470 * @param tokenId ID of token1471 * @param blockHashAt1472 * @example getTokenTopmostOwner(10, 5);1473 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1474 */1475 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1476 let owner;1477 if (typeof blockHashAt === 'undefined') {1478 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1479 } else {1480 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1481 }14821483 if (owner === null) return null;14841485 return owner.toHuman();1486 }14871488 /**1489 * Get tokens nested in the provided token1490 * @param collectionId ID of collection1491 * @param tokenId ID of token1492 * @param blockHashAt optionally query the data at the block with this hash1493 * @example getTokenChildren(10, 5);1494 * @returns tokens whose depth of nesting is <= 51495 */1496 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1497 let children;1498 if(typeof blockHashAt === 'undefined') {1499 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1500 } else {1501 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1502 }15031504 return children.toJSON().map((x: any) => {1505 return {collectionId: x.collection, tokenId: x.token};1506 });1507 }15081509 /**1510 * Nest one token into another1511 * @param signer keyring of signer1512 * @param tokenObj token to be nested1513 * @param rootTokenObj token to be parent1514 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1515 * @returns ```true``` if extrinsic success, otherwise ```false```1516 */1517 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1518 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1519 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1520 if(!result) {1521 throw Error('Unable to nest token!');1522 }1523 return result;1524 }15251526 /**1527 * Remove token from nested state1528 * @param signer keyring of signer1529 * @param tokenObj token to unnest1530 * @param rootTokenObj parent of a token1531 * @param toAddressObj address of a new token owner1532 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1533 * @returns ```true``` if extrinsic success, otherwise ```false```1534 */1535 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1536 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1537 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1538 if(!result) {1539 throw Error('Unable to unnest token!');1540 }1541 return result;1542 }15431544 /**1545 * Mint new collection1546 * @param signer keyring of signer1547 * @param collectionOptions Collection options1548 * @example1549 * mintCollection(aliceKeyring, {1550 * name: 'New',1551 * description: 'New collection',1552 * tokenPrefix: 'NEW',1553 * })1554 * @returns object of the created collection1555 */1556 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1557 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1558 }15591560 /**1561 * Mint new token1562 * @param signer keyring of signer1563 * @param data token data1564 * @returns created token object1565 */1566 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1567 const creationResult = await this.helper.executeExtrinsic(1568 signer,1569 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1570 nft: {1571 properties: data.properties,1572 },1573 }],1574 true,1575 );1576 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1577 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1578 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1579 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1580 }15811582 /**1583 * Mint multiple NFT tokens1584 * @param signer keyring of signer1585 * @param collectionId ID of collection1586 * @param tokens array of tokens with owner and properties1587 * @example1588 * mintMultipleTokens(aliceKeyring, 10, [{1589 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1590 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1591 * },{1592 * owner: {Ethereum: "0x9F0583DbB855d..."},1593 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1594 * }]);1595 * @returns ```true``` if extrinsic success, otherwise ```false```1596 */1597 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1598 const creationResult = await this.helper.executeExtrinsic(1599 signer,1600 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1601 true,1602 );1603 const collection = this.getCollectionObject(collectionId);1604 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1605 }16061607 /**1608 * Mint multiple NFT tokens with one owner1609 * @param signer keyring of signer1610 * @param collectionId ID of collection1611 * @param owner tokens owner1612 * @param tokens array of tokens with owner and properties1613 * @example1614 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1615 * properties: [{1616 * key: "gender",1617 * value: "female",1618 * },{1619 * key: "age",1620 * value: "33",1621 * }],1622 * }]);1623 * @returns array of newly created tokens1624 */1625 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1626 const rawTokens = [];1627 for (const token of tokens) {1628 const raw = {NFT: {properties: token.properties}};1629 rawTokens.push(raw);1630 }1631 const creationResult = await this.helper.executeExtrinsic(1632 signer,1633 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1634 true,1635 );1636 const collection = this.getCollectionObject(collectionId);1637 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1638 }16391640 /**1641 * Set, change, or remove approved address to transfer the ownership of the NFT.1642 *1643 * @param signer keyring of signer1644 * @param collectionId ID of collection1645 * @param tokenId ID of token1646 * @param toAddressObj address to approve1647 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1648 * @returns ```true``` if extrinsic success, otherwise ```false```1649 */1650 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1651 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1652 }1653}165416551656class RFTGroup extends NFTnRFT {1657 /**1658 * Get collection object1659 * @param collectionId ID of collection1660 * @example getCollectionObject(2);1661 * @returns instance of UniqueRFTCollection1662 */1663 getCollectionObject(collectionId: number): UniqueRFTCollection {1664 return new UniqueRFTCollection(collectionId, this.helper);1665 }16661667 /**1668 * Get token object1669 * @param collectionId ID of collection1670 * @param tokenId ID of token1671 * @example getTokenObject(10, 5);1672 * @returns instance of UniqueNFTToken1673 */1674 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1675 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1676 }16771678 /**1679 * Get top 10 token owners with the largest number of pieces1680 * @param collectionId ID of collection1681 * @param tokenId ID of token1682 * @example getTokenTop10Owners(10, 5);1683 * @returns array of top 10 owners1684 */1685 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1686 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1687 }16881689 /**1690 * Get number of pieces owned by address1691 * @param collectionId ID of collection1692 * @param tokenId ID of token1693 * @param addressObj address token owner1694 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1695 * @returns number of pieces ownerd by address1696 */1697 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1698 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1699 }17001701 /**1702 * Transfer pieces of token to another address1703 * @param signer keyring of signer1704 * @param collectionId ID of collection1705 * @param tokenId ID of token1706 * @param addressObj address of a new owner1707 * @param amount number of pieces to be transfered1708 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1709 * @returns ```true``` if extrinsic success, otherwise ```false```1710 */1711 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1712 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1713 }17141715 /**1716 * Change ownership of some pieces of RFT on behalf of the owner.1717 * @param signer keyring of signer1718 * @param collectionId ID of collection1719 * @param tokenId ID of token1720 * @param fromAddressObj address on behalf of which the token will be sent1721 * @param toAddressObj new token owner1722 * @param amount number of pieces to be transfered1723 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1724 * @returns ```true``` if extrinsic success, otherwise ```false```1725 */1726 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1727 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1728 }17291730 /**1731 * Mint new collection1732 * @param signer keyring of signer1733 * @param collectionOptions Collection options1734 * @example1735 * mintCollection(aliceKeyring, {1736 * name: 'New',1737 * description: 'New collection',1738 * tokenPrefix: 'NEW',1739 * })1740 * @returns object of the created collection1741 */1742 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1743 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1744 }17451746 /**1747 * Mint new token1748 * @param signer keyring of signer1749 * @param data token data1750 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1751 * @returns created token object1752 */1753 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1754 const creationResult = await this.helper.executeExtrinsic(1755 signer,1756 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1757 refungible: {1758 pieces: data.pieces,1759 properties: data.properties,1760 },1761 }],1762 true,1763 );1764 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1765 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1766 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1767 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1768 }17691770 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1771 throw Error('Not implemented');1772 const creationResult = await this.helper.executeExtrinsic(1773 signer,1774 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1775 true, // `Unable to mint RFT tokens for ${label}`,1776 );1777 const collection = this.getCollectionObject(collectionId);1778 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1779 }17801781 /**1782 * Mint multiple RFT tokens with one owner1783 * @param signer keyring of signer1784 * @param collectionId ID of collection1785 * @param owner tokens owner1786 * @param tokens array of tokens with properties and pieces1787 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1788 * @returns array of newly created RFT tokens1789 */1790 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1791 const rawTokens = [];1792 for (const token of tokens) {1793 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1794 rawTokens.push(raw);1795 }1796 const creationResult = await this.helper.executeExtrinsic(1797 signer,1798 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1799 true,1800 );1801 const collection = this.getCollectionObject(collectionId);1802 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1803 }18041805 /**1806 * Destroys a concrete instance of RFT.1807 * @param signer keyring of signer1808 * @param collectionId ID of collection1809 * @param tokenId ID of token1810 * @param amount number of pieces to be burnt1811 * @example burnToken(aliceKeyring, 10, 5);1812 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1813 */1814 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1815 return await super.burnToken(signer, collectionId, tokenId, amount);1816 }18171818 /**1819 * Destroys a concrete instance of RFT on behalf of the owner.1820 * @param signer keyring of signer1821 * @param collectionId ID of collection1822 * @param tokenId ID of token1823 * @param fromAddressObj address on behalf of which the token will be burnt1824 * @param amount number of pieces to be burnt1825 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1826 * @returns ```true``` if extrinsic success, otherwise ```false```1827 */1828 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1829 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1830 }18311832 /**1833 * Set, change, or remove approved address to transfer the ownership of the RFT.1834 *1835 * @param signer keyring of signer1836 * @param collectionId ID of collection1837 * @param tokenId ID of token1838 * @param toAddressObj address to approve1839 * @param amount number of pieces to be approved1840 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1841 * @returns true if the token success, otherwise false1842 */1843 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1844 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1845 }18461847 /**1848 * Get total number of pieces1849 * @param collectionId ID of collection1850 * @param tokenId ID of token1851 * @example getTokenTotalPieces(10, 5);1852 * @returns number of pieces1853 */1854 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1855 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1856 }18571858 /**1859 * Change number of token pieces. Signer must be the owner of all token pieces.1860 * @param signer keyring of signer1861 * @param collectionId ID of collection1862 * @param tokenId ID of token1863 * @param amount new number of pieces1864 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1865 * @returns true if the repartion was success, otherwise false1866 */1867 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1868 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1869 const repartitionResult = await this.helper.executeExtrinsic(1870 signer,1871 'api.tx.unique.repartition', [collectionId, tokenId, amount],1872 true,1873 );1874 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1875 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1876 }1877}187818791880class FTGroup extends CollectionGroup {1881 /**1882 * Get collection object1883 * @param collectionId ID of collection1884 * @example getCollectionObject(2);1885 * @returns instance of UniqueFTCollection1886 */1887 getCollectionObject(collectionId: number): UniqueFTCollection {1888 return new UniqueFTCollection(collectionId, this.helper);1889 }18901891 /**1892 * Mint new fungible collection1893 * @param signer keyring of signer1894 * @param collectionOptions Collection options1895 * @param decimalPoints number of token decimals1896 * @example1897 * mintCollection(aliceKeyring, {1898 * name: 'New',1899 * description: 'New collection',1900 * tokenPrefix: 'NEW',1901 * }, 18)1902 * @returns newly created fungible collection1903 */1904 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1905 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1906 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1907 collectionOptions.mode = {fungible: decimalPoints};1908 for (const key of ['name', 'description', 'tokenPrefix']) {1909 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);1910 }1911 const creationResult = await this.helper.executeExtrinsic(1912 signer,1913 'api.tx.unique.createCollectionEx', [collectionOptions],1914 true,1915 );1916 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1917 }19181919 /**1920 * Mint tokens1921 * @param signer keyring of signer1922 * @param collectionId ID of collection1923 * @param owner address owner of new tokens1924 * @param amount amount of tokens to be meanted1925 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1926 * @returns ```true``` if extrinsic success, otherwise ```false```1927 */1928 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1929 const creationResult = await this.helper.executeExtrinsic(1930 signer,1931 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1932 fungible: {1933 value: amount,1934 },1935 }],1936 true, // `Unable to mint fungible tokens for ${label}`,1937 );1938 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1939 }19401941 /**1942 * Mint multiple Fungible tokens with one owner1943 * @param signer keyring of signer1944 * @param collectionId ID of collection1945 * @param owner tokens owner1946 * @param tokens array of tokens with properties and pieces1947 * @returns ```true``` if extrinsic success, otherwise ```false```1948 */1949 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1950 const rawTokens = [];1951 for (const token of tokens) {1952 const raw = {Fungible: {Value: token.value}};1953 rawTokens.push(raw);1954 }1955 const creationResult = await this.helper.executeExtrinsic(1956 signer,1957 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1958 true,1959 );1960 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1961 }19621963 /**1964 * Get the top 10 owners with the largest balance for the Fungible collection1965 * @param collectionId ID of collection1966 * @example getTop10Owners(10);1967 * @returns array of ```ICrossAccountId```1968 */1969 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1970 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1971 }19721973 /**1974 * Get account balance1975 * @param collectionId ID of collection1976 * @param addressObj address of owner1977 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1978 * @returns amount of fungible tokens owned by address1979 */1980 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1981 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1982 }19831984 /**1985 * Transfer tokens to address1986 * @param signer keyring of signer1987 * @param collectionId ID of collection1988 * @param toAddressObj address recipient1989 * @param amount amount of tokens to be sent1990 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1991 * @returns ```true``` if extrinsic success, otherwise ```false```1992 */1993 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1994 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1995 }19961997 /**1998 * Transfer some tokens on behalf of the owner.1999 * @param signer keyring of signer2000 * @param collectionId ID of collection2001 * @param fromAddressObj address on behalf of which tokens will be sent2002 * @param toAddressObj address where token to be sent2003 * @param amount number of tokens to be sent2004 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2005 * @returns ```true``` if extrinsic success, otherwise ```false```2006 */2007 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2008 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2009 }20102011 /**2012 * Destroy some amount of tokens2013 * @param signer keyring of signer2014 * @param collectionId ID of collection2015 * @param amount amount of tokens to be destroyed2016 * @example burnTokens(aliceKeyring, 10, 1000n);2017 * @returns ```true``` if extrinsic success, otherwise ```false```2018 */2019 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2020 return await super.burnToken(signer, collectionId, 0, amount);2021 }20222023 /**2024 * Burn some tokens on behalf of the owner.2025 * @param signer keyring of signer2026 * @param collectionId ID of collection2027 * @param fromAddressObj address on behalf of which tokens will be burnt2028 * @param amount amount of tokens to be burnt2029 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2030 * @returns ```true``` if extrinsic success, otherwise ```false```2031 */2032 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2033 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2034 }20352036 /**2037 * Get total collection supply2038 * @param collectionId2039 * @returns2040 */2041 async getTotalPieces(collectionId: number): Promise<bigint> {2042 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2043 }20442045 /**2046 * Set, change, or remove approved address to transfer tokens.2047 *2048 * @param signer keyring of signer2049 * @param collectionId ID of collection2050 * @param toAddressObj address to be approved2051 * @param amount amount of tokens to be approved2052 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2053 * @returns ```true``` if extrinsic success, otherwise ```false```2054 */2055 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2056 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2057 }20582059 /**2060 * Get amount of fungible tokens approved to transfer2061 * @param collectionId ID of collection2062 * @param fromAddressObj owner of tokens2063 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2064 * @returns number of tokens approved for the transfer2065 */2066 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2067 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2068 }2069}207020712072class ChainGroup extends HelperGroup<ChainHelperBase> {2073 /**2074 * Get system properties of a chain2075 * @example getChainProperties();2076 * @returns ss58Format, token decimals, and token symbol2077 */2078 getChainProperties(): IChainProperties {2079 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2080 return {2081 ss58Format: properties.ss58Format.toJSON(),2082 tokenDecimals: properties.tokenDecimals.toJSON(),2083 tokenSymbol: properties.tokenSymbol.toJSON(),2084 };2085 }20862087 /**2088 * Get chain header2089 * @example getLatestBlockNumber();2090 * @returns the number of the last block2091 */2092 async getLatestBlockNumber(): Promise<number> {2093 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2094 }20952096 /**2097 * Get block hash by block number2098 * @param blockNumber number of block2099 * @example getBlockHashByNumber(12345);2100 * @returns hash of a block2101 */2102 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2103 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2104 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2105 return blockHash;2106 }21072108 // TODO add docs2109 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2110 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2111 if (!blockHash) return null;2112 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2113 }21142115 /**2116 * Get account nonce2117 * @param address substrate address2118 * @example getNonce("5GrwvaEF5zXb26Fz...");2119 * @returns number, account's nonce2120 */2121 async getNonce(address: TSubstrateAccount): Promise<number> {2122 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2123 }2124}21252126class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2127 /**2128 * Get substrate address balance2129 * @param address substrate address2130 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2131 * @returns amount of tokens on address2132 */2133 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2134 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2135 }21362137 /**2138 * Transfer tokens to substrate address2139 * @param signer keyring of signer2140 * @param address substrate address of a recipient2141 * @param amount amount of tokens to be transfered2142 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2143 * @returns ```true``` if extrinsic success, otherwise ```false```2144 */2145 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2146 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}`*/);21472148 let transfer = {from: null, to: null, amount: 0n} as any;2149 result.result.events.forEach(({event: {data, method, section}}) => {2150 if ((section === 'balances') && (method === 'Transfer')) {2151 transfer = {2152 from: this.helper.address.normalizeSubstrate(data[0]),2153 to: this.helper.address.normalizeSubstrate(data[1]),2154 amount: BigInt(data[2]),2155 };2156 }2157 });2158 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2159 && this.helper.address.normalizeSubstrate(address) === transfer.to 2160 && BigInt(amount) === transfer.amount;2161 return isSuccess;2162 }21632164 /**2165 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2166 * @param address substrate address2167 * @returns2168 */2169 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2170 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2171 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2172 }2173}21742175class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2176 /**2177 * Get ethereum address balance2178 * @param address ethereum address2179 * @example getEthereum("0x9F0583DbB855d...")2180 * @returns amount of tokens on address2181 */2182 async getEthereum(address: TEthereumAccount): Promise<bigint> {2183 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2184 }21852186 /**2187 * Transfer tokens to address2188 * @param signer keyring of signer2189 * @param address Ethereum address of a recipient2190 * @param amount amount of tokens to be transfered2191 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2192 * @returns ```true``` if extrinsic success, otherwise ```false```2193 */2194 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2195 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);21962197 let transfer = {from: null, to: null, amount: 0n} as any;2198 result.result.events.forEach(({event: {data, method, section}}) => {2199 if ((section === 'balances') && (method === 'Transfer')) {2200 transfer = {2201 from: data[0].toString(),2202 to: data[1].toString(),2203 amount: BigInt(data[2]),2204 };2205 }2206 });2207 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from 2208 && address === transfer.to 2209 && BigInt(amount) === transfer.amount;2210 return isSuccess;2211 }2212}22132214class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2215 subBalanceGroup: SubstrateBalanceGroup<T>;2216 ethBalanceGroup: EthereumBalanceGroup<T>;22172218 constructor(helper: T) {2219 super(helper);2220 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2221 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2222 }22232224 getCollectionCreationPrice(): bigint {2225 return 2n * this.getOneTokenNominal();2226 }2227 /**2228 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2229 * @example getOneTokenNominal()2230 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2231 */2232 getOneTokenNominal(): bigint {2233 const chainProperties = this.helper.chain.getChainProperties();2234 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2235 }22362237 /**2238 * Get substrate address balance2239 * @param address substrate address2240 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2241 * @returns amount of tokens on address2242 */2243 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2244 return this.subBalanceGroup.getSubstrate(address);2245 }22462247 /**2248 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2249 * @param address substrate address2250 * @returns2251 */2252 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2253 return this.subBalanceGroup.getSubstrateFull(address);2254 }22552256 /**2257 * Get ethereum address balance2258 * @param address ethereum address2259 * @example getEthereum("0x9F0583DbB855d...")2260 * @returns amount of tokens on address2261 */2262 async getEthereum(address: TEthereumAccount): Promise<bigint> {2263 return this.ethBalanceGroup.getEthereum(address);2264 }22652266 /**2267 * Transfer tokens to substrate address2268 * @param signer keyring of signer2269 * @param address substrate address of a recipient2270 * @param amount amount of tokens to be transfered2271 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2272 * @returns ```true``` if extrinsic success, otherwise ```false```2273 */2274 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2275 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2276 }2277}22782279class AddressGroup extends HelperGroup<ChainHelperBase> {2280 /**2281 * Normalizes the address to the specified ss58 format, by default ```42```.2282 * @param address substrate address2283 * @param ss58Format format for address conversion, by default ```42```2284 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2285 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2286 */2287 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2288 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2289 }22902291 /**2292 * Get address in the connected chain format2293 * @param address substrate address2294 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2295 * @returns address in chain format2296 */2297 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2298 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2299 }23002301 /**2302 * Get substrate mirror of an ethereum address2303 * @param ethAddress ethereum address2304 * @param toChainFormat false for normalized account2305 * @example ethToSubstrate('0x9F0583DbB855d...')2306 * @returns substrate mirror of a provided ethereum address2307 */2308 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2309 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2310 }23112312 /**2313 * Get ethereum mirror of a substrate address2314 * @param subAddress substrate account2315 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2316 * @returns ethereum mirror of a provided substrate address2317 */2318 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2319 return CrossAccountId.translateSubToEth(subAddress);2320 }23212322 paraSiblingSovereignAccount(paraid: number) {2323 // We are getting a *sibling* parachain sovereign account,2324 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2325 const siblingPrefix = '0x7369626c';23262327 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2328 const suffix = '000000000000000000000000000000000000000000000000';23292330 return siblingPrefix + encodedParaId + suffix;2331 }2332}23332334class StakingGroup extends HelperGroup<UniqueHelper> {2335 /**2336 * Stake tokens for App Promotion2337 * @param signer keyring of signer2338 * @param amountToStake amount of tokens to stake2339 * @param label extra label for log2340 * @returns2341 */2342 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2343 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2344 const _stakeResult = await this.helper.executeExtrinsic(2345 signer, 'api.tx.appPromotion.stake',2346 [amountToStake], true,2347 );2348 // TODO extract info from stakeResult2349 return true;2350 }23512352 /**2353 * Unstake tokens for App Promotion2354 * @param signer keyring of signer2355 * @param amountToUnstake amount of tokens to unstake2356 * @param label extra label for log2357 * @returns block number where balances will be unlocked2358 */2359 async unstake(signer: TSigner, label?: string): Promise<number> {2360 if(typeof label === 'undefined') label = `${signer.address}`;2361 const _unstakeResult = await this.helper.executeExtrinsic(2362 signer, 'api.tx.appPromotion.unstake',2363 [], true,2364 );2365 // TODO extract block number fron events2366 return 1;2367 }23682369 /**2370 * Get total staked amount for address2371 * @param address substrate or ethereum address2372 * @returns total staked amount2373 */2374 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2375 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2376 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2377 }23782379 /**2380 * Get total staked per block2381 * @param address substrate or ethereum address2382 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2383 */2384 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2385 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2386 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2387 return { 2388 block: block.toBigInt(),2389 amount: amount.toBigInt(),2390 };2391 });2392 }23932394 /**2395 * Get total pending unstake amount for address2396 * @param address substrate or ethereum address2397 * @returns total pending unstake amount2398 */2399 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2400 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2401 }24022403 /**2404 * Get pending unstake amount per block for address2405 * @param address substrate or ethereum address2406 * @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 block2407 */2408 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2409 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2410 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2411 return {2412 block: block.toBigInt(),2413 amount: amount.toBigInt(),2414 };2415 });2416 return result;2417 }2418}24192420class SchedulerGroup extends HelperGroup<UniqueHelper> {2421 scheduledIdSlider = 0;24222423 async waitNoScheduledTasks() {2424 const api = this.helper.api!;2425 2426 // eslint-disable-next-line no-async-promise-executor2427 const promise = new Promise<void>(async resolve => {2428 const unsubscribe = await api.rpc.chain.subscribeNewHeads(async () => {2429 const areThereScheduledTasks = await api.query.scheduler.lookup.entries();24302431 if(areThereScheduledTasks.length == 0) {2432 unsubscribe();2433 resolve();2434 }2435 }); 2436 });24372438 return promise;2439 }24402441 async makeScheduledIds(num: number): Promise<string[]> {2442 await this.waitNoScheduledTasks();24432444 function makeId(slider: number) {2445 const scheduledIdSize = 32;2446 const hexId = slider.toString(16);2447 const prefixSize = scheduledIdSize - hexId.length;24482449 const scheduledId = '0x' + '0'.repeat(prefixSize) + hexId;24502451 return scheduledId; 2452 }24532454 const ids = [];2455 for (let i = 0; i < num; i++) {2456 ids.push(makeId(this.scheduledIdSlider));2457 this.scheduledIdSlider += 1;2458 }24592460 return ids;2461 }24622463 async makeScheduledId(): Promise<string> {2464 return (await this.makeScheduledIds(1))[0];2465 }24662467 async cancelScheduled(signer: TSigner, scheduledId: string) {2468 return this.helper.executeExtrinsic(2469 signer,2470 'api.tx.scheduler.cancelNamed',2471 [scheduledId],2472 true,2473 );2474 }24752476 async changePriority(signer: TSigner, scheduledId: string, priority: number) {2477 return this.helper.executeExtrinsic(2478 signer,2479 'api.tx.scheduler.changeNamedPriority',2480 [scheduledId, priority],2481 true,2482 );2483 }24842485 scheduleAt<T extends UniqueHelper>(2486 scheduledId: string,2487 executionBlockNumber: number,2488 options: ISchedulerOptions = {},2489 ) {2490 return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2491 }24922493 scheduleAfter<T extends UniqueHelper>(2494 scheduledId: string,2495 blocksBeforeExecution: number,2496 options: ISchedulerOptions = {},2497 ) {2498 return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2499 }25002501 schedule<T extends UniqueHelper>(2502 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2503 scheduledId: string,2504 blocksNum: number,2505 options: ISchedulerOptions = {},2506 ) {2507 // eslint-disable-next-line @typescript-eslint/naming-convention2508 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2509 return this.helper.clone(ScheduledHelperType, {2510 scheduleFn,2511 scheduledId,2512 blocksNum,2513 options,2514 }) as T;2515 }2516}25172518class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2519 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2520 await this.helper.executeExtrinsic(2521 signer,2522 'api.tx.foreignAssets.registerForeignAsset',2523 [ownerAddress, location, metadata],2524 true,2525 );2526 }25272528 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2529 await this.helper.executeExtrinsic(2530 signer,2531 'api.tx.foreignAssets.updateForeignAsset',2532 [foreignAssetId, location, metadata],2533 true,2534 );2535 }2536}25372538class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2539 palletName: string;25402541 constructor(helper: T, palletName: string) {2542 super(helper);25432544 this.palletName = palletName;2545 }25462547 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2548 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2549 }2550}25512552class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2553 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2554 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2555 }25562557 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2558 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2559 }25602561 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2562 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2563 }2564}25652566class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2567 async accounts(address: string, currencyId: any) {2568 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2569 return BigInt(free);2570 }2571}25722573class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2574 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2575 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2576 }25772578 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2579 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2580 }25812582 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2583 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2584 }25852586 async account(assetId: string | number, address: string) {2587 const accountAsset = (2588 await this.helper.callRpc('api.query.assets.account', [assetId, address])2589 ).toJSON()! as any;25902591 if (accountAsset !== null) {2592 return BigInt(accountAsset['balance']);2593 } else {2594 return null;2595 }2596 }2597}25982599class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2600 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2601 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2602 }2603}26042605class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2606 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2607 const apiPrefix = 'api.tx.assetManager.';26082609 const registerTx = this.helper.constructApiCall(2610 apiPrefix + 'registerForeignAsset',2611 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2612 );26132614 const setUnitsTx = this.helper.constructApiCall(2615 apiPrefix + 'setAssetUnitsPerSecond',2616 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2617 );26182619 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2620 const encodedProposal = batchCall?.method.toHex() || '';2621 return encodedProposal;2622 }26232624 async assetTypeId(location: any) {2625 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2626 }2627}26282629class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2630 async notePreimage(signer: TSigner, encodedProposal: string) {2631 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2632 }26332634 externalProposeMajority(proposalHash: string) {2635 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2636 }26372638 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2639 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2640 }26412642 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2643 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2644 }2645}26462647class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2648 collective: string;26492650 constructor(helper: MoonbeamHelper, collective: string) {2651 super(helper);26522653 this.collective = collective;2654 }26552656 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2657 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2658 }26592660 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2661 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2662 }26632664 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2665 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2666 }26672668 async proposalCount() {2669 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2670 }2671}26722673export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2674export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;26752676export class UniqueHelper extends ChainHelperBase {2677 balance: BalanceGroup<UniqueHelper>;2678 collection: CollectionGroup;2679 nft: NFTGroup;2680 rft: RFTGroup;2681 ft: FTGroup;2682 staking: StakingGroup;2683 scheduler: SchedulerGroup;2684 foreignAssets: ForeignAssetsGroup;2685 xcm: XcmGroup<UniqueHelper>;2686 xTokens: XTokensGroup<UniqueHelper>;2687 tokens: TokensGroup<UniqueHelper>;26882689 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2690 super(logger, options.helperBase ?? UniqueHelper);26912692 this.balance = new BalanceGroup(this);2693 this.collection = new CollectionGroup(this);2694 this.nft = new NFTGroup(this);2695 this.rft = new RFTGroup(this);2696 this.ft = new FTGroup(this);2697 this.staking = new StakingGroup(this);2698 this.scheduler = new SchedulerGroup(this);2699 this.foreignAssets = new ForeignAssetsGroup(this);2700 this.xcm = new XcmGroup(this, 'polkadotXcm');2701 this.xTokens = new XTokensGroup(this);2702 this.tokens = new TokensGroup(this);2703 }27042705 getSudo<T extends UniqueHelper>() {2706 // eslint-disable-next-line @typescript-eslint/naming-convention2707 const SudoHelperType = SudoHelper(this.helperBase);2708 return this.clone(SudoHelperType) as T;2709 }2710}27112712export class XcmChainHelper extends ChainHelperBase {2713 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2714 const wsProvider = new WsProvider(wsEndpoint);2715 this.api = new ApiPromise({2716 provider: wsProvider,2717 });2718 await this.api.isReadyOrError;2719 this.network = await UniqueHelper.detectNetwork(this.api);2720 }2721}27222723export class RelayHelper extends XcmChainHelper {2724 xcm: XcmGroup<RelayHelper>;27252726 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2727 super(logger, options.helperBase ?? RelayHelper);27282729 this.xcm = new XcmGroup(this, 'xcmPallet');2730 }2731}27322733export class WestmintHelper extends XcmChainHelper {2734 balance: SubstrateBalanceGroup<WestmintHelper>;2735 xcm: XcmGroup<WestmintHelper>;2736 assets: AssetsGroup<WestmintHelper>;2737 xTokens: XTokensGroup<WestmintHelper>;27382739 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2740 super(logger, options.helperBase ?? WestmintHelper);27412742 this.balance = new SubstrateBalanceGroup(this);2743 this.xcm = new XcmGroup(this, 'polkadotXcm');2744 this.assets = new AssetsGroup(this);2745 this.xTokens = new XTokensGroup(this);2746 }2747}27482749export class MoonbeamHelper extends XcmChainHelper {2750 balance: EthereumBalanceGroup<MoonbeamHelper>;2751 assetManager: MoonbeamAssetManagerGroup;2752 assets: AssetsGroup<MoonbeamHelper>;2753 xTokens: XTokensGroup<MoonbeamHelper>;2754 democracy: MoonbeamDemocracyGroup;2755 collective: {2756 council: MoonbeamCollectiveGroup,2757 techCommittee: MoonbeamCollectiveGroup,2758 };27592760 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2761 super(logger, options.helperBase ?? MoonbeamHelper);27622763 this.balance = new EthereumBalanceGroup(this);2764 this.assetManager = new MoonbeamAssetManagerGroup(this);2765 this.assets = new AssetsGroup(this);2766 this.xTokens = new XTokensGroup(this);2767 this.democracy = new MoonbeamDemocracyGroup(this);2768 this.collective = {2769 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2770 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2771 };2772 }2773}27742775export class AcalaHelper extends XcmChainHelper {2776 balance: SubstrateBalanceGroup<AcalaHelper>;2777 assetRegistry: AcalaAssetRegistryGroup;2778 xTokens: XTokensGroup<AcalaHelper>;2779 tokens: TokensGroup<AcalaHelper>;27802781 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2782 super(logger, options.helperBase ?? AcalaHelper);27832784 this.balance = new SubstrateBalanceGroup(this);2785 this.assetRegistry = new AcalaAssetRegistryGroup(this);2786 this.xTokens = new XTokensGroup(this);2787 this.tokens = new TokensGroup(this);2788 }27892790 getSudo<T extends AcalaHelper>() {2791 // eslint-disable-next-line @typescript-eslint/naming-convention2792 const SudoHelperType = SudoHelper(this.helperBase);2793 return this.clone(SudoHelperType) as T;2794 }2795}27962797// eslint-disable-next-line @typescript-eslint/naming-convention2798function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2799 return class extends Base {2800 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2801 scheduledId: string;2802 blocksNum: number;2803 options: ISchedulerOptions;28042805 constructor(...args: any[]) {2806 const logger = args[0] as ILogger;2807 const options = args[1] as {2808 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2809 scheduledId: string,2810 blocksNum: number,2811 options: ISchedulerOptions2812 };28132814 super(logger);28152816 this.scheduleFn = options.scheduleFn;2817 this.scheduledId = options.scheduledId;2818 this.blocksNum = options.blocksNum;2819 this.options = options.options;2820 }28212822 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2823 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2824 const extrinsic = 'api.tx.scheduler.' + this.scheduleFn;28252826 return super.executeExtrinsic(2827 sender,2828 extrinsic,2829 [2830 this.scheduledId,2831 this.blocksNum,2832 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2833 this.options.priority ?? null,2834 {Value: scheduledTx},2835 ],2836 expectSuccess,2837 );2838 }2839 };2840}28412842// eslint-disable-next-line @typescript-eslint/naming-convention2843function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2844 return class extends Base {2845 constructor(...args: any[]) {2846 super(...args);2847 }28482849 executeExtrinsic (2850 sender: IKeyringPair,2851 extrinsic: string,2852 params: any[],2853 expectSuccess?: boolean,2854 ): Promise<ITransactionResult> {2855 const call = this.constructApiCall(extrinsic, params);28562857 return super.executeExtrinsic(2858 sender,2859 'api.tx.sudo.sudo',2860 [call],2861 expectSuccess,2862 );2863 }2864 };2865}28662867export class UniqueBaseCollection {2868 helper: UniqueHelper;2869 collectionId: number;28702871 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2872 this.collectionId = collectionId;2873 this.helper = uniqueHelper;2874 }28752876 async getData() {2877 return await this.helper.collection.getData(this.collectionId);2878 }28792880 async getLastTokenId() {2881 return await this.helper.collection.getLastTokenId(this.collectionId);2882 }28832884 async doesTokenExist(tokenId: number) {2885 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2886 }28872888 async getAdmins() {2889 return await this.helper.collection.getAdmins(this.collectionId);2890 }28912892 async getAllowList() {2893 return await this.helper.collection.getAllowList(this.collectionId);2894 }28952896 async getEffectiveLimits() {2897 return await this.helper.collection.getEffectiveLimits(this.collectionId);2898 }28992900 async getProperties(propertyKeys?: string[] | null) {2901 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2902 }29032904 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2905 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2906 }29072908 async getOptions() {2909 return await this.helper.collection.getCollectionOptions(this.collectionId);2910 }29112912 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2913 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2914 }29152916 async confirmSponsorship(signer: TSigner) {2917 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2918 }29192920 async removeSponsor(signer: TSigner) {2921 return await this.helper.collection.removeSponsor(signer, this.collectionId);2922 }29232924 async setLimits(signer: TSigner, limits: ICollectionLimits) {2925 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2926 }29272928 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2929 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2930 }29312932 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2933 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2934 }29352936 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2937 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2938 }29392940 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2941 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2942 }29432944 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2945 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2946 }29472948 async setProperties(signer: TSigner, properties: IProperty[]) {2949 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2950 }29512952 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2953 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2954 }29552956 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2957 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2958 }29592960 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2961 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2962 }29632964 async disableNesting(signer: TSigner) {2965 return await this.helper.collection.disableNesting(signer, this.collectionId);2966 }29672968 async burn(signer: TSigner) {2969 return await this.helper.collection.burn(signer, this.collectionId);2970 }29712972 scheduleAt<T extends UniqueHelper>(2973 scheduledId: string,2974 executionBlockNumber: number,2975 options: ISchedulerOptions = {},2976 ) {2977 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2978 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2979 }29802981 scheduleAfter<T extends UniqueHelper>(2982 scheduledId: string,2983 blocksBeforeExecution: number,2984 options: ISchedulerOptions = {},2985 ) {2986 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2987 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2988 }29892990 getSudo<T extends UniqueHelper>() {2991 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2992 }2993}299429952996export class UniqueNFTCollection extends UniqueBaseCollection {2997 getTokenObject(tokenId: number) {2998 return new UniqueNFToken(tokenId, this);2999 }30003001 async getTokensByAddress(addressObj: ICrossAccountId) {3002 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3003 }30043005 async getToken(tokenId: number, blockHashAt?: string) {3006 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3007 }30083009 async getTokenOwner(tokenId: number, blockHashAt?: string) {3010 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3011 }30123013 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3014 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3015 }30163017 async getTokenChildren(tokenId: number, blockHashAt?: string) {3018 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3019 }30203021 async getPropertyPermissions(propertyKeys: string[] | null = null) {3022 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3023 }30243025 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3026 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3027 }30283029 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3030 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3031 }30323033 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3034 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3035 }30363037 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3038 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3039 }30403041 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3042 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3043 }30443045 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3046 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3047 }30483049 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3050 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3051 }30523053 async burnToken(signer: TSigner, tokenId: number) {3054 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3055 }30563057 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3058 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3059 }30603061 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3062 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3063 }30643065 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3066 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3067 }30683069 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3070 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3071 }30723073 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3074 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3075 }30763077 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3078 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3079 }30803081 scheduleAt<T extends UniqueHelper>(3082 scheduledId: string,3083 executionBlockNumber: number,3084 options: ISchedulerOptions = {},3085 ) {3086 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3087 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3088 }30893090 scheduleAfter<T extends UniqueHelper>(3091 scheduledId: string,3092 blocksBeforeExecution: number,3093 options: ISchedulerOptions = {},3094 ) {3095 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3096 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3097 }30983099 getSudo<T extends UniqueHelper>() {3100 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3101 }3102}310331043105export class UniqueRFTCollection extends UniqueBaseCollection {3106 getTokenObject(tokenId: number) {3107 return new UniqueRFToken(tokenId, this);3108 }31093110 async getToken(tokenId: number, blockHashAt?: string) {3111 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3112 }31133114 async getTokensByAddress(addressObj: ICrossAccountId) {3115 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3116 }31173118 async getTop10TokenOwners(tokenId: number) {3119 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3120 }31213122 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3123 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3124 }31253126 async getTokenTotalPieces(tokenId: number) {3127 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3128 }31293130 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3131 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3132 }31333134 async getPropertyPermissions(propertyKeys: string[] | null = null) {3135 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3136 }31373138 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3139 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3140 }31413142 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3143 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3144 }31453146 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3147 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3148 }31493150 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3151 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3152 }31533154 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3155 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3156 }31573158 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3159 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3160 }31613162 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3163 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3164 }31653166 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3167 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3168 }31693170 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3171 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3172 }31733174 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3175 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3176 }31773178 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3179 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3180 }31813182 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3183 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3184 }31853186 scheduleAt<T extends UniqueHelper>(3187 scheduledId: string,3188 executionBlockNumber: number,3189 options: ISchedulerOptions = {},3190 ) {3191 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3192 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3193 }31943195 scheduleAfter<T extends UniqueHelper>(3196 scheduledId: string,3197 blocksBeforeExecution: number,3198 options: ISchedulerOptions = {},3199 ) {3200 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3201 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3202 }32033204 getSudo<T extends UniqueHelper>() {3205 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3206 }3207}320832093210export class UniqueFTCollection extends UniqueBaseCollection {3211 async getBalance(addressObj: ICrossAccountId) {3212 return await this.helper.ft.getBalance(this.collectionId, addressObj);3213 }32143215 async getTotalPieces() {3216 return await this.helper.ft.getTotalPieces(this.collectionId);3217 }32183219 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3220 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3221 }32223223 async getTop10Owners() {3224 return await this.helper.ft.getTop10Owners(this.collectionId);3225 }32263227 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3228 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3229 }32303231 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3232 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3233 }32343235 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3236 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3237 }32383239 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3240 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3241 }32423243 async burnTokens(signer: TSigner, amount=1n) {3244 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3245 }32463247 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3248 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3249 }32503251 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3252 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3253 }32543255 scheduleAt<T extends UniqueHelper>(3256 scheduledId: string,3257 executionBlockNumber: number,3258 options: ISchedulerOptions = {},3259 ) {3260 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3261 return new UniqueFTCollection(this.collectionId, scheduledHelper);3262 }32633264 scheduleAfter<T extends UniqueHelper>(3265 scheduledId: string,3266 blocksBeforeExecution: number,3267 options: ISchedulerOptions = {},3268 ) {3269 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3270 return new UniqueFTCollection(this.collectionId, scheduledHelper);3271 }32723273 getSudo<T extends UniqueHelper>() {3274 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3275 }3276}327732783279export class UniqueBaseToken {3280 collection: UniqueNFTCollection | UniqueRFTCollection;3281 collectionId: number;3282 tokenId: number;32833284 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3285 this.collection = collection;3286 this.collectionId = collection.collectionId;3287 this.tokenId = tokenId;3288 }32893290 async getNextSponsored(addressObj: ICrossAccountId) {3291 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3292 }32933294 async getProperties(propertyKeys?: string[] | null) {3295 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3296 }32973298 async setProperties(signer: TSigner, properties: IProperty[]) {3299 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3300 }33013302 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3303 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3304 }33053306 async doesExist() {3307 return await this.collection.doesTokenExist(this.tokenId);3308 }33093310 nestingAccount() {3311 return this.collection.helper.util.getTokenAccount(this);3312 }33133314 scheduleAt<T extends UniqueHelper>(3315 scheduledId: string,3316 executionBlockNumber: number,3317 options: ISchedulerOptions = {},3318 ) {3319 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3320 return new UniqueBaseToken(this.tokenId, scheduledCollection);3321 }33223323 scheduleAfter<T extends UniqueHelper>(3324 scheduledId: string,3325 blocksBeforeExecution: number,3326 options: ISchedulerOptions = {},3327 ) {3328 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3329 return new UniqueBaseToken(this.tokenId, scheduledCollection);3330 }33313332 getSudo<T extends UniqueHelper>() {3333 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3334 }3335}333633373338export class UniqueNFToken extends UniqueBaseToken {3339 collection: UniqueNFTCollection;33403341 constructor(tokenId: number, collection: UniqueNFTCollection) {3342 super(tokenId, collection);3343 this.collection = collection;3344 }33453346 async getData(blockHashAt?: string) {3347 return await this.collection.getToken(this.tokenId, blockHashAt);3348 }33493350 async getOwner(blockHashAt?: string) {3351 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3352 }33533354 async getTopmostOwner(blockHashAt?: string) {3355 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3356 }33573358 async getChildren(blockHashAt?: string) {3359 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3360 }33613362 async nest(signer: TSigner, toTokenObj: IToken) {3363 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3364 }33653366 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3367 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3368 }33693370 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3371 return await this.collection.transferToken(signer, this.tokenId, addressObj);3372 }33733374 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3375 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3376 }33773378 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3379 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3380 }33813382 async isApproved(toAddressObj: ICrossAccountId) {3383 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3384 }33853386 async burn(signer: TSigner) {3387 return await this.collection.burnToken(signer, this.tokenId);3388 }33893390 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3391 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3392 }33933394 scheduleAt<T extends UniqueHelper>(3395 scheduledId: string,3396 executionBlockNumber: number,3397 options: ISchedulerOptions = {},3398 ) {3399 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3400 return new UniqueNFToken(this.tokenId, scheduledCollection);3401 }34023403 scheduleAfter<T extends UniqueHelper>(3404 scheduledId: string,3405 blocksBeforeExecution: number,3406 options: ISchedulerOptions = {},3407 ) {3408 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3409 return new UniqueNFToken(this.tokenId, scheduledCollection);3410 }34113412 getSudo<T extends UniqueHelper>() {3413 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3414 }3415}34163417export class UniqueRFToken extends UniqueBaseToken {3418 collection: UniqueRFTCollection;34193420 constructor(tokenId: number, collection: UniqueRFTCollection) {3421 super(tokenId, collection);3422 this.collection = collection;3423 }34243425 async getData(blockHashAt?: string) {3426 return await this.collection.getToken(this.tokenId, blockHashAt);3427 }34283429 async getTop10Owners() {3430 return await this.collection.getTop10TokenOwners(this.tokenId);3431 }34323433 async getBalance(addressObj: ICrossAccountId) {3434 return await this.collection.getTokenBalance(this.tokenId, addressObj);3435 }34363437 async getTotalPieces() {3438 return await this.collection.getTokenTotalPieces(this.tokenId);3439 }34403441 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3442 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3443 }34443445 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3446 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3447 }34483449 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3450 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3451 }34523453 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3454 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3455 }34563457 async repartition(signer: TSigner, amount: bigint) {3458 return await this.collection.repartitionToken(signer, this.tokenId, amount);3459 }34603461 async burn(signer: TSigner, amount=1n) {3462 return await this.collection.burnToken(signer, this.tokenId, amount);3463 }34643465 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3466 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3467 }34683469 scheduleAt<T extends UniqueHelper>(3470 scheduledId: string,3471 executionBlockNumber: number,3472 options: ISchedulerOptions = {},3473 ) {3474 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3475 return new UniqueRFToken(this.tokenId, scheduledCollection);3476 }34773478 scheduleAfter<T extends UniqueHelper>(3479 scheduledId: string,3480 blocksBeforeExecution: number,3481 options: ISchedulerOptions = {},3482 ) {3483 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3484 return new UniqueRFToken(this.tokenId, scheduledCollection);3485 }34863487 getSudo<T extends UniqueHelper>() {3488 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3489 }3490}