difftreelog
test fix integration
in: master
6 files changed
tests/src/eth/contractSponsoring.test.tsdiffbeforeafterboth--- a/tests/src/eth/contractSponsoring.test.ts
+++ b/tests/src/eth/contractSponsoring.test.ts
@@ -516,7 +516,7 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const sponsor = await helper.eth.createAccountWithBalance(donor);
const user = await helper.eth.createAccountWithBalance(donor);
- const helpers = await helper.ethNativeContract.contractHelpers(owner);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
const testContract = await deployTestContract(helper, owner);
@@ -531,10 +531,10 @@
await helpers.methods.setSponsoringFeeLimit(testContract.options.address, 2_000_000n * gasPrice).send();
const originalUserBalance = await helper.balance.getEthereum(user);
- await testContract.methods.test(100).send({from: user, gas: 2_000_000});
+ await testContract.methods.test(100).send({from: user, gas: 2_000_000, maxFeePerGas: gasPrice.toString()});
expect(await helper.balance.getEthereum(user)).to.be.equal(originalUserBalance);
- await testContract.methods.test(100).send({from: user, gas: 2_100_000});
+ await testContract.methods.test(100).send({from: user, gas: 2_100_000, maxFeePerGas: gasPrice.toString()});
expect(await helper.balance.getEthereum(user)).to.not.be.equal(originalUserBalance);
});
tests/src/eth/ethFeesAreCorrect.test.tsdiffbeforeafterboth--- a/tests/src/eth/ethFeesAreCorrect.test.ts
+++ b/tests/src/eth/ethFeesAreCorrect.test.ts
@@ -41,10 +41,10 @@
const {tokenId: tokenB} = await collection.mintToken(minter, {Ethereum: aliceEth});
const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
- const contract = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+ const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
const balanceBeforeWeb3Transfer = await helper.balance.getEthereum(owner);
- await contract.methods.transfer(receiver, tokenA).send({from: owner});
+ await contract.methods.transfer(receiver, tokenA).send({from: owner, maxFeePerGas: (await helper.eth.getGasPrice()).toString()});
const balanceAfterWeb3Transfer = await helper.balance.getEthereum(owner);
const web3Diff = balanceBeforeWeb3Transfer - balanceAfterWeb3Transfer;
tests/src/eth/reFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -674,7 +674,7 @@
requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
donor = await privateKey({url: import.meta.url});
- [alice] = await helper.arrange.createAccounts([20n], donor);
+ [alice] = await helper.arrange.createAccounts([1000n], donor);
});
});
@@ -699,7 +699,7 @@
},
);
- const contract = await helper.ethNativeContract.collectionById(collection.collectionId, 'rft', caller);
+ const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'rft', caller);
const name = await contract.methods.name().call();
expect(name).to.equal('Leviathan');
});
tests/src/maintenance.seqtest.tsdiffbeforeafterboth--- a/tests/src/maintenance.seqtest.ts
+++ b/tests/src/maintenance.seqtest.ts
@@ -342,19 +342,19 @@
itSub('Does not allow preimage execution with non-root', async ({helper}) => {
await expect(helper.executeExtrinsic(bob, 'api.tx.maintenance.executePreimage', [
preimageHashes[0], {refTime: 10000000000, proofSize: 10000},
- ])).to.be.rejectedWith(/BadOrigin/);
+ ])).to.be.rejectedWith(/^Misc: BadOrigin$/);
});
itSub('Does not allow execution of non-existent preimages', async ({helper}) => {
await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [
'0x1010101010101010101010101010101010101010101010101010101010101010', {refTime: 10000000000, proofSize: 10000},
- ])).to.be.rejectedWith(/Unavailable/);
+ ])).to.be.rejectedWith(/^Misc: Unavailable$/);
});
itSub('Does not allow preimage execution with less than minimum weights', async ({helper}) => {
await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [
preimageHashes[0], {refTime: 1000, proofSize: 100},
- ])).to.be.rejectedWith(/Exhausted/);
+ ])).to.be.rejectedWith(/^Misc: Exhausted$/);
});
after(async function() {
tests/src/pallet-presence.test.tsdiffbeforeafterboth--- a/tests/src/pallet-presence.test.ts
+++ b/tests/src/pallet-presence.test.ts
@@ -24,6 +24,7 @@
'timestamp',
'transactionpayment',
'treasury',
+ 'statetriemigration',
'structure',
'system',
'vesting',
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 {SignerOptions} from '@polkadot/api/types/submittable';10import '../../interfaces/augment-api';11import {AugmentedSubmittables} from '@polkadot/api-base/types/submittable';12import {ApiInterfaceEvents} from '@polkadot/api/types';13import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';14import {IKeyringPair} from '@polkadot/types/types';15import {hexToU8a} from '@polkadot/util/hex';16import {u8aConcat} from '@polkadot/util/u8a';17import {18 IApiListeners,19 IBlock,20 IEvent,21 IChainProperties,22 ICollectionCreationOptions,23 ICollectionLimits,24 ICollectionPermissions,25 ICrossAccountId,26 ICrossAccountIdLower,27 ILogger,28 INestingPermissions,29 IProperty,30 IStakingInfo,31 ISchedulerOptions,32 ISubstrateBalance,33 IToken,34 ITokenPropertyPermission,35 ITransactionResult,36 IUniqueHelperLog,37 TApiAllowedListeners,38 TEthereumAccount,39 TSigner,40 TSubstrateAccount,41 TNetworks,42 IForeignAssetMetadata,43 AcalaAssetMetadata,44 MoonbeamAssetInfo,45 DemocracyStandardAccountVote,46 IEthCrossAccountId,47} from './types';48import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';49import type {Vec} from '@polkadot/types-codec';50import {FrameSystemEventRecord, PalletBalancesIdAmount} from '@polkadot/types/lookup';5152export class CrossAccountId {53 Substrate!: TSubstrateAccount;54 Ethereum!: TEthereumAccount;5556 constructor(account: ICrossAccountId) {57 if ('Substrate' in account) this.Substrate = account.Substrate;58 else this.Ethereum = account.Ethereum;59 }6061 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {62 switch (domain) {63 case 'Substrate': return new CrossAccountId({Substrate: account.address});64 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();65 }66 }6768 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {69 if ('substrate' in address) return new CrossAccountId({Substrate: address.substrate});70 else return new CrossAccountId({Ethereum: address.ethereum});71 }7273 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {74 return encodeAddress(decodeAddress(address), ss58Format);75 }7677 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {78 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});79 }8081 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {82 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);83 return this;84 }8586 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {87 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));88 }8990 toEthereum(): CrossAccountId {91 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});92 return this;93 }9495 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {96 return evmToAddress(address, ss58Format);97 }9899 toSubstrate(ss58Format?: number): CrossAccountId {100 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});101 return this;102 }103104 toLowerCase(): CrossAccountId {105 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();106 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();107 return this;108 }109}110111const nesting = {112 toChecksumAddress(address: string): string {113 if (typeof address === 'undefined') return '';114115 if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);116117 address = address.toLowerCase().replace(/^0x/i, '');118 const addressHash = keccakAsHex(address).replace(/^0x/i, '');119 const checksumAddress = ['0x'];120121 for (let i = 0; i < address.length; i++) {122 // If ith character is 8 to f then make it uppercase123 if (parseInt(addressHash[i], 16) > 7) {124 checksumAddress.push(address[i].toUpperCase());125 } else {126 checksumAddress.push(address[i]);127 }128 }129 return checksumAddress.join('');130 },131 tokenIdToAddress(collectionId: number, tokenId: number) {132 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);133 },134};135136class UniqueUtil {137 static transactionStatus = {138 NOT_READY: 'NotReady',139 FAIL: 'Fail',140 SUCCESS: 'Success',141 };142143 static chainLogType = {144 EXTRINSIC: 'extrinsic',145 RPC: 'rpc',146 };147148 static getTokenAccount(token: IToken): CrossAccountId {149 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});150 }151152 static getTokenAddress(token: IToken): string {153 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);154 }155156 static getDefaultLogger(): ILogger {157 return {158 log(msg: any, level = 'INFO') {159 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));160 },161 level: {162 ERROR: 'ERROR',163 WARNING: 'WARNING',164 INFO: 'INFO',165 },166 };167 }168169 static vec2str(arr: string[] | number[]) {170 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');171 }172173 static str2vec(string: string) {174 if (typeof string !== 'string') return string;175 return Array.from(string).map(x => x.charCodeAt(0));176 }177178 static fromSeed(seed: string, ss58Format = 42) {179 const keyring = new Keyring({type: 'sr25519', ss58Format});180 return keyring.addFromUri(seed);181 }182183 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {184 if (creationResult.status !== this.transactionStatus.SUCCESS) {185 throw Error('Unable to create collection!');186 }187188 let collectionId = null;189 creationResult.result.events.forEach(({event: {data, method, section}}) => {190 if ((section === 'common') && (method === 'CollectionCreated')) {191 collectionId = parseInt(data[0].toString(), 10);192 }193 });194195 if (collectionId === null) {196 throw Error('No CollectionCreated event was found!');197 }198199 return collectionId;200 }201202 static extractTokensFromCreationResult(creationResult: ITransactionResult): {203 success: boolean,204 tokens: { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[],205 } {206 if (creationResult.status !== this.transactionStatus.SUCCESS) {207 throw Error('Unable to create tokens!');208 }209 let success = false;210 const tokens = [] as { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[];211 creationResult.result.events.forEach(({event: {data, method, section}}) => {212 if (method === 'ExtrinsicSuccess') {213 success = true;214 } else if ((section === 'common') && (method === 'ItemCreated')) {215 tokens.push({216 collectionId: parseInt(data[0].toString(), 10),217 tokenId: parseInt(data[1].toString(), 10),218 owner: data[2].toHuman(),219 amount: data[3].toBigInt(),220 });221 }222 });223 return {success, tokens};224 }225226 static extractTokensFromBurnResult(burnResult: ITransactionResult): {227 success: boolean,228 tokens: { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[],229 } {230 if (burnResult.status !== this.transactionStatus.SUCCESS) {231 throw Error('Unable to burn tokens!');232 }233 let success = false;234 const tokens = [] as { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[];235 burnResult.result.events.forEach(({event: {data, method, section}}) => {236 if (method === 'ExtrinsicSuccess') {237 success = true;238 } else if ((section === 'common') && (method === 'ItemDestroyed')) {239 tokens.push({240 collectionId: parseInt(data[0].toString(), 10),241 tokenId: parseInt(data[1].toString(), 10),242 owner: data[2].toHuman(),243 amount: data[3].toBigInt(),244 });245 }246 });247 return {success, tokens};248 }249250 static findCollectionInEvents(events: { event: IEvent }[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {251 let eventId = null;252 events.forEach(({event: {data, method, section}}) => {253 if ((section === expectedSection) && (method === expectedMethod)) {254 eventId = parseInt(data[0].toString(), 10);255 }256 });257258 if (eventId === null) {259 throw Error(`No ${expectedMethod} event was found!`);260 }261 return eventId === collectionId;262 }263264 static isTokenTransferSuccess(events: { event: IEvent }[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {265 const normalizeAddress = (address: string | ICrossAccountId) => {266 if (typeof address === 'string') return address;267 const obj = {} as any;268 Object.keys(address).forEach(k => {269 obj[k.toLocaleLowerCase()] = (address as any)[k];270 });271 if (obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);272 if (obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();273 return address;274 };275 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;276 events.forEach(({event: {data, method, section}}) => {277 if ((section === 'common') && (method === 'Transfer')) {278 const hData = (data as any).toJSON();279 transfer = {280 collectionId: hData[0],281 tokenId: hData[1],282 from: normalizeAddress(hData[2]),283 to: normalizeAddress(hData[3]),284 amount: BigInt(hData[4]),285 };286 }287 });288 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;289 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);290 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);291 isSuccess = isSuccess && amount === transfer.amount;292 return isSuccess;293 }294295 static bigIntToDecimals(number: bigint, decimals = 18) {296 const numberStr = number.toString();297 const dotPos = numberStr.length - decimals;298299 if (dotPos <= 0) {300 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;301 } else {302 const intPart = numberStr.substring(0, dotPos);303 const fractPart = numberStr.substring(dotPos);304 return intPart + '.' + fractPart;305 }306 }307}308309class UniqueEventHelper {310 private static extractIndex(index: any): [number, number] | string {311 if (index.toRawType() === '[u8;2]') return [index[0], index[1]];312 return index.toJSON();313 }314315 private static extractSub(data: any, subTypes: any): { [key: string]: any } {316 let obj: any = {};317 let index = 0;318319 if (data.entries) {320 for (const [key, value] of data.entries()) {321 obj[key] = this.extractData(value, subTypes[index]);322 index++;323 }324 } else obj = data.toJSON();325326 return obj;327 }328329 private static toHuman(data: any) {330 return data && data.toHuman ? data.toHuman() : `${data}`;331 }332333 private static extractData(data: any, type: any): any {334 if (!type) return this.toHuman(data);335 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();336 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();337 if (type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);338 return this.toHuman(data);339 }340341 public static extractEvents(events: { event: any, phase: any }[]): IEvent[] {342 const parsedEvents: IEvent[] = [];343344 events.forEach((record) => {345 const {event, phase} = record;346 const types = event.typeDef;347348 const eventData: IEvent = {349 section: event.section.toString(),350 method: event.method.toString(),351 index: this.extractIndex(event.index),352 data: [],353 phase: phase.toJSON(),354 };355356 event.data.forEach((val: any, index: number) => {357 eventData.data.push(this.extractData(val, types[index]));358 });359360 parsedEvents.push(eventData);361 });362363 return parsedEvents;364 }365}366const InvalidTypeSymbol = Symbol('Invalid type');367// eslint-disable-next-line @typescript-eslint/no-unused-vars368export type Invalid<ErrorMessage> =369 | ((370 invalidType: typeof InvalidTypeSymbol,371 ..._: typeof InvalidTypeSymbol[]372 ) => typeof InvalidTypeSymbol)373 | null374 | undefined;375// Has slightly better error messages than Get376type Get2<T, P extends string, E> =377 P extends `${infer Key}.${infer Key2}` ? Key extends keyof T ? Key2 extends keyof T[Key] ? T[Key][Key2] : E : E : E;378type ForceFunction<T> = T extends (...args: any) => any ? T : (...args: any) => Invalid<'not a function'>;379380export class ChainHelperBase {381 helperBase: any;382383 transactionStatus = UniqueUtil.transactionStatus;384 chainLogType = UniqueUtil.chainLogType;385 util: typeof UniqueUtil;386 eventHelper: typeof UniqueEventHelper;387 logger: ILogger;388 api: ApiPromise | null;389 forcedNetwork: TNetworks | null;390 network: TNetworks | null;391 wsEndpoint: string | null;392 chainLog: IUniqueHelperLog[];393 children: ChainHelperBase[];394 address: AddressGroup;395 chain: ChainGroup;396397 constructor(logger?: ILogger, helperBase?: any) {398 this.helperBase = helperBase;399400 this.util = UniqueUtil;401 this.eventHelper = UniqueEventHelper;402 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();403 this.logger = logger;404 this.api = null;405 this.forcedNetwork = null;406 this.network = null;407 this.wsEndpoint = null;408 this.chainLog = [];409 this.children = [];410 this.address = new AddressGroup(this);411 this.chain = new ChainGroup(this);412 }413414 clone(helperCls: ChainHelperBaseConstructor, options: { [key: string]: any } = {}) {415 Object.setPrototypeOf(helperCls.prototype, this);416 const newHelper = new helperCls(this.logger, options);417418 newHelper.api = this.api;419 newHelper.network = this.network;420 newHelper.forceNetwork = this.forceNetwork;421422 this.children.push(newHelper);423424 return newHelper;425 }426427 getEndpoint(): string {428 if (this.wsEndpoint === null) throw Error('No connection was established');429 return this.wsEndpoint;430 }431432 getApi(): ApiPromise {433 if (this.api === null) throw Error('API not initialized');434 return this.api;435 }436437 async subscribeEvents(expectedEvents: { section: string, names: string[] }[]) {438 const collectedEvents: IEvent[] = [];439 const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {440 const ievents = this.eventHelper.extractEvents(events);441 ievents.forEach((event) => {442 expectedEvents.forEach((e => {443 if (event.section === e.section && e.names.includes(event.method)) {444 collectedEvents.push(event);445 }446 }));447 });448 });449 return {unsubscribe: unsubscribe as any, collectedEvents};450 }451452 clearChainLog(): void {453 this.chainLog = [];454 }455456 forceNetwork(value: TNetworks): void {457 this.forcedNetwork = value;458 }459460 async connect(wsEndpoint: string, listeners?: IApiListeners) {461 if (this.api !== null) throw Error('Already connected');462 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);463 this.wsEndpoint = wsEndpoint;464 this.api = api;465 this.network = network;466 }467468 async disconnect() {469 for (const child of this.children) {470 child.clearApi();471 }472473 if (this.api === null) return;474 await this.api.disconnect();475 this.clearApi();476 }477478 clearApi() {479 this.api = null;480 this.network = null;481 }482483 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {484 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;485 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];486487 if (xcmChains.indexOf(spec.specName) > -1) return spec.specName;488489 if (['quartz', 'unique', 'sapphire'].indexOf(spec.specName) > -1) return spec.specName;490 return 'opal';491 }492493 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {494 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});495 await api.isReady;496497 const network = await this.detectNetwork(api);498499 await api.disconnect();500501 return network;502 }503504 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{505 api: ApiPromise;506 network: TNetworks;507 }> {508 if (typeof network === 'undefined' || network === null) network = 'opal';509 const supportedRPC = {510 opal: {511 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,512 },513 quartz: {514 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,515 },516 unique: {517 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,518 },519 rococo: {},520 westend: {},521 moonbeam: {},522 moonriver: {},523 acala: {},524 karura: {},525 westmint: {},526 };527 if (!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);528 const rpc = supportedRPC[network];529530 // TODO: investigate how to replace rpc in runtime531 // api._rpcCore.addUserInterfaces(rpc);532533 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});534535 await api.isReadyOrError;536537 if (typeof listeners === 'undefined') listeners = {};538 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {539 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;540 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);541 }542543 return {api, network};544 }545546 getTransactionStatus(data: { events: { event: IEvent }[], status: any }) {547 const {events, status} = data;548 if (status.isReady) {549 return this.transactionStatus.NOT_READY;550 }551 if (status.isBroadcast) {552 return this.transactionStatus.NOT_READY;553 }554 if (status.isInBlock || status.isFinalized) {555 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');556 if (errors.length > 0) {557 return this.transactionStatus.FAIL;558 }559 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {560 return this.transactionStatus.SUCCESS;561 }562 }563564 return this.transactionStatus.FAIL;565 }566567 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {568 const sign = (callback: any) => {569 if (options !== null) return transaction.signAndSend(sender, options, callback);570 return transaction.signAndSend(sender, callback);571 };572 // eslint-disable-next-line no-async-promise-executor573 return new Promise(async (resolve, reject) => {574 try {575 const unsub = await sign((result: any) => {576 const status = this.getTransactionStatus(result);577578 if (status === this.transactionStatus.SUCCESS) {579 this.logger.log(`${label} successful`);580 unsub();581 resolve({result, status, blockHash: result.status.asInBlock.toHuman()});582 } else if (status === this.transactionStatus.FAIL) {583 let moduleError = null;584585 if (result.hasOwnProperty('dispatchError')) {586 const dispatchError = result['dispatchError'];587588 if (dispatchError) {589 if (dispatchError.isModule) {590 const modErr = dispatchError.asModule;591 const errorMeta = dispatchError.registry.findMetaError(modErr);592593 moduleError = `${errorMeta.section}.${errorMeta.name}`;594 } else {595 moduleError = dispatchError.toHuman();596 }597 } else {598 this.logger.log(result, this.logger.level.ERROR);599 }600 }601602 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);603 unsub();604 reject({status, moduleError, result});605 }606 });607 } catch (e) {608 this.logger.log(e, this.logger.level.ERROR);609 reject(e);610 }611 });612 }613614 async signTransactionWithoutSending(signer: TSigner, tx: any) {615 const api = this.getApi();616 const signingInfo = await api.derive.tx.signingInfo(signer.address);617618 tx.sign(signer, {619 blockHash: api.genesisHash,620 genesisHash: api.genesisHash,621 runtimeVersion: api.runtimeVersion,622 nonce: signingInfo.nonce,623 });624625 return tx.toHex();626 }627628 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {629 const api = this.getApi();630 const signingInfo = await api.derive.tx.signingInfo(signer.address);631632 // We need to sign the tx because633 // unsigned transactions does not have an inclusion fee634 tx.sign(signer, {635 blockHash: api.genesisHash,636 genesisHash: api.genesisHash,637 runtimeVersion: api.runtimeVersion,638 nonce: signingInfo.nonce,639 });640641 if (len === null) {642 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;643 } else {644 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;645 }646 }647648 constructApiCall(apiCall: string, params: any[]) {649 if (!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);650 let call = this.getApi() as any;651 for (const part of apiCall.slice(4).split('.')) {652 call = call[part];653 if (!call) {654 const advice = part.includes('_') ? ' Looks like it needs to be converted to camel case.' : '';655 throw Error(`Function ${part} of api call ${apiCall} not found.${advice}`);656 }657 }658 return call(...params);659 }660661 encodeApiCall(apiCall: string, params: any[]) {662 return this.constructApiCall(apiCall, params).method.toHex();663 }664665 async executeExtrinsic<666 E extends string,667 V extends (668 ...args: any) => any = ForceFunction<669 Get2<670 AugmentedSubmittables<'promise'>,671 E, (...args: any) => Invalid<'not found'>672 >673 >674 >(675 sender: TSigner,676 extrinsic: `api.tx.${E}`,677 params: Parameters<V>,678 expectSuccess = true,679 options: Partial<SignerOptions> | null = null,/*, failureMessage='expected success'*/680 ): Promise<ITransactionResult> {681 if (this.api === null) throw Error('API not initialized');682 if (!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);683684 const startTime = (new Date()).getTime();685 let result: ITransactionResult;686 let events: IEvent[] = [];687 try {688 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;689 events = this.eventHelper.extractEvents(result.result.events);690 const errorEvent = events.find((event) => event.method == 'ExecutedFailed' || event.method == 'CreatedFailed');691 if (errorEvent)692 throw Error(errorEvent.method + ': ' + extrinsic);693 }694 catch (e) {695 if (!(e as object).hasOwnProperty('status')) throw e;696 result = e as ITransactionResult;697 }698699 const endTime = (new Date()).getTime();700701 const log = {702 executedAt: endTime,703 executionTime: endTime - startTime,704 type: this.chainLogType.EXTRINSIC,705 status: result.status,706 call: extrinsic,707 signer: this.getSignerAddress(sender),708 params,709 } as IUniqueHelperLog;710711 let errorMessage = '';712713 if (result.status !== this.transactionStatus.SUCCESS) {714 if (result.moduleError) {715 errorMessage = typeof result.moduleError === 'string'716 ? result.moduleError717 : `${Object.keys(result.moduleError)[0]}: ${Object.values(result.moduleError)[0]}`;718 log.moduleError = errorMessage;719 }720 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;721 }722 if (events.length > 0) log.events = events;723724 this.chainLog.push(log);725726 if (expectSuccess && result.status !== this.transactionStatus.SUCCESS) {727 if (result.moduleError) throw Error(`${errorMessage}`);728 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));729 }730 return result as any;731 }732733 async callRpc734 // <735 // K extends 'rpc' | 'query',736 // E extends string,737 // V extends (...args: any) => any = ForceFunction<738 // Get2<739 // K extends 'rpc' ? DecoratedRpc<'promise', RpcInterface> : QueryableStorage<'promise'>,740 // E, (...args: any) => Invalid<'not found'>741 // >742 // >,743 // P = Parameters<V>,744 // >745 (rpc: string, params?: any[]): Promise<any> {746747 if (typeof params === 'undefined') params = [] as any;748 if (this.api === null) throw Error('API not initialized');749 if (!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);750751 const startTime = (new Date()).getTime();752 let result;753 let error = null;754 const log = {755 type: this.chainLogType.RPC,756 call: rpc,757 params,758 } as any as IUniqueHelperLog;759760 try {761 result = await this.constructApiCall(rpc, params as any);762 }763 catch (e) {764 error = e;765 }766767 const endTime = (new Date()).getTime();768769 log.executedAt = endTime;770 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';771 log.executionTime = endTime - startTime;772773 this.chainLog.push(log);774775 if (error !== null) throw error;776777 return result;778 }779780 getSignerAddress(signer: IKeyringPair | string): string {781 if (typeof signer === 'string') return signer;782 return signer.address;783 }784785 fetchAllPalletNames(): string[] {786 if (this.api === null) throw Error('API not initialized');787 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase()).sort();788 }789790 fetchMissingPalletNames(requiredPallets: readonly string[]): string[] {791 const palletNames = this.fetchAllPalletNames();792 return requiredPallets.filter(p => !palletNames.includes(p));793 }794}795796797class HelperGroup<T extends ChainHelperBase> {798 helper: T;799800 constructor(uniqueHelper: T) {801 this.helper = uniqueHelper;802 }803}804805806class CollectionGroup extends HelperGroup<UniqueHelper> {807 /**808 * Get number of blocks when sponsored transaction is available.809 *810 * @param collectionId ID of collection811 * @param tokenId ID of token812 * @param addressObj address for which the sponsorship is checked813 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});814 * @returns number of blocks or null if sponsorship hasn't been set815 */816 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {817 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();818 }819820 /**821 * Get the number of created collections.822 *823 * @returns number of created collections824 */825 async getTotalCount(): Promise<number> {826 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();827 }828829 /**830 * Get information about the collection with additional data,831 * including the number of tokens it contains, its administrators,832 * the normalized address of the collection's owner, and decoded name and description.833 *834 * @param collectionId ID of collection835 * @example await getData(2)836 * @returns collection information object837 */838 async getData(collectionId: number): Promise<{839 id: number;840 name: string;841 description: string;842 tokensCount: number;843 admins: CrossAccountId[];844 normalizedOwner: TSubstrateAccount;845 raw: any846 } | null> {847 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);848 const humanCollection = collection.toHuman(), collectionData = {849 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],850 raw: humanCollection,851 } as any, jsonCollection = collection.toJSON();852 if (humanCollection === null) return null;853 collectionData.raw.limits = jsonCollection.limits;854 collectionData.raw.permissions = jsonCollection.permissions;855 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);856 for (const key of ['name', 'description']) {857 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);858 }859860 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))861 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)862 : 0;863 collectionData.admins = await this.getAdmins(collectionId);864865 return collectionData;866 }867868 /**869 * Get the addresses of the collection's administrators, optionally normalized.870 *871 * @param collectionId ID of collection872 * @param normalize whether to normalize the addresses to the default ss58 format873 * @example await getAdmins(1)874 * @returns array of administrators875 */876 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {877 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();878879 return normalize880 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())881 : admins;882 }883884 /**885 * Get the addresses added to the collection allow-list, optionally normalized.886 * @param collectionId ID of collection887 * @param normalize whether to normalize the addresses to the default ss58 format888 * @example await getAllowList(1)889 * @returns array of allow-listed addresses890 */891 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {892 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();893 return normalize894 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())895 : allowListed;896 }897898 /**899 * Get the effective limits of the collection instead of null for default values900 *901 * @param collectionId ID of collection902 * @example await getEffectiveLimits(2)903 * @returns object of collection limits904 */905 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {906 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();907 }908909 /**910 * Burns the collection if the signer has sufficient permissions and collection is empty.911 *912 * @param signer keyring of signer913 * @param collectionId ID of collection914 * @example await helper.collection.burn(aliceKeyring, 3);915 * @returns ```true``` if extrinsic success, otherwise ```false```916 */917 async burn(signer: TSigner, collectionId: number): Promise<boolean> {918 const result = await this.helper.executeExtrinsic(919 signer,920 'api.tx.unique.destroyCollection', [collectionId],921 true,922 );923924 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');925 }926927 /**928 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.929 *930 * @param signer keyring of signer931 * @param collectionId ID of collection932 * @param sponsorAddress Sponsor substrate address933 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")934 * @returns ```true``` if extrinsic success, otherwise ```false```935 */936 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {937 const result = await this.helper.executeExtrinsic(938 signer,939 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],940 true,941 );942943 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');944 }945946 /**947 * Confirms consent to sponsor the collection on behalf of the signer.948 *949 * @param signer keyring of signer950 * @param collectionId ID of collection951 * @example confirmSponsorship(aliceKeyring, 10)952 * @returns ```true``` if extrinsic success, otherwise ```false```953 */954 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {955 const result = await this.helper.executeExtrinsic(956 signer,957 'api.tx.unique.confirmSponsorship', [collectionId],958 true,959 );960961 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');962 }963964 /**965 * Removes the sponsor of a collection, regardless if it consented or not.966 *967 * @param signer keyring of signer968 * @param collectionId ID of collection969 * @example removeSponsor(aliceKeyring, 10)970 * @returns ```true``` if extrinsic success, otherwise ```false```971 */972 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {973 const result = await this.helper.executeExtrinsic(974 signer,975 'api.tx.unique.removeCollectionSponsor', [collectionId],976 true,977 );978979 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');980 }981982 /**983 * Sets the limits of the collection. At least one limit must be specified for a correct call.984 *985 * @param signer keyring of signer986 * @param collectionId ID of collection987 * @param limits collection limits object988 * @example989 * await setLimits(990 * aliceKeyring,991 * 10,992 * {993 * sponsorTransferTimeout: 0,994 * ownerCanDestroy: false995 * }996 * )997 * @returns ```true``` if extrinsic success, otherwise ```false```998 */999 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {1000 const result = await this.helper.executeExtrinsic(1001 signer,1002 'api.tx.unique.setCollectionLimits', [collectionId, limits],1003 true,1004 );10051006 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');1007 }10081009 /**1010 * Changes the owner of the collection to the new Substrate address.1011 *1012 * @param signer keyring of signer1013 * @param collectionId ID of collection1014 * @param ownerAddress substrate address of new owner1015 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")1016 * @returns ```true``` if extrinsic success, otherwise ```false```1017 */1018 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {1019 const result = await this.helper.executeExtrinsic(1020 signer,1021 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],1022 true,1023 );10241025 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');1026 }10271028 /**1029 * Adds a collection administrator.1030 *1031 * @param signer keyring of signer1032 * @param collectionId ID of collection1033 * @param adminAddressObj Administrator address (substrate or ethereum)1034 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})1035 * @returns ```true``` if extrinsic success, otherwise ```false```1036 */1037 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1038 const result = await this.helper.executeExtrinsic(1039 signer,1040 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],1041 true,1042 );10431044 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');1045 }10461047 /**1048 * Removes a collection administrator.1049 *1050 * @param signer keyring of signer1051 * @param collectionId ID of collection1052 * @param adminAddressObj Administrator address (substrate or ethereum)1053 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})1054 * @returns ```true``` if extrinsic success, otherwise ```false```1055 */1056 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1057 const result = await this.helper.executeExtrinsic(1058 signer,1059 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],1060 true,1061 );10621063 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');1064 }10651066 /**1067 * Check if user is in allow list.1068 *1069 * @param collectionId ID of collection1070 * @param user Account to check1071 * @example await getAdmins(1)1072 * @returns is user in allow list1073 */1074 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {1075 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();1076 }10771078 /**1079 * Adds an address to allow list1080 * @param signer keyring of signer1081 * @param collectionId ID of collection1082 * @param addressObj address to add to the allow list1083 * @returns ```true``` if extrinsic success, otherwise ```false```1084 */1085 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1086 const result = await this.helper.executeExtrinsic(1087 signer,1088 'api.tx.unique.addToAllowList', [collectionId, addressObj],1089 true,1090 );10911092 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1093 }10941095 /**1096 * Removes an address from allow list1097 *1098 * @param signer keyring of signer1099 * @param collectionId ID of collection1100 * @param addressObj address to remove from the allow list1101 * @returns ```true``` if extrinsic success, otherwise ```false```1102 */1103 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1104 const result = await this.helper.executeExtrinsic(1105 signer,1106 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1107 true,1108 );11091110 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1111 }11121113 /**1114 * Sets onchain permissions for selected collection.1115 *1116 * @param signer keyring of signer1117 * @param collectionId ID of collection1118 * @param permissions collection permissions object1119 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1120 * @returns ```true``` if extrinsic success, otherwise ```false```1121 */1122 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1123 const result = await this.helper.executeExtrinsic(1124 signer,1125 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1126 true,1127 );11281129 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1130 }11311132 /**1133 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1134 *1135 * @param signer keyring of signer1136 * @param collectionId ID of collection1137 * @param permissions nesting permissions object1138 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1139 * @returns ```true``` if extrinsic success, otherwise ```false```1140 */1141 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1142 return await this.setPermissions(signer, collectionId, {nesting: permissions});1143 }11441145 /**1146 * Disables nesting for selected collection.1147 *1148 * @param signer keyring of signer1149 * @param collectionId ID of collection1150 * @example disableNesting(aliceKeyring, 10);1151 * @returns ```true``` if extrinsic success, otherwise ```false```1152 */1153 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1154 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1155 }11561157 /**1158 * Sets onchain properties to the collection.1159 *1160 * @param signer keyring of signer1161 * @param collectionId ID of collection1162 * @param properties array of property objects1163 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1164 * @returns ```true``` if extrinsic success, otherwise ```false```1165 */1166 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1167 const result = await this.helper.executeExtrinsic(1168 signer,1169 'api.tx.unique.setCollectionProperties', [collectionId, properties],1170 true,1171 );11721173 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1174 }11751176 /**1177 * Get collection properties.1178 *1179 * @param collectionId ID of collection1180 * @param propertyKeys optionally filter the returned properties to only these keys1181 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1182 * @returns array of key-value pairs1183 */1184 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1185 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1186 }11871188 async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1189 const api = this.helper.getApi();1190 const props = (await api.query.common.collectionProperties(collectionId)).toJSON();11911192 return (props! as any).consumedSpace;1193 }11941195 async getCollectionOptions(collectionId: number) {1196 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1197 }11981199 /**1200 * Deletes onchain properties from the collection.1201 *1202 * @param signer keyring of signer1203 * @param collectionId ID of collection1204 * @param propertyKeys array of property keys to delete1205 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1206 * @returns ```true``` if extrinsic success, otherwise ```false```1207 */1208 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1209 const result = await this.helper.executeExtrinsic(1210 signer,1211 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1212 true,1213 );12141215 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1216 }12171218 /**1219 * Changes the owner of the token.1220 *1221 * @param signer keyring of signer1222 * @param collectionId ID of collection1223 * @param tokenId ID of token1224 * @param addressObj address of a new owner1225 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1226 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1227 * @returns true if the token success, otherwise false1228 */1229 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1230 const result = await this.helper.executeExtrinsic(1231 signer,1232 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1233 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1234 );12351236 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1237 }12381239 /**1240 *1241 * Change ownership of a token(s) on behalf of the owner.1242 *1243 * @param signer keyring of signer1244 * @param collectionId ID of collection1245 * @param tokenId ID of token1246 * @param fromAddressObj address on behalf of which the token will be sent1247 * @param toAddressObj new token owner1248 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1249 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1250 * @returns true if the token success, otherwise false1251 */1252 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1253 const result = await this.helper.executeExtrinsic(1254 signer,1255 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1256 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1257 );1258 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1259 }12601261 /**1262 *1263 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1264 *1265 * @param signer keyring of signer1266 * @param collectionId ID of collection1267 * @param tokenId ID of token1268 * @param amount amount of tokens to be burned. For NFT must be set to 1n1269 * @example burnToken(aliceKeyring, 10, 5);1270 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1271 */1272 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount = 1n): Promise<boolean> {1273 const burnResult = await this.helper.executeExtrinsic(1274 signer,1275 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1276 true, // `Unable to burn token for ${label}`,1277 );1278 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1279 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1280 return burnedTokens.success;1281 }12821283 /**1284 * Destroys a concrete instance of NFT on behalf of the owner1285 *1286 * @param signer keyring of signer1287 * @param collectionId ID of collection1288 * @param tokenId ID of token1289 * @param fromAddressObj address on behalf of which the token will be burnt1290 * @param amount amount of tokens to be burned. For NFT must be set to 1n1291 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1292 * @returns ```true``` if extrinsic success, otherwise ```false```1293 */1294 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1295 const burnResult = await this.helper.executeExtrinsic(1296 signer,1297 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1298 true, // `Unable to burn token from for ${label}`,1299 );1300 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1301 return burnedTokens.success && burnedTokens.tokens.length > 0;1302 }13031304 /**1305 * Set, change, or remove approved address to transfer the ownership of the NFT.1306 *1307 * @param signer keyring of signer1308 * @param collectionId ID of collection1309 * @param tokenId ID of token1310 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1311 * @param amount amount of token to be approved. For NFT must be set to 1n1312 * @returns ```true``` if extrinsic success, otherwise ```false```1313 */1314 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1315 const approveResult = await this.helper.executeExtrinsic(1316 signer,1317 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1318 true, // `Unable to approve token for ${label}`,1319 );13201321 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1322 }13231324 /**1325 * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1326 *1327 * @param signer keyring of signer1328 * @param collectionId ID of collection1329 * @param tokenId ID of token1330 * @param fromAddressObj Signer's Ethereum address containing her tokens1331 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1332 * @param amount amount of token to be approved. For NFT must be set to 1n1333 * @returns ```true``` if extrinsic success, otherwise ```false```1334 */1335 async approveTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {1336 const approveResult = await this.helper.executeExtrinsic(1337 signer,1338 'api.tx.unique.approveFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1339 true, // `Unable to approve token for ${label}`,1340 );13411342 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1343 }13441345 /**1346 * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1347 *1348 * @param signer keyring of signer1349 * @param collectionId ID of collection1350 * @param tokenId ID of token1351 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1352 * @param amount amount of token to be approved. For NFT must be set to 1n1353 * @returns ```true``` if extrinsic success, otherwise ```false```1354 */1355 async approveTokenFromEth(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1356 const ethMirror = CrossAccountId.fromKeyring(signer).toEthereum();1357 return await this.approveTokenFrom(signer, collectionId, tokenId, ethMirror, toAddressObj, amount);1358 }13591360 /**1361 * Get the amount of token pieces approved to transfer or burn. Normally 0.1362 *1363 * @param collectionId ID of collection1364 * @param tokenId ID of token1365 * @param toAccountObj address which is approved to use token pieces1366 * @param fromAccountObj address which may have allowed the use of its owned tokens1367 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1368 * @returns number of approved to transfer pieces1369 */1370 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1371 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1372 }13731374 /**1375 * Get the last created token ID in a collection1376 *1377 * @param collectionId ID of collection1378 * @example getLastTokenId(10);1379 * @returns id of the last created token1380 */1381 async getLastTokenId(collectionId: number): Promise<number> {1382 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1383 }13841385 /**1386 * Check if token exists1387 *1388 * @param collectionId ID of collection1389 * @param tokenId ID of token1390 * @example doesTokenExist(10, 20);1391 * @returns true if the token exists, otherwise false1392 */1393 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1394 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1395 }1396}13971398class NFTnRFT extends CollectionGroup {1399 /**1400 * Get tokens owned by account1401 *1402 * @param collectionId ID of collection1403 * @param addressObj tokens owner1404 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1405 * @returns array of token ids owned by account1406 */1407 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1408 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1409 }14101411 /**1412 * Get token data1413 *1414 * @param collectionId ID of collection1415 * @param tokenId ID of token1416 * @param propertyKeys optionally filter the token properties to only these keys1417 * @param blockHashAt optionally query the data at some block with this hash1418 * @example getToken(10, 5);1419 * @returns human readable token data1420 */1421 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1422 properties: IProperty[];1423 owner: CrossAccountId;1424 normalizedOwner: CrossAccountId;1425 } | null> {1426 let tokenData;1427 if (typeof blockHashAt === 'undefined') {1428 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1429 }1430 else {1431 if (propertyKeys.length == 0) {1432 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1433 if (!collection) return null;1434 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1435 }1436 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1437 }1438 tokenData = tokenData.toHuman();1439 if (tokenData === null || tokenData.owner === null) return null;1440 const owner = {} as any;1441 for (const key of Object.keys(tokenData.owner)) {1442 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1443 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1444 : tokenData.owner[key];1445 }1446 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1447 return tokenData;1448 }14491450 /**1451 * Get token's owner1452 * @param collectionId ID of collection1453 * @param tokenId ID of token1454 * @param blockHashAt optionally query the data at the block with this hash1455 * @example getTokenOwner(10, 5);1456 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1457 */1458 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1459 let owner;1460 if (typeof blockHashAt === 'undefined') {1461 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1462 } else {1463 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1464 }1465 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1466 }14671468 /**1469 * Recursively find the address that owns the token1470 * @param collectionId ID of collection1471 * @param tokenId ID of token1472 * @param blockHashAt1473 * @example getTokenTopmostOwner(10, 5);1474 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1475 */1476 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1477 let owner;1478 if (typeof blockHashAt === 'undefined') {1479 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1480 } else {1481 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1482 }14831484 if (owner === null) return null;14851486 return owner.toHuman();1487 }14881489 /**1490 * Nest one token into another1491 * @param signer keyring of signer1492 * @param tokenObj token to be nested1493 * @param rootTokenObj token to be parent1494 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1495 * @returns ```true``` if extrinsic success, otherwise ```false```1496 */1497 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1498 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1499 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1500 if (!result) {1501 throw Error('Unable to nest token!');1502 }1503 return result;1504 }15051506 /**1507 * Remove token from nested state1508 * @param signer keyring of signer1509 * @param tokenObj token to unnest1510 * @param rootTokenObj parent of a token1511 * @param toAddressObj address of a new token owner1512 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1513 * @returns ```true``` if extrinsic success, otherwise ```false```1514 */1515 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1516 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1517 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1518 if (!result) {1519 throw Error('Unable to unnest token!');1520 }1521 return result;1522 }15231524 /**1525 * Set permissions to change token properties1526 *1527 * @param signer keyring of signer1528 * @param collectionId ID of collection1529 * @param permissions permissions to change a property by the collection admin or token owner1530 * @example setTokenPropertyPermissions(1531 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1532 * )1533 * @returns true if extrinsic success otherwise false1534 */1535 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1536 const result = await this.helper.executeExtrinsic(1537 signer,1538 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1539 true,1540 );15411542 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1543 }15441545 /**1546 * Get token property permissions.1547 *1548 * @param collectionId ID of collection1549 * @param propertyKeys optionally filter the returned property permissions to only these keys1550 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1551 * @returns array of key-permission pairs1552 */1553 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1554 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1555 }15561557 /**1558 * Set token properties1559 *1560 * @param signer keyring of signer1561 * @param collectionId ID of collection1562 * @param tokenId ID of token1563 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1564 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1565 * @returns ```true``` if extrinsic success, otherwise ```false```1566 */1567 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1568 const result = await this.helper.executeExtrinsic(1569 signer,1570 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1571 true,1572 );15731574 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1575 }15761577 /**1578 * Get properties, metadata assigned to a token.1579 *1580 * @param collectionId ID of collection1581 * @param tokenId ID of token1582 * @param propertyKeys optionally filter the returned properties to only these keys1583 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1584 * @returns array of key-value pairs1585 */1586 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1587 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1588 }15891590 /**1591 * Delete the provided properties of a token1592 * @param signer keyring of signer1593 * @param collectionId ID of collection1594 * @param tokenId ID of token1595 * @param propertyKeys property keys to be deleted1596 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1597 * @returns ```true``` if extrinsic success, otherwise ```false```1598 */1599 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1600 const result = await this.helper.executeExtrinsic(1601 signer,1602 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1603 true,1604 );16051606 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1607 }16081609 /**1610 * Mint new collection1611 *1612 * @param signer keyring of signer1613 * @param collectionOptions basic collection options and properties1614 * @param mode NFT or RFT type of a collection1615 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1616 * @returns object of the created collection1617 */1618 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1619 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1620 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1621 for (const key of ['name', 'description', 'tokenPrefix']) {1622 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);1623 }1624 const creationResult = await this.helper.executeExtrinsic(1625 signer,1626 'api.tx.unique.createCollectionEx', [collectionOptions],1627 true, // errorLabel,1628 );1629 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1630 }16311632 getCollectionObject(_collectionId: number): any {1633 return null;1634 }16351636 getTokenObject(_collectionId: number, _tokenId: number): any {1637 return null;1638 }16391640 /**1641 * Tells whether the given `owner` approves the `operator`.1642 * @param collectionId ID of collection1643 * @param owner owner address1644 * @param operator operator addrees1645 * @returns true if operator is enabled1646 */1647 async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1648 return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1649 }16501651 /** Sets or unsets the approval of a given operator.1652 * The `operator` is allowed to transfer all tokens of the `caller` on their behalf.1653 * @param operator Operator1654 * @param approved Should operator status be granted or revoked?1655 * @returns ```true``` if extrinsic success, otherwise ```false```1656 */1657 async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1658 const result = await this.helper.executeExtrinsic(1659 signer,1660 'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1661 true,1662 );1663 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1664 }1665}166616671668class NFTGroup extends NFTnRFT {1669 /**1670 * Get collection object1671 * @param collectionId ID of collection1672 * @example getCollectionObject(2);1673 * @returns instance of UniqueNFTCollection1674 */1675 getCollectionObject(collectionId: number): UniqueNFTCollection {1676 return new UniqueNFTCollection(collectionId, this.helper);1677 }16781679 /**1680 * Get token object1681 * @param collectionId ID of collection1682 * @param tokenId ID of token1683 * @example getTokenObject(10, 5);1684 * @returns instance of UniqueNFTToken1685 */1686 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1687 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1688 }16891690 /**1691 * Is token approved to transfer1692 * @param collectionId ID of collection1693 * @param tokenId ID of token1694 * @param toAccountObj address to be approved1695 * @returns ```true``` if extrinsic success, otherwise ```false```1696 */1697 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1698 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1699 }17001701 /**1702 * Changes the owner of the token.1703 *1704 * @param signer keyring of signer1705 * @param collectionId ID of collection1706 * @param tokenId ID of token1707 * @param addressObj address of a new owner1708 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1709 * @returns ```true``` if extrinsic success, otherwise ```false```1710 */1711 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1712 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1713 }17141715 /**1716 *1717 * Change ownership of a NFT on behalf of the owner.1718 *1719 * @param signer keyring of signer1720 * @param collectionId ID of collection1721 * @param tokenId ID of token1722 * @param fromAddressObj address on behalf of which the token will be sent1723 * @param toAddressObj new token owner1724 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1725 * @returns ```true``` if extrinsic success, otherwise ```false```1726 */1727 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1728 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1729 }17301731 /**1732 * Get tokens nested in the provided token1733 * @param collectionId ID of collection1734 * @param tokenId ID of token1735 * @param blockHashAt optionally query the data at the block with this hash1736 * @example getTokenChildren(10, 5);1737 * @returns tokens whose depth of nesting is <= 51738 */1739 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1740 let children;1741 if (typeof blockHashAt === 'undefined') {1742 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1743 } else {1744 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1745 }17461747 return children.toJSON().map((x: any) => ({collectionId: x.collection, tokenId: x.token}));1748 }17491750 /**1751 * Mint new collection1752 * @param signer keyring of signer1753 * @param collectionOptions Collection options1754 * @example1755 * mintCollection(aliceKeyring, {1756 * name: 'New',1757 * description: 'New collection',1758 * tokenPrefix: 'NEW',1759 * })1760 * @returns object of the created collection1761 */1762 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1763 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1764 }17651766 /**1767 * Mint new token1768 * @param signer keyring of signer1769 * @param data token data1770 * @returns created token object1771 */1772 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1773 const creationResult = await this.helper.executeExtrinsic(1774 signer,1775 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1776 NFT: {1777 properties: data.properties,1778 },1779 }],1780 true,1781 );1782 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1783 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1784 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1785 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1786 }17871788 /**1789 * Mint multiple NFT tokens1790 * @param signer keyring of signer1791 * @param collectionId ID of collection1792 * @param tokens array of tokens with owner and properties1793 * @example1794 * mintMultipleTokens(aliceKeyring, 10, [{1795 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1796 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1797 * },{1798 * owner: {Ethereum: "0x9F0583DbB855d..."},1799 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1800 * }]);1801 * @returns ```true``` if extrinsic success, otherwise ```false```1802 */1803 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: { owner: ICrossAccountId, properties?: IProperty[] }[]): Promise<UniqueNFToken[]> {1804 const creationResult = await this.helper.executeExtrinsic(1805 signer,1806 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1807 true,1808 );1809 const collection = this.getCollectionObject(collectionId);1810 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1811 }18121813 /**1814 * Mint multiple NFT tokens with one owner1815 * @param signer keyring of signer1816 * @param collectionId ID of collection1817 * @param owner tokens owner1818 * @param tokens array of tokens with owner and properties1819 * @example1820 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1821 * properties: [{1822 * key: "gender",1823 * value: "female",1824 * },{1825 * key: "age",1826 * value: "33",1827 * }],1828 * }]);1829 * @returns array of newly created tokens1830 */1831 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: { properties?: IProperty[] }[]): Promise<UniqueNFToken[]> {1832 const rawTokens = [];1833 for (const token of tokens) {1834 const raw = {NFT: {properties: token.properties}};1835 rawTokens.push(raw);1836 }1837 const creationResult = await this.helper.executeExtrinsic(1838 signer,1839 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1840 true,1841 );1842 const collection = this.getCollectionObject(collectionId);1843 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1844 }18451846 /**1847 * Set, change, or remove approved address to transfer the ownership of the NFT.1848 *1849 * @param signer keyring of signer1850 * @param collectionId ID of collection1851 * @param tokenId ID of token1852 * @param toAddressObj address to approve1853 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1854 * @returns ```true``` if extrinsic success, otherwise ```false```1855 */1856 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1857 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1858 }1859}186018611862class RFTGroup extends NFTnRFT {1863 /**1864 * Get collection object1865 * @param collectionId ID of collection1866 * @example getCollectionObject(2);1867 * @returns instance of UniqueRFTCollection1868 */1869 getCollectionObject(collectionId: number): UniqueRFTCollection {1870 return new UniqueRFTCollection(collectionId, this.helper);1871 }18721873 /**1874 * Get token object1875 * @param collectionId ID of collection1876 * @param tokenId ID of token1877 * @example getTokenObject(10, 5);1878 * @returns instance of UniqueNFTToken1879 */1880 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1881 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1882 }18831884 /**1885 * Get top 10 token owners with the largest number of pieces1886 * @param collectionId ID of collection1887 * @param tokenId ID of token1888 * @example getTokenTop10Owners(10, 5);1889 * @returns array of top 10 owners1890 */1891 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1892 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1893 }18941895 /**1896 * Get number of pieces owned by address1897 * @param collectionId ID of collection1898 * @param tokenId ID of token1899 * @param addressObj address token owner1900 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1901 * @returns number of pieces ownerd by address1902 */1903 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1904 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1905 }19061907 /**1908 * Transfer pieces of token to another address1909 * @param signer keyring of signer1910 * @param collectionId ID of collection1911 * @param tokenId ID of token1912 * @param addressObj address of a new owner1913 * @param amount number of pieces to be transfered1914 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1915 * @returns ```true``` if extrinsic success, otherwise ```false```1916 */1917 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1918 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1919 }19201921 /**1922 * Change ownership of some pieces of RFT on behalf of the owner.1923 * @param signer keyring of signer1924 * @param collectionId ID of collection1925 * @param tokenId ID of token1926 * @param fromAddressObj address on behalf of which the token will be sent1927 * @param toAddressObj new token owner1928 * @param amount number of pieces to be transfered1929 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1930 * @returns ```true``` if extrinsic success, otherwise ```false```1931 */1932 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1933 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1934 }19351936 /**1937 * Mint new collection1938 * @param signer keyring of signer1939 * @param collectionOptions Collection options1940 * @example1941 * mintCollection(aliceKeyring, {1942 * name: 'New',1943 * description: 'New collection',1944 * tokenPrefix: 'NEW',1945 * })1946 * @returns object of the created collection1947 */1948 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1949 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1950 }19511952 /**1953 * Mint new token1954 * @param signer keyring of signer1955 * @param data token data1956 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1957 * @returns created token object1958 */1959 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1960 const creationResult = await this.helper.executeExtrinsic(1961 signer,1962 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1963 ReFungible: {1964 pieces: data.pieces,1965 properties: data.properties,1966 },1967 }],1968 true,1969 );1970 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1971 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1972 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1973 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1974 }19751976 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: { owner: ICrossAccountId, pieces: bigint, properties?: IProperty[] }[]): Promise<UniqueRFToken[]> {1977 throw Error('Not implemented');1978 const creationResult = await this.helper.executeExtrinsic(1979 signer,1980 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1981 true, // `Unable to mint RFT tokens for ${label}`,1982 );1983 const collection = this.getCollectionObject(collectionId);1984 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1985 }19861987 /**1988 * Mint multiple RFT tokens with one owner1989 * @param signer keyring of signer1990 * @param collectionId ID of collection1991 * @param owner tokens owner1992 * @param tokens array of tokens with properties and pieces1993 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1994 * @returns array of newly created RFT tokens1995 */1996 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: { pieces: bigint, properties?: IProperty[] }[]): Promise<UniqueRFToken[]> {1997 const rawTokens = [];1998 for (const token of tokens) {1999 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};2000 rawTokens.push(raw);2001 }2002 const creationResult = await this.helper.executeExtrinsic(2003 signer,2004 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2005 true,2006 );2007 const collection = this.getCollectionObject(collectionId);2008 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));2009 }20102011 /**2012 * Destroys a concrete instance of RFT.2013 * @param signer keyring of signer2014 * @param collectionId ID of collection2015 * @param tokenId ID of token2016 * @param amount number of pieces to be burnt2017 * @example burnToken(aliceKeyring, 10, 5);2018 * @returns ```true``` if the extrinsic is successful, otherwise ```false```2019 */2020 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount = 1n): Promise<boolean> {2021 return await super.burnToken(signer, collectionId, tokenId, amount);2022 }20232024 /**2025 * Destroys a concrete instance of RFT on behalf of the owner.2026 * @param signer keyring of signer2027 * @param collectionId ID of collection2028 * @param tokenId ID of token2029 * @param fromAddressObj address on behalf of which the token will be burnt2030 * @param amount number of pieces to be burnt2031 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)2032 * @returns ```true``` if extrinsic success, otherwise ```false```2033 */2034 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {2035 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);2036 }20372038 /**2039 * Set, change, or remove approved address to transfer the ownership of the RFT.2040 *2041 * @param signer keyring of signer2042 * @param collectionId ID of collection2043 * @param tokenId ID of token2044 * @param toAddressObj address to approve2045 * @param amount number of pieces to be approved2046 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);2047 * @returns true if the token success, otherwise false2048 */2049 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {2050 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);2051 }20522053 /**2054 * Get total number of pieces2055 * @param collectionId ID of collection2056 * @param tokenId ID of token2057 * @example getTokenTotalPieces(10, 5);2058 * @returns number of pieces2059 */2060 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {2061 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();2062 }20632064 /**2065 * Change number of token pieces. Signer must be the owner of all token pieces.2066 * @param signer keyring of signer2067 * @param collectionId ID of collection2068 * @param tokenId ID of token2069 * @param amount new number of pieces2070 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);2071 * @returns true if the repartion was success, otherwise false2072 */2073 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {2074 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);2075 const repartitionResult = await this.helper.executeExtrinsic(2076 signer,2077 'api.tx.unique.repartition', [collectionId, tokenId, amount],2078 true,2079 );2080 if (currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');2081 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');2082 }2083}208420852086class FTGroup extends CollectionGroup {2087 /**2088 * Get collection object2089 * @param collectionId ID of collection2090 * @example getCollectionObject(2);2091 * @returns instance of UniqueFTCollection2092 */2093 getCollectionObject(collectionId: number): UniqueFTCollection {2094 return new UniqueFTCollection(collectionId, this.helper);2095 }20962097 /**2098 * Mint new fungible collection2099 * @param signer keyring of signer2100 * @param collectionOptions Collection options2101 * @param decimalPoints number of token decimals2102 * @example2103 * mintCollection(aliceKeyring, {2104 * name: 'New',2105 * description: 'New collection',2106 * tokenPrefix: 'NEW',2107 * }, 18)2108 * @returns newly created fungible collection2109 */2110 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {2111 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object2112 if (collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');2113 collectionOptions.mode = {fungible: decimalPoints};2114 for (const key of ['name', 'description', 'tokenPrefix']) {2115 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);2116 }2117 const creationResult = await this.helper.executeExtrinsic(2118 signer,2119 'api.tx.unique.createCollectionEx', [collectionOptions],2120 true,2121 );2122 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2123 }21242125 /**2126 * Mint tokens2127 * @param signer keyring of signer2128 * @param collectionId ID of collection2129 * @param owner address owner of new tokens2130 * @param amount amount of tokens to be meanted2131 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);2132 * @returns ```true``` if extrinsic success, otherwise ```false```2133 */2134 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2135 const creationResult = await this.helper.executeExtrinsic(2136 signer,2137 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2138 Fungible: {2139 value: amount,2140 },2141 }],2142 true, // `Unable to mint fungible tokens for ${label}`,2143 );2144 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2145 }21462147 /**2148 * Mint multiple Fungible tokens with one owner2149 * @param signer keyring of signer2150 * @param collectionId ID of collection2151 * @param owner tokens owner2152 * @param tokens array of tokens with properties and pieces2153 * @returns ```true``` if extrinsic success, otherwise ```false```2154 */2155 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: { value: bigint }[], owner: ICrossAccountId): Promise<boolean> {2156 const rawTokens = [];2157 for (const token of tokens) {2158 const raw = {Fungible: {Value: token.value}};2159 rawTokens.push(raw);2160 }2161 const creationResult = await this.helper.executeExtrinsic(2162 signer,2163 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2164 true,2165 );2166 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2167 }21682169 /**2170 * Get the top 10 owners with the largest balance for the Fungible collection2171 * @param collectionId ID of collection2172 * @example getTop10Owners(10);2173 * @returns array of ```ICrossAccountId```2174 */2175 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2176 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2177 }21782179 /**2180 * Get account balance2181 * @param collectionId ID of collection2182 * @param addressObj address of owner2183 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2184 * @returns amount of fungible tokens owned by address2185 */2186 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2187 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2188 }21892190 /**2191 * Transfer tokens to address2192 * @param signer keyring of signer2193 * @param collectionId ID of collection2194 * @param toAddressObj address recipient2195 * @param amount amount of tokens to be sent2196 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2197 * @returns ```true``` if extrinsic success, otherwise ```false```2198 */2199 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount = 1n) {2200 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2201 }22022203 /**2204 * Transfer some tokens on behalf of the owner.2205 * @param signer keyring of signer2206 * @param collectionId ID of collection2207 * @param fromAddressObj address on behalf of which tokens will be sent2208 * @param toAddressObj address where token to be sent2209 * @param amount number of tokens to be sent2210 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2211 * @returns ```true``` if extrinsic success, otherwise ```false```2212 */2213 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {2214 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2215 }22162217 /**2218 * Destroy some amount of tokens2219 * @param signer keyring of signer2220 * @param collectionId ID of collection2221 * @param amount amount of tokens to be destroyed2222 * @example burnTokens(aliceKeyring, 10, 1000n);2223 * @returns ```true``` if extrinsic success, otherwise ```false```2224 */2225 async burnTokens(signer: IKeyringPair, collectionId: number, amount = 1n): Promise<boolean> {2226 return await super.burnToken(signer, collectionId, 0, amount);2227 }22282229 /**2230 * Burn some tokens on behalf of the owner.2231 * @param signer keyring of signer2232 * @param collectionId ID of collection2233 * @param fromAddressObj address on behalf of which tokens will be burnt2234 * @param amount amount of tokens to be burnt2235 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2236 * @returns ```true``` if extrinsic success, otherwise ```false```2237 */2238 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {2239 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2240 }22412242 /**2243 * Get total collection supply2244 * @param collectionId2245 * @returns2246 */2247 async getTotalPieces(collectionId: number): Promise<bigint> {2248 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2249 }22502251 /**2252 * Set, change, or remove approved address to transfer tokens.2253 *2254 * @param signer keyring of signer2255 * @param collectionId ID of collection2256 * @param toAddressObj address to be approved2257 * @param amount amount of tokens to be approved2258 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2259 * @returns ```true``` if extrinsic success, otherwise ```false```2260 */2261 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount = 1n) {2262 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2263 }22642265 /**2266 * Get amount of fungible tokens approved to transfer2267 * @param collectionId ID of collection2268 * @param fromAddressObj owner of tokens2269 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2270 * @returns number of tokens approved for the transfer2271 */2272 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2273 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2274 }2275}227622772278class ChainGroup extends HelperGroup<ChainHelperBase> {2279 /**2280 * Get system properties of a chain2281 * @example getChainProperties();2282 * @returns ss58Format, token decimals, and token symbol2283 */2284 getChainProperties(): IChainProperties {2285 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2286 return {2287 ss58Format: properties.ss58Format.toJSON(),2288 tokenDecimals: properties.tokenDecimals.toJSON(),2289 tokenSymbol: properties.tokenSymbol.toJSON(),2290 };2291 }22922293 /**2294 * Get chain header2295 * @example getLatestBlockNumber();2296 * @returns the number of the last block2297 */2298 async getLatestBlockNumber(): Promise<number> {2299 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2300 }23012302 /**2303 * Get block hash by block number2304 * @param blockNumber number of block2305 * @example getBlockHashByNumber(12345);2306 * @returns hash of a block2307 */2308 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2309 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2310 if (blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2311 return blockHash;2312 }23132314 // TODO add docs2315 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2316 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2317 if (!blockHash) return null;2318 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2319 }23202321 /**2322 * Get latest relay block2323 * @returns {number} relay block2324 */2325 async getRelayBlockNumber(): Promise<bigint> {2326 const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2327 return BigInt(blockNumber);2328 }23292330 /**2331 * Get account nonce2332 * @param address substrate address2333 * @example getNonce("5GrwvaEF5zXb26Fz...");2334 * @returns number, account's nonce2335 */2336 async getNonce(address: TSubstrateAccount): Promise<number> {2337 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2338 }2339}23402341class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2342 /**2343 * Get substrate address balance2344 * @param address substrate address2345 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2346 * @returns amount of tokens on address2347 */2348 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2349 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2350 }23512352 /**2353 * Transfer tokens to substrate address2354 * @param signer keyring of signer2355 * @param address substrate address of a recipient2356 * @param amount amount of tokens to be transfered2357 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2358 * @returns ```true``` if extrinsic success, otherwise ```false```2359 */2360 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2361 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}`*/);23622363 let transfer = {from: null, to: null, amount: 0n} as any;2364 result.result.events.forEach(({event: {data, method, section}}) => {2365 if ((section === 'balances') && (method === 'Transfer')) {2366 transfer = {2367 from: this.helper.address.normalizeSubstrate(data[0]),2368 to: this.helper.address.normalizeSubstrate(data[1]),2369 amount: BigInt(data[2]),2370 };2371 }2372 });2373 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2374 && this.helper.address.normalizeSubstrate(address) === transfer.to2375 && BigInt(amount) === transfer.amount;2376 return isSuccess;2377 }23782379 /**2380 * Get full substrate balance including free, frozen, and reserved2381 * @param address substrate address2382 * @returns2383 */2384 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2385 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2386 return {free: accountInfo.free.toBigInt(), frozen: accountInfo.frozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2387 }23882389 /**2390 * Get total issuance2391 * @returns2392 */2393 async getTotalIssuance(): Promise<bigint> {2394 const total = (await this.helper.callRpc('api.query.balances.totalIssuance', []));2395 return total.toBigInt();2396 }23972398 async getLocked(address: TSubstrateAccount): Promise<{ id: string, amount: bigint, reason: string }[]> {2399 const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2400 return locks.map((lock: any) => ({id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons}));2401 }2402 async getFrozen(address: TSubstrateAccount): Promise<{ id: string, amount: bigint }[]> {2403 const locks = await this.helper.api!.query.balances.freezes(address);2404 return locks.map(lock => ({id: lock.id.toUtf8(), amount: lock.amount.toBigInt()}));2405 }2406}24072408class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2409 /**2410 * Get ethereum address balance2411 * @param address ethereum address2412 * @example getEthereum("0x9F0583DbB855d...")2413 * @returns amount of tokens on address2414 */2415 async getEthereum(address: TEthereumAccount): Promise<bigint> {2416 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2417 }24182419 /**2420 * Transfer tokens to address2421 * @param signer keyring of signer2422 * @param address Ethereum address of a recipient2423 * @param amount amount of tokens to be transfered2424 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2425 * @returns ```true``` if extrinsic success, otherwise ```false```2426 */2427 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2428 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);24292430 let transfer = {from: null, to: null, amount: 0n} as any;2431 result.result.events.forEach(({event: {data, method, section}}) => {2432 if ((section === 'balances') && (method === 'Transfer')) {2433 transfer = {2434 from: data[0].toString(),2435 to: data[1].toString(),2436 amount: BigInt(data[2]),2437 };2438 }2439 });2440 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2441 && address === transfer.to2442 && BigInt(amount) === transfer.amount;2443 return isSuccess;2444 }2445}24462447class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2448 subBalanceGroup: SubstrateBalanceGroup<T>;2449 ethBalanceGroup: EthereumBalanceGroup<T>;24502451 constructor(helper: T) {2452 super(helper);2453 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2454 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2455 }24562457 getCollectionCreationPrice(): bigint {2458 return 2n * this.getOneTokenNominal();2459 }2460 /**2461 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2462 * @example getOneTokenNominal()2463 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2464 */2465 getOneTokenNominal(): bigint {2466 const chainProperties = this.helper.chain.getChainProperties();2467 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2468 }24692470 /**2471 * Get substrate address balance2472 * @param address substrate address2473 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2474 * @returns amount of tokens on address2475 */2476 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2477 return this.subBalanceGroup.getSubstrate(address);2478 }24792480 /**2481 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2482 * @param address substrate address2483 * @returns2484 */2485 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2486 return this.subBalanceGroup.getSubstrateFull(address);2487 }24882489 /**2490 * Get total issuance2491 * @returns2492 */2493 getTotalIssuance(): Promise<bigint> {2494 return this.subBalanceGroup.getTotalIssuance();2495 }24962497 /**2498 * Get locked balances2499 * @param address substrate address2500 * @returns locked balances with reason via api.query.balances.locks2501 * @deprecated all the methods should switch to getFrozen2502 */2503 getLocked(address: TSubstrateAccount) {2504 return this.subBalanceGroup.getLocked(address);2505 }25062507 /**2508 * Get frozen balances2509 * @param address substrate address2510 * @returns frozen balances with id via api.query.balances.freezes2511 */2512 getFrozen(address: TSubstrateAccount) {2513 return this.subBalanceGroup.getFrozen(address);2514 }25152516 /**2517 * Get ethereum address balance2518 * @param address ethereum address2519 * @example getEthereum("0x9F0583DbB855d...")2520 * @returns amount of tokens on address2521 */2522 getEthereum(address: TEthereumAccount): Promise<bigint> {2523 return this.ethBalanceGroup.getEthereum(address);2524 }25252526 async setBalanceSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint, reservedAmount = 0n) {2527 await this.helper.executeExtrinsic(signer, 'api.tx.balances.setBalance', [address, amount, reservedAmount], true);2528 }25292530 /**2531 * Transfer tokens to substrate address2532 * @param signer keyring of signer2533 * @param address substrate address of a recipient2534 * @param amount amount of tokens to be transfered2535 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2536 * @returns ```true``` if extrinsic success, otherwise ```false```2537 */2538 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2539 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2540 }25412542 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2543 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);25442545 let transfer = {from: null, to: null, amount: 0n} as any;2546 result.result.events.forEach(({event: {data, method, section}}) => {2547 if ((section === 'balances') && (method === 'Transfer')) {2548 transfer = {2549 from: this.helper.address.normalizeSubstrate(data[0]),2550 to: this.helper.address.normalizeSubstrate(data[1]),2551 amount: BigInt(data[2]),2552 };2553 }2554 });2555 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2556 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2557 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2558 return isSuccess;2559 }25602561 /**2562 * Transfer tokens with the unlock period2563 * @param signer signers Keyring2564 * @param address Substrate address of recipient2565 * @param schedule Schedule params2566 * @example vestedTransfer(signer, recepient.address, 20000, 100, 10, 50 * nominal); // total amount of vested tokens will be 100 * 50 = 50002567 */2568 async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: { start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint }): Promise<void> {2569 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2570 const event = result.result.events2571 .find(e => e.event.section === 'vesting' &&2572 e.event.method === 'VestingScheduleAdded' &&2573 e.event.data[0].toHuman() === signer.address);2574 if (!event) throw Error('Cannot find transfer in events');2575 }25762577 /**2578 * Get schedule for recepient of vested transfer2579 * @param address Substrate address of recipient2580 * @returns2581 */2582 async getVestingSchedules(address: TSubstrateAccount): Promise<{ start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint }[]> {2583 const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2584 return schedule.map((schedule: any) => ({2585 start: BigInt(schedule.start),2586 period: BigInt(schedule.period),2587 periodCount: BigInt(schedule.periodCount),2588 perPeriod: BigInt(schedule.perPeriod),2589 }));2590 }25912592 /**2593 * Claim vested tokens2594 * @param signer signers Keyring2595 */2596 async claim(signer: TSigner) {2597 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2598 const event = result.result.events2599 .find(e => e.event.section === 'vesting' &&2600 e.event.method === 'Claimed' &&2601 e.event.data[0].toHuman() === signer.address);2602 if (!event) throw Error('Cannot find claim in events');2603 }2604}26052606class AddressGroup extends HelperGroup<ChainHelperBase> {2607 /**2608 * Normalizes the address to the specified ss58 format, by default ```42```.2609 * @param address substrate address2610 * @param ss58Format format for address conversion, by default ```42```2611 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2612 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2613 */2614 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2615 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2616 }26172618 /**2619 * Get address in the connected chain format2620 * @param address substrate address2621 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2622 * @returns address in chain format2623 */2624 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2625 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2626 }26272628 /**2629 * Get substrate mirror of an ethereum address2630 * @param ethAddress ethereum address2631 * @param toChainFormat false for normalized account2632 * @example ethToSubstrate('0x9F0583DbB855d...')2633 * @returns substrate mirror of a provided ethereum address2634 */2635 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat = false): TSubstrateAccount {2636 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2637 }26382639 /**2640 * Get ethereum mirror of a substrate address2641 * @param subAddress substrate account2642 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2643 * @returns ethereum mirror of a provided substrate address2644 */2645 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2646 return CrossAccountId.translateSubToEth(subAddress);2647 }26482649 /**2650 * Encode key to substrate address2651 * @param key key for encoding address2652 * @param ss58Format prefix for encoding to the address of the corresponding network2653 * @returns encoded substrate address2654 */2655 encodeSubstrateAddress(key: Uint8Array | string | bigint, ss58Format = 42): string {2656 const u8a: Uint8Array = typeof key === 'string'2657 ? hexToU8a(key)2658 : typeof key === 'bigint'2659 ? hexToU8a(key.toString(16))2660 : key;26612662 if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2663 throw new Error(`ss58Format is not valid, received ${typeofss58Format} "${ss58Format}"`);2664 }26652666 const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2667 if (!allowedDecodedLengths.includes(u8a.length)) {2668 throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2669 }26702671 const u8aPrefix = ss58Format < 642672 ? new Uint8Array([ss58Format])2673 : new Uint8Array([2674 ((ss58Format & 0xfc) >> 2) | 0x40,2675 (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2676 ]);26772678 const input = u8aConcat(u8aPrefix, u8a);26792680 return base58Encode(u8aConcat(2681 input,2682 blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2683 ));2684 }26852686 /**2687 * Restore substrate address from bigint representation2688 * @param number decimal representation of substrate address2689 * @returns substrate address2690 */2691 restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2692 if (this.helper.api === null) {2693 throw 'Not connected';2694 }2695 const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2696 if (res === undefined || res === null) {2697 throw 'Restore address error';2698 }2699 return res.toString();2700 }27012702 /**2703 * Convert etherium cross account id to substrate cross account id2704 * @param ethCrossAccount etherium cross account2705 * @returns substrate cross account id2706 */2707 convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2708 if (ethCrossAccount.sub === '0') {2709 return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2710 }27112712 const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2713 return {Substrate: ss58};2714 }27152716 paraSiblingSovereignAccount(paraid: number) {2717 // We are getting a *sibling* parachain sovereign account,2718 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2719 const siblingPrefix = '0x7369626c';27202721 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2722 const suffix = '000000000000000000000000000000000000000000000000';27232724 return siblingPrefix + encodedParaId + suffix;2725 }2726}27272728class StakingGroup extends HelperGroup<UniqueHelper> {2729 /**2730 * Stake tokens for App Promotion2731 * @param signer keyring of signer2732 * @param amountToStake amount of tokens to stake2733 * @param label extra label for log2734 * @returns2735 */2736 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2737 if (typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2738 const _stakeResult = await this.helper.executeExtrinsic(2739 signer, 'api.tx.appPromotion.stake',2740 [amountToStake], true,2741 );2742 // TODO extract info from stakeResult2743 return true;2744 }27452746 /**2747 * Unstake all staked tokens2748 * @param signer keyring of signer2749 * @param amountToUnstake amount of tokens to unstake2750 * @param label extra label for log2751 * @returns block hash where unstake happened2752 */2753 async unstakeAll(signer: TSigner, label?: string): Promise<string> {2754 if (typeof label === 'undefined') label = `${signer.address}`;2755 const unstakeResult = await this.helper.executeExtrinsic(2756 signer, 'api.tx.appPromotion.unstakeAll',2757 [], true,2758 );2759 return unstakeResult.blockHash;2760 }27612762 /**2763 * Unstake the part of a staked tokens2764 * @param signer keyring of signer2765 * @param amount amount of tokens to unstake2766 * @param label extra label for log2767 * @returns block hash where unstake happened2768 */2769 async unstakePartial(signer: TSigner, amount: bigint, label?: string): Promise<string> {2770 if (typeof label === 'undefined') label = `${signer.address}`;2771 const unstakeResult = await this.helper.executeExtrinsic(2772 signer, 'api.tx.appPromotion.unstakePartial',2773 [amount], true,2774 );2775 return unstakeResult.blockHash;2776 }27772778 /**2779 * Get total number of active stakes2780 * @param address substrate address2781 * @returns {number}2782 */2783 async getStakesNumber(address: ICrossAccountId): Promise<number> {2784 if ('Ethereum' in address) throw Error('only substrate address');2785 return (await this.helper.callRpc('api.query.appPromotion.stakesPerAccount', [address.Substrate])).toNumber();2786 }27872788 /**2789 * Get total staked amount for address2790 * @param address substrate or ethereum address2791 * @returns total staked amount2792 */2793 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2794 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2795 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2796 }27972798 /**2799 * Get total staked per block2800 * @param address substrate or ethereum address2801 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2802 */2803 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2804 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2805 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => ({2806 block: block.toBigInt(),2807 amount: amount.toBigInt(),2808 }));2809 }28102811 /**2812 * Get total pending unstake amount for address2813 * @param address substrate or ethereum address2814 * @returns total pending unstake amount2815 */2816 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2817 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2818 }28192820 /**2821 * Get pending unstake amount per block for address2822 * @param address substrate or ethereum address2823 * @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 block2824 */2825 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2826 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2827 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => ({2828 block: block.toBigInt(),2829 amount: amount.toBigInt(),2830 }));2831 return result;2832 }2833}28342835class SchedulerGroup extends HelperGroup<UniqueHelper> {2836 constructor(helper: UniqueHelper) {2837 super(helper);2838 }28392840 cancelScheduled(signer: TSigner, scheduledId: string) {2841 return this.helper.executeExtrinsic(2842 signer,2843 'api.tx.scheduler.cancelNamed',2844 [scheduledId],2845 true,2846 );2847 }28482849 changePriority(signer: TSigner, scheduledId: string, priority: number) {2850 return this.helper.executeExtrinsic(2851 signer,2852 'api.tx.scheduler.changeNamedPriority',2853 [scheduledId, priority],2854 true,2855 );2856 }28572858 scheduleAt<T extends UniqueHelper>(2859 executionBlockNumber: number,2860 options: ISchedulerOptions = {},2861 ) {2862 return this.schedule<T>('schedule', executionBlockNumber, options);2863 }28642865 scheduleAfter<T extends UniqueHelper>(2866 blocksBeforeExecution: number,2867 options: ISchedulerOptions = {},2868 ) {2869 return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2870 }28712872 schedule<T extends UniqueHelper>(2873 scheduleFn: 'schedule' | 'scheduleAfter',2874 blocksNum: number,2875 options: ISchedulerOptions = {},2876 ) {2877 // eslint-disable-next-line @typescript-eslint/naming-convention2878 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2879 return this.helper.clone(ScheduledHelperType, {2880 scheduleFn,2881 blocksNum,2882 options,2883 }) as T;2884 }2885}28862887class CollatorSelectionGroup extends HelperGroup<UniqueHelper> {2888 //todo:collator documentation2889 addInvulnerable(signer: TSigner, address: string) {2890 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.addInvulnerable', [address]);2891 }28922893 removeInvulnerable(signer: TSigner, address: string) {2894 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.removeInvulnerable', [address]);2895 }28962897 async getInvulnerables(): Promise<string[]> {2898 return (await this.helper.callRpc('api.query.collatorSelection.invulnerables')).map((x: any) => x.toHuman());2899 }29002901 /** and also total max invulnerables */2902 maxCollators(): number {2903 return (this.helper.getApi().consts.configuration.defaultCollatorSelectionMaxCollators.toJSON() as number);2904 }29052906 async getDesiredCollators(): Promise<number> {2907 return (await this.helper.callRpc('api.query.configuration.collatorSelectionDesiredCollatorsOverride')).toNumber();2908 }29092910 setLicenseBond(signer: TSigner, amount: bigint) {2911 return this.helper.executeExtrinsic(signer, 'api.tx.configuration.setCollatorSelectionLicenseBond', [amount]);2912 }29132914 async getLicenseBond(): Promise<bigint> {2915 return (await this.helper.callRpc('api.query.configuration.collatorSelectionLicenseBondOverride')).toBigInt();2916 }29172918 obtainLicense(signer: TSigner) {2919 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.getLicense', []);2920 }29212922 releaseLicense(signer: TSigner) {2923 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.releaseLicense', []);2924 }29252926 forceReleaseLicense(signer: TSigner, released: string) {2927 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.forceReleaseLicense', [released]);2928 }29292930 async hasLicense(address: string): Promise<bigint> {2931 return (await this.helper.callRpc('api.query.collatorSelection.licenseDepositOf', [address])).toBigInt();2932 }29332934 onboard(signer: TSigner) {2935 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.onboard', []);2936 }29372938 offboard(signer: TSigner) {2939 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.offboard', []);2940 }29412942 async getCandidates(): Promise<string[]> {2943 return (await this.helper.callRpc('api.query.collatorSelection.candidates')).map((x: any) => x.toHuman());2944 }2945}29462947class PreimageGroup extends HelperGroup<UniqueHelper> {2948 async getPreimageInfo(h256: string) {2949 return (await this.helper.callRpc('api.query.preimage.statusFor', [h256])).toJSON();2950 }29512952 /**2953 * Create a preimage with a hex or a byte array.2954 * @param signer keyring of the signer.2955 * @param bytes preimage encoded in hex or a byte array, e.g. an extrinsic call.2956 * @example await notePreimage(preimageMaker,2957 * helper.constructApiCall('api.tx.identity.forceInsertIdentities', [identitiesToAdd]).method.toHex()2958 * );2959 * @returns promise of extrinsic execution.2960 */2961 notePreimage(signer: TSigner, bytes: string | Uint8Array) {2962 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.notePreimage', [bytes]);2963 }29642965 /**2966 * Delete an existing preimage and return the deposit.2967 * @param signer keyring of the signer - either the owner or the preimage manager (sudo).2968 * @param h256 hash of the preimage.2969 * @returns promise of extrinsic execution.2970 */2971 unnotePreimage(signer: TSigner, h256: string) {2972 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unnotePreimage', [h256]);2973 }29742975 /**2976 * Request a preimage be uploaded to the chain without paying any fees or deposits.2977 * @param signer keyring of the signer - either the owner or the preimage manager (sudo).2978 * @param h256 hash of the preimage.2979 * @returns promise of extrinsic execution.2980 */2981 requestPreimage(signer: TSigner, h256: string) {2982 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.requestPreimage', [h256]);2983 }29842985 /**2986 * Clear a previously made request for a preimage.2987 * @param signer keyring of the signer - either the owner or the preimage manager (sudo).2988 * @param h256 hash of the preimage.2989 * @returns promise of extrinsic execution.2990 */2991 unrequestPreimage(signer: TSigner, h256: string) {2992 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unrequestPreimage', [h256]);2993 }2994}29952996class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2997 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2998 await this.helper.executeExtrinsic(2999 signer,3000 'api.tx.foreignAssets.registerForeignAsset',3001 [ownerAddress, location, metadata],3002 true,3003 );3004 }30053006 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {3007 await this.helper.executeExtrinsic(3008 signer,3009 'api.tx.foreignAssets.updateForeignAsset',3010 [foreignAssetId, location, metadata],3011 true,3012 );3013 }3014}30153016class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {3017 palletName: string;30183019 constructor(helper: T, palletName: string) {3020 super(helper);30213022 this.palletName = palletName;3023 }30243025 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {3026 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);3027 }30283029 async setSafeXcmVersion(signer: TSigner, version: number) {3030 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.forceDefaultXcmVersion`, [version], true);3031 }30323033 async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {3034 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);3035 }30363037 async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint, xcmVersion = 3) {3038 const destinationContent = {3039 parents: 0,3040 interior: {3041 X1: {3042 Parachain: destinationParaId,3043 },3044 },3045 };30463047 const beneficiaryContent = {3048 parents: 0,3049 interior: {3050 X1: {3051 AccountId32: {3052 network: 'Any',3053 id: targetAccount,3054 },3055 },3056 },3057 };30583059 const assetsContent = [3060 {3061 id: {3062 Concrete: {3063 parents: 0,3064 interior: 'Here',3065 },3066 },3067 fun: {3068 Fungible: amount,3069 },3070 },3071 ];30723073 let destination;3074 let beneficiary;3075 let assets;30763077 if (xcmVersion == 2) {3078 destination = {V1: destinationContent};3079 beneficiary = {V1: beneficiaryContent};3080 assets = {V1: assetsContent};30813082 } else if (xcmVersion == 3) {3083 destination = {V2: destinationContent};3084 beneficiary = {V2: beneficiaryContent};3085 assets = {V2: assetsContent};30863087 } else {3088 throw Error('Unknown XCM version: ' + xcmVersion);3089 }30903091 const feeAssetItem = 0;30923093 await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);3094 }30953096 async send(signer: IKeyringPair, destination: any, message: any) {3097 await this.helper.executeExtrinsic(3098 signer,3099 `api.tx.${this.palletName}.send`,3100 [3101 destination,3102 message,3103 ],3104 true,3105 );3106 }3107}31083109class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {3110 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {3111 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);3112 }31133114 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {3115 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);3116 }31173118 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {3119 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);3120 }3121}31223123class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {3124 async accounts(address: string, currencyId: any) {3125 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;3126 return BigInt(free);3127 }3128}31293130class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {3131 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {3132 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);3133 }31343135 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {3136 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);3137 }31383139 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {3140 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);3141 }31423143 async account(assetId: string | number, address: string) {3144 const accountAsset = (3145 await this.helper.callRpc('api.query.assets.account', [assetId, address])3146 ).toJSON()! as any;31473148 if (accountAsset !== null) {3149 return BigInt(accountAsset['balance']);3150 } else {3151 return null;3152 }3153 }3154}31553156class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {3157 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {3158 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);3159 }3160}31613162class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {3163 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {3164 const apiPrefix = 'api.tx.assetManager.';31653166 const registerTx = this.helper.constructApiCall(3167 apiPrefix + 'registerForeignAsset',3168 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],3169 );31703171 const setUnitsTx = this.helper.constructApiCall(3172 apiPrefix + 'setAssetUnitsPerSecond',3173 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],3174 );31753176 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);3177 const encodedProposal = batchCall?.method.toHex() || '';3178 return encodedProposal;3179 }31803181 async assetTypeId(location: any) {3182 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);3183 }3184}31853186class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {3187 notePreimagePallet: string;31883189 constructor(helper: MoonbeamHelper, options: { [key: string]: any } = {}) {3190 super(helper);3191 this.notePreimagePallet = options.notePreimagePallet;3192 }31933194 async notePreimage(signer: TSigner, encodedProposal: string) {3195 await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);3196 }31973198 externalProposeMajority(proposal: any) {3199 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);3200 }32013202 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {3203 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);3204 }32053206 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {3207 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);3208 }3209}32103211class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {3212 collective: string;32133214 constructor(helper: MoonbeamHelper, collective: string) {3215 super(helper);32163217 this.collective = collective;3218 }32193220 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {3221 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);3222 }32233224 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {3225 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);3226 }32273228 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {3229 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);3230 }32313232 async proposalCount() {3233 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));3234 }3235}32363237export type ChainHelperBaseConstructor = new (...args: any[]) => ChainHelperBase;3238export type UniqueHelperConstructor = new (...args: any[]) => UniqueHelper;32393240export class UniqueHelper extends ChainHelperBase {3241 balance: BalanceGroup<UniqueHelper>;3242 collection: CollectionGroup;3243 nft: NFTGroup;3244 rft: RFTGroup;3245 ft: FTGroup;3246 staking: StakingGroup;3247 scheduler: SchedulerGroup;3248 collatorSelection: CollatorSelectionGroup;3249 preimage: PreimageGroup;3250 foreignAssets: ForeignAssetsGroup;3251 xcm: XcmGroup<UniqueHelper>;3252 xTokens: XTokensGroup<UniqueHelper>;3253 tokens: TokensGroup<UniqueHelper>;32543255 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3256 super(logger, options.helperBase ?? UniqueHelper);32573258 this.balance = new BalanceGroup(this);3259 this.collection = new CollectionGroup(this);3260 this.nft = new NFTGroup(this);3261 this.rft = new RFTGroup(this);3262 this.ft = new FTGroup(this);3263 this.staking = new StakingGroup(this);3264 this.scheduler = new SchedulerGroup(this);3265 this.collatorSelection = new CollatorSelectionGroup(this);3266 this.preimage = new PreimageGroup(this);3267 this.foreignAssets = new ForeignAssetsGroup(this);3268 this.xcm = new XcmGroup(this, 'polkadotXcm');3269 this.xTokens = new XTokensGroup(this);3270 this.tokens = new TokensGroup(this);3271 }32723273 getSudo<T extends UniqueHelper>() {3274 // eslint-disable-next-line @typescript-eslint/naming-convention3275 const SudoHelperType = SudoHelper(this.helperBase);3276 return this.clone(SudoHelperType) as T;3277 }3278}32793280export class XcmChainHelper extends ChainHelperBase {3281 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {3282 const wsProvider = new WsProvider(wsEndpoint);3283 this.api = new ApiPromise({3284 provider: wsProvider,3285 });3286 await this.api.isReadyOrError;3287 this.network = await UniqueHelper.detectNetwork(this.api);3288 }3289}32903291export class RelayHelper extends XcmChainHelper {3292 balance: SubstrateBalanceGroup<RelayHelper>;3293 xcm: XcmGroup<RelayHelper>;32943295 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3296 super(logger, options.helperBase ?? RelayHelper);32973298 this.balance = new SubstrateBalanceGroup(this);3299 this.xcm = new XcmGroup(this, 'xcmPallet');3300 }3301}33023303export class WestmintHelper extends XcmChainHelper {3304 balance: SubstrateBalanceGroup<WestmintHelper>;3305 xcm: XcmGroup<WestmintHelper>;3306 assets: AssetsGroup<WestmintHelper>;3307 xTokens: XTokensGroup<WestmintHelper>;33083309 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3310 super(logger, options.helperBase ?? WestmintHelper);33113312 this.balance = new SubstrateBalanceGroup(this);3313 this.xcm = new XcmGroup(this, 'polkadotXcm');3314 this.assets = new AssetsGroup(this);3315 this.xTokens = new XTokensGroup(this);3316 }3317}33183319export class MoonbeamHelper extends XcmChainHelper {3320 balance: EthereumBalanceGroup<MoonbeamHelper>;3321 assetManager: MoonbeamAssetManagerGroup;3322 assets: AssetsGroup<MoonbeamHelper>;3323 xTokens: XTokensGroup<MoonbeamHelper>;3324 democracy: MoonbeamDemocracyGroup;3325 collective: {3326 council: MoonbeamCollectiveGroup,3327 techCommittee: MoonbeamCollectiveGroup,3328 };33293330 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3331 super(logger, options.helperBase ?? MoonbeamHelper);33323333 this.balance = new EthereumBalanceGroup(this);3334 this.assetManager = new MoonbeamAssetManagerGroup(this);3335 this.assets = new AssetsGroup(this);3336 this.xTokens = new XTokensGroup(this);3337 this.democracy = new MoonbeamDemocracyGroup(this, options);3338 this.collective = {3339 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),3340 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),3341 };3342 }3343}33443345export class AstarHelper extends XcmChainHelper {3346 balance: SubstrateBalanceGroup<AstarHelper>;3347 assets: AssetsGroup<AstarHelper>;3348 xcm: XcmGroup<AstarHelper>;33493350 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3351 super(logger, options.helperBase ?? AstarHelper);33523353 this.balance = new SubstrateBalanceGroup(this);3354 this.assets = new AssetsGroup(this);3355 this.xcm = new XcmGroup(this, 'polkadotXcm');3356 }33573358 getSudo<T extends UniqueHelper>() {3359 // eslint-disable-next-line @typescript-eslint/naming-convention3360 const SudoHelperType = SudoHelper(this.helperBase);3361 return this.clone(SudoHelperType) as T;3362 }3363}33643365export class AcalaHelper extends XcmChainHelper {3366 balance: SubstrateBalanceGroup<AcalaHelper>;3367 assetRegistry: AcalaAssetRegistryGroup;3368 xTokens: XTokensGroup<AcalaHelper>;3369 tokens: TokensGroup<AcalaHelper>;3370 xcm: XcmGroup<AcalaHelper>;33713372 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3373 super(logger, options.helperBase ?? AcalaHelper);33743375 this.balance = new SubstrateBalanceGroup(this);3376 this.assetRegistry = new AcalaAssetRegistryGroup(this);3377 this.xTokens = new XTokensGroup(this);3378 this.tokens = new TokensGroup(this);3379 this.xcm = new XcmGroup(this, 'polkadotXcm');3380 }33813382 getSudo<T extends AcalaHelper>() {3383 // eslint-disable-next-line @typescript-eslint/naming-convention3384 const SudoHelperType = SudoHelper(this.helperBase);3385 return this.clone(SudoHelperType) as T;3386 }3387}33883389// eslint-disable-next-line @typescript-eslint/naming-convention3390function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3391 return class extends Base {3392 scheduleFn: 'schedule' | 'scheduleAfter';3393 blocksNum: number;3394 options: ISchedulerOptions;33953396 constructor(...args: any[]) {3397 const logger = args[0] as ILogger;3398 const options = args[1] as {3399 scheduleFn: 'schedule' | 'scheduleAfter',3400 blocksNum: number,3401 options: ISchedulerOptions3402 };34033404 super(logger);34053406 this.scheduleFn = options.scheduleFn;3407 this.blocksNum = options.blocksNum;3408 this.options = options.options;3409 }34103411 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3412 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);34133414 const mandatorySchedArgs = [3415 this.blocksNum,3416 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3417 this.options.priority ?? null,3418 scheduledTx,3419 ];34203421 let schedArgs;3422 let scheduleFn;34233424 if (this.options.scheduledId) {3425 schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];34263427 if (this.scheduleFn == 'schedule') {3428 scheduleFn = 'scheduleNamed';3429 } else if (this.scheduleFn == 'scheduleAfter') {3430 scheduleFn = 'scheduleNamedAfter';3431 }3432 } else {3433 schedArgs = mandatorySchedArgs;3434 scheduleFn = this.scheduleFn;3435 }34363437 const extrinsic = 'api.tx.scheduler.' + scheduleFn;34383439 return super.executeExtrinsic(3440 sender,3441 extrinsic as any,3442 schedArgs,3443 expectSuccess,3444 );3445 }3446 };3447}34483449// eslint-disable-next-line @typescript-eslint/naming-convention3450function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3451 return class extends Base {3452 constructor(...args: any[]) {3453 super(...args);3454 }34553456 async executeExtrinsic(3457 sender: IKeyringPair,3458 extrinsic: string,3459 params: any[],3460 expectSuccess?: boolean,3461 options: Partial<SignerOptions> | null = null,3462 ): Promise<ITransactionResult> {3463 const call = this.constructApiCall(extrinsic, params);3464 const result = await super.executeExtrinsic(3465 sender,3466 'api.tx.sudo.sudo',3467 [call],3468 expectSuccess,3469 options,3470 );34713472 if (result.status === 'Fail') return result;34733474 const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;3475 if (data.isErr) {3476 if (data.asErr.isModule) {3477 const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;3478 const metaError = super.getApi()?.registry.findMetaError(error);3479 throw new Error(`${metaError.section}.${metaError.name}`);3480 } else if (data.asErr.isToken) {3481 throw new Error(`Token: ${data.asErr.asToken}`);3482 }3483 }3484 return result;3485 }3486 };3487}34883489export class UniqueBaseCollection {3490 helper: UniqueHelper;3491 collectionId: number;34923493 constructor(collectionId: number, uniqueHelper: UniqueHelper) {3494 this.collectionId = collectionId;3495 this.helper = uniqueHelper;3496 }34973498 async getData() {3499 return await this.helper.collection.getData(this.collectionId);3500 }35013502 async getLastTokenId() {3503 return await this.helper.collection.getLastTokenId(this.collectionId);3504 }35053506 async doesTokenExist(tokenId: number) {3507 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3508 }35093510 async getAdmins() {3511 return await this.helper.collection.getAdmins(this.collectionId);3512 }35133514 async getAllowList() {3515 return await this.helper.collection.getAllowList(this.collectionId);3516 }35173518 async getEffectiveLimits() {3519 return await this.helper.collection.getEffectiveLimits(this.collectionId);3520 }35213522 async getProperties(propertyKeys?: string[] | null) {3523 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3524 }35253526 async getPropertiesConsumedSpace() {3527 return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3528 }35293530 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3531 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3532 }35333534 async getOptions() {3535 return await this.helper.collection.getCollectionOptions(this.collectionId);3536 }35373538 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3539 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3540 }35413542 async confirmSponsorship(signer: TSigner) {3543 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3544 }35453546 async removeSponsor(signer: TSigner) {3547 return await this.helper.collection.removeSponsor(signer, this.collectionId);3548 }35493550 async setLimits(signer: TSigner, limits: ICollectionLimits) {3551 return await this.helper.collection.setLimits(signer, this.collectionId, limits);3552 }35533554 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3555 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3556 }35573558 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3559 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3560 }35613562 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3563 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3564 }35653566 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3567 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3568 }35693570 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3571 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3572 }35733574 async setProperties(signer: TSigner, properties: IProperty[]) {3575 return await this.helper.collection.setProperties(signer, this.collectionId, properties);3576 }35773578 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3579 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3580 }35813582 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3583 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3584 }35853586 async enableNesting(signer: TSigner, permissions: INestingPermissions) {3587 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3588 }35893590 async disableNesting(signer: TSigner) {3591 return await this.helper.collection.disableNesting(signer, this.collectionId);3592 }35933594 async burn(signer: TSigner) {3595 return await this.helper.collection.burn(signer, this.collectionId);3596 }35973598 scheduleAt<T extends UniqueHelper>(3599 executionBlockNumber: number,3600 options: ISchedulerOptions = {},3601 ) {3602 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3603 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3604 }36053606 scheduleAfter<T extends UniqueHelper>(3607 blocksBeforeExecution: number,3608 options: ISchedulerOptions = {},3609 ) {3610 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3611 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3612 }36133614 getSudo<T extends UniqueHelper>() {3615 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3616 }3617}361836193620export class UniqueNFTCollection extends UniqueBaseCollection {3621 getTokenObject(tokenId: number) {3622 return new UniqueNFToken(tokenId, this);3623 }36243625 async getTokensByAddress(addressObj: ICrossAccountId) {3626 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3627 }36283629 async getToken(tokenId: number, blockHashAt?: string) {3630 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3631 }36323633 async getTokenOwner(tokenId: number, blockHashAt?: string) {3634 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3635 }36363637 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3638 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3639 }36403641 async getTokenChildren(tokenId: number, blockHashAt?: string) {3642 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3643 }36443645 async getPropertyPermissions(propertyKeys: string[] | null = null) {3646 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3647 }36483649 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3650 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3651 }36523653 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3654 const api = this.helper.getApi();3655 const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();36563657 return (props! as any).consumedSpace;3658 }36593660 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3661 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3662 }36633664 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3665 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3666 }36673668 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3669 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3670 }36713672 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3673 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3674 }36753676 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3677 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3678 }36793680 async mintMultipleTokens(signer: TSigner, tokens: { owner: ICrossAccountId, properties?: IProperty[] }[]) {3681 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3682 }36833684 async burnToken(signer: TSigner, tokenId: number) {3685 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3686 }36873688 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3689 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3690 }36913692 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3693 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3694 }36953696 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3697 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3698 }36993700 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3701 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3702 }37033704 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3705 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3706 }37073708 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3709 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3710 }37113712 scheduleAt<T extends UniqueHelper>(3713 executionBlockNumber: number,3714 options: ISchedulerOptions = {},3715 ) {3716 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3717 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3718 }37193720 scheduleAfter<T extends UniqueHelper>(3721 blocksBeforeExecution: number,3722 options: ISchedulerOptions = {},3723 ) {3724 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3725 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3726 }37273728 getSudo<T extends UniqueHelper>() {3729 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3730 }3731}373237333734export class UniqueRFTCollection extends UniqueBaseCollection {3735 getTokenObject(tokenId: number) {3736 return new UniqueRFToken(tokenId, this);3737 }37383739 async getToken(tokenId: number, blockHashAt?: string) {3740 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3741 }37423743 async getTokenOwner(tokenId: number, blockHashAt?: string) {3744 return await this.helper.rft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3745 }37463747 async getTokensByAddress(addressObj: ICrossAccountId) {3748 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3749 }37503751 async getTop10TokenOwners(tokenId: number) {3752 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3753 }37543755 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3756 return await this.helper.rft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3757 }37583759 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3760 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3761 }37623763 async getTokenTotalPieces(tokenId: number) {3764 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3765 }37663767 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3768 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3769 }37703771 async getPropertyPermissions(propertyKeys: string[] | null = null) {3772 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3773 }37743775 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3776 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3777 }37783779 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3780 const api = this.helper.getApi();3781 const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();37823783 return (props! as any).consumedSpace;3784 }37853786 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount = 1n) {3787 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3788 }37893790 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {3791 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3792 }37933794 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {3795 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3796 }37973798 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3799 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3800 }38013802 async mintToken(signer: TSigner, pieces = 1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3803 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3804 }38053806 async mintMultipleTokens(signer: TSigner, tokens: { pieces: bigint, owner: ICrossAccountId, properties?: IProperty[] }[]) {3807 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3808 }38093810 async burnToken(signer: TSigner, tokenId: number, amount = 1n) {3811 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3812 }38133814 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n) {3815 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3816 }38173818 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3819 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3820 }38213822 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3823 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3824 }38253826 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3827 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3828 }38293830 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3831 return await this.helper.rft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3832 }38333834 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3835 return await this.helper.rft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3836 }38373838 scheduleAt<T extends UniqueHelper>(3839 executionBlockNumber: number,3840 options: ISchedulerOptions = {},3841 ) {3842 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3843 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3844 }38453846 scheduleAfter<T extends UniqueHelper>(3847 blocksBeforeExecution: number,3848 options: ISchedulerOptions = {},3849 ) {3850 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3851 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3852 }38533854 getSudo<T extends UniqueHelper>() {3855 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3856 }3857}385838593860export class UniqueFTCollection extends UniqueBaseCollection {3861 async getBalance(addressObj: ICrossAccountId) {3862 return await this.helper.ft.getBalance(this.collectionId, addressObj);3863 }38643865 async getTotalPieces() {3866 return await this.helper.ft.getTotalPieces(this.collectionId);3867 }38683869 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3870 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3871 }38723873 async getTop10Owners() {3874 return await this.helper.ft.getTop10Owners(this.collectionId);3875 }38763877 async mint(signer: TSigner, amount = 1n, owner: ICrossAccountId = {Substrate: signer.address}) {3878 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3879 }38803881 async mintWithOneOwner(signer: TSigner, tokens: { value: bigint }[], owner: ICrossAccountId = {Substrate: signer.address}) {3882 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3883 }38843885 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {3886 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3887 }38883889 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {3890 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3891 }38923893 async burnTokens(signer: TSigner, amount = 1n) {3894 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3895 }38963897 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount = 1n) {3898 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3899 }39003901 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {3902 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3903 }39043905 scheduleAt<T extends UniqueHelper>(3906 executionBlockNumber: number,3907 options: ISchedulerOptions = {},3908 ) {3909 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3910 return new UniqueFTCollection(this.collectionId, scheduledHelper);3911 }39123913 scheduleAfter<T extends UniqueHelper>(3914 blocksBeforeExecution: number,3915 options: ISchedulerOptions = {},3916 ) {3917 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3918 return new UniqueFTCollection(this.collectionId, scheduledHelper);3919 }39203921 getSudo<T extends UniqueHelper>() {3922 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3923 }3924}392539263927export class UniqueBaseToken {3928 collection: UniqueNFTCollection | UniqueRFTCollection;3929 collectionId: number;3930 tokenId: number;39313932 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3933 this.collection = collection;3934 this.collectionId = collection.collectionId;3935 this.tokenId = tokenId;3936 }39373938 async getNextSponsored(addressObj: ICrossAccountId) {3939 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3940 }39413942 async getProperties(propertyKeys?: string[] | null) {3943 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3944 }39453946 async getTokenPropertiesConsumedSpace() {3947 return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3948 }39493950 async setProperties(signer: TSigner, properties: IProperty[]) {3951 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3952 }39533954 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3955 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3956 }39573958 async doesExist() {3959 return await this.collection.doesTokenExist(this.tokenId);3960 }39613962 nestingAccount() {3963 return this.collection.helper.util.getTokenAccount(this);3964 }39653966 scheduleAt<T extends UniqueHelper>(3967 executionBlockNumber: number,3968 options: ISchedulerOptions = {},3969 ) {3970 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3971 return new UniqueBaseToken(this.tokenId, scheduledCollection);3972 }39733974 scheduleAfter<T extends UniqueHelper>(3975 blocksBeforeExecution: number,3976 options: ISchedulerOptions = {},3977 ) {3978 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3979 return new UniqueBaseToken(this.tokenId, scheduledCollection);3980 }39813982 getSudo<T extends UniqueHelper>() {3983 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3984 }3985}398639873988export class UniqueNFToken extends UniqueBaseToken {3989 collection: UniqueNFTCollection;39903991 constructor(tokenId: number, collection: UniqueNFTCollection) {3992 super(tokenId, collection);3993 this.collection = collection;3994 }39953996 async getData(blockHashAt?: string) {3997 return await this.collection.getToken(this.tokenId, blockHashAt);3998 }39994000 async getOwner(blockHashAt?: string) {4001 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);4002 }40034004 async getTopmostOwner(blockHashAt?: string) {4005 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);4006 }40074008 async getChildren(blockHashAt?: string) {4009 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);4010 }40114012 async nest(signer: TSigner, toTokenObj: IToken) {4013 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);4014 }40154016 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {4017 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);4018 }40194020 async transfer(signer: TSigner, addressObj: ICrossAccountId) {4021 return await this.collection.transferToken(signer, this.tokenId, addressObj);4022 }40234024 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {4025 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);4026 }40274028 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {4029 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);4030 }40314032 async isApproved(toAddressObj: ICrossAccountId) {4033 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);4034 }40354036 async burn(signer: TSigner) {4037 return await this.collection.burnToken(signer, this.tokenId);4038 }40394040 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {4041 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);4042 }40434044 scheduleAt<T extends UniqueHelper>(4045 executionBlockNumber: number,4046 options: ISchedulerOptions = {},4047 ) {4048 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);4049 return new UniqueNFToken(this.tokenId, scheduledCollection);4050 }40514052 scheduleAfter<T extends UniqueHelper>(4053 blocksBeforeExecution: number,4054 options: ISchedulerOptions = {},4055 ) {4056 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);4057 return new UniqueNFToken(this.tokenId, scheduledCollection);4058 }40594060 getSudo<T extends UniqueHelper>() {4061 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());4062 }4063}40644065export class UniqueRFToken extends UniqueBaseToken {4066 collection: UniqueRFTCollection;40674068 constructor(tokenId: number, collection: UniqueRFTCollection) {4069 super(tokenId, collection);4070 this.collection = collection;4071 }40724073 async getData(blockHashAt?: string) {4074 return await this.collection.getToken(this.tokenId, blockHashAt);4075 }40764077 async getOwner(blockHashAt?: string) {4078 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);4079 }40804081 async getTop10Owners() {4082 return await this.collection.getTop10TokenOwners(this.tokenId);4083 }40844085 async getTopmostOwner(blockHashAt?: string) {4086 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);4087 }40884089 async nest(signer: TSigner, toTokenObj: IToken) {4090 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);4091 }40924093 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {4094 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);4095 }40964097 async getBalance(addressObj: ICrossAccountId) {4098 return await this.collection.getTokenBalance(this.tokenId, addressObj);4099 }41004101 async getTotalPieces() {4102 return await this.collection.getTokenTotalPieces(this.tokenId);4103 }41044105 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {4106 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);4107 }41084109 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount = 1n) {4110 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);4111 }41124113 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {4114 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);4115 }41164117 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {4118 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);4119 }41204121 async repartition(signer: TSigner, amount: bigint) {4122 return await this.collection.repartitionToken(signer, this.tokenId, amount);4123 }41244125 async burn(signer: TSigner, amount = 1n) {4126 return await this.collection.burnToken(signer, this.tokenId, amount);4127 }41284129 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount = 1n) {4130 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);4131 }41324133 scheduleAt<T extends UniqueHelper>(4134 executionBlockNumber: number,4135 options: ISchedulerOptions = {},4136 ) {4137 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);4138 return new UniqueRFToken(this.tokenId, scheduledCollection);4139 }41404141 scheduleAfter<T extends UniqueHelper>(4142 blocksBeforeExecution: number,4143 options: ISchedulerOptions = {},4144 ) {4145 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);4146 return new UniqueRFToken(this.tokenId, scheduledCollection);4147 }41484149 getSudo<T extends UniqueHelper>() {4150 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());4151 }4152}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {SignerOptions} from '@polkadot/api/types/submittable';10import '../../interfaces/augment-api';11import {AugmentedSubmittables} from '@polkadot/api-base/types/submittable';12import {ApiInterfaceEvents} from '@polkadot/api/types';13import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';14import {IKeyringPair} from '@polkadot/types/types';15import {hexToU8a} from '@polkadot/util/hex';16import {u8aConcat} from '@polkadot/util/u8a';17import {18 IApiListeners,19 IBlock,20 IEvent,21 IChainProperties,22 ICollectionCreationOptions,23 ICollectionLimits,24 ICollectionPermissions,25 ICrossAccountId,26 ICrossAccountIdLower,27 ILogger,28 INestingPermissions,29 IProperty,30 IStakingInfo,31 ISchedulerOptions,32 ISubstrateBalance,33 IToken,34 ITokenPropertyPermission,35 ITransactionResult,36 IUniqueHelperLog,37 TApiAllowedListeners,38 TEthereumAccount,39 TSigner,40 TSubstrateAccount,41 TNetworks,42 IForeignAssetMetadata,43 AcalaAssetMetadata,44 MoonbeamAssetInfo,45 DemocracyStandardAccountVote,46 IEthCrossAccountId,47} from './types';48import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';49import type {Vec} from '@polkadot/types-codec';50import {FrameSystemEventRecord, PalletBalancesIdAmount} from '@polkadot/types/lookup';5152export class CrossAccountId {53 Substrate!: TSubstrateAccount;54 Ethereum!: TEthereumAccount;5556 constructor(account: ICrossAccountId) {57 if ('Substrate' in account) this.Substrate = account.Substrate;58 else this.Ethereum = account.Ethereum;59 }6061 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {62 switch (domain) {63 case 'Substrate': return new CrossAccountId({Substrate: account.address});64 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();65 }66 }6768 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {69 if ('substrate' in address) return new CrossAccountId({Substrate: address.substrate});70 else return new CrossAccountId({Ethereum: address.ethereum});71 }7273 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {74 return encodeAddress(decodeAddress(address), ss58Format);75 }7677 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {78 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});79 }8081 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {82 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);83 return this;84 }8586 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {87 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));88 }8990 toEthereum(): CrossAccountId {91 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});92 return this;93 }9495 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {96 return evmToAddress(address, ss58Format);97 }9899 toSubstrate(ss58Format?: number): CrossAccountId {100 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});101 return this;102 }103104 toLowerCase(): CrossAccountId {105 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();106 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();107 return this;108 }109}110111const nesting = {112 toChecksumAddress(address: string): string {113 if (typeof address === 'undefined') return '';114115 if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);116117 address = address.toLowerCase().replace(/^0x/i, '');118 const addressHash = keccakAsHex(address).replace(/^0x/i, '');119 const checksumAddress = ['0x'];120121 for (let i = 0; i < address.length; i++) {122 // If ith character is 8 to f then make it uppercase123 if (parseInt(addressHash[i], 16) > 7) {124 checksumAddress.push(address[i].toUpperCase());125 } else {126 checksumAddress.push(address[i]);127 }128 }129 return checksumAddress.join('');130 },131 tokenIdToAddress(collectionId: number, tokenId: number) {132 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);133 },134};135136class UniqueUtil {137 static transactionStatus = {138 NOT_READY: 'NotReady',139 FAIL: 'Fail',140 SUCCESS: 'Success',141 };142143 static chainLogType = {144 EXTRINSIC: 'extrinsic',145 RPC: 'rpc',146 };147148 static getTokenAccount(token: IToken): CrossAccountId {149 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});150 }151152 static getTokenAddress(token: IToken): string {153 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);154 }155156 static getDefaultLogger(): ILogger {157 return {158 log(msg: any, level = 'INFO') {159 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));160 },161 level: {162 ERROR: 'ERROR',163 WARNING: 'WARNING',164 INFO: 'INFO',165 },166 };167 }168169 static vec2str(arr: string[] | number[]) {170 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');171 }172173 static str2vec(string: string) {174 if (typeof string !== 'string') return string;175 return Array.from(string).map(x => x.charCodeAt(0));176 }177178 static fromSeed(seed: string, ss58Format = 42) {179 const keyring = new Keyring({type: 'sr25519', ss58Format});180 return keyring.addFromUri(seed);181 }182183 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {184 if (creationResult.status !== this.transactionStatus.SUCCESS) {185 throw Error('Unable to create collection!');186 }187188 let collectionId = null;189 creationResult.result.events.forEach(({event: {data, method, section}}) => {190 if ((section === 'common') && (method === 'CollectionCreated')) {191 collectionId = parseInt(data[0].toString(), 10);192 }193 });194195 if (collectionId === null) {196 throw Error('No CollectionCreated event was found!');197 }198199 return collectionId;200 }201202 static extractTokensFromCreationResult(creationResult: ITransactionResult): {203 success: boolean,204 tokens: { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[],205 } {206 if (creationResult.status !== this.transactionStatus.SUCCESS) {207 throw Error('Unable to create tokens!');208 }209 let success = false;210 const tokens = [] as { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[];211 creationResult.result.events.forEach(({event: {data, method, section}}) => {212 if (method === 'ExtrinsicSuccess') {213 success = true;214 } else if ((section === 'common') && (method === 'ItemCreated')) {215 tokens.push({216 collectionId: parseInt(data[0].toString(), 10),217 tokenId: parseInt(data[1].toString(), 10),218 owner: data[2].toHuman(),219 amount: data[3].toBigInt(),220 });221 }222 });223 return {success, tokens};224 }225226 static extractTokensFromBurnResult(burnResult: ITransactionResult): {227 success: boolean,228 tokens: { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[],229 } {230 if (burnResult.status !== this.transactionStatus.SUCCESS) {231 throw Error('Unable to burn tokens!');232 }233 let success = false;234 const tokens = [] as { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[];235 burnResult.result.events.forEach(({event: {data, method, section}}) => {236 if (method === 'ExtrinsicSuccess') {237 success = true;238 } else if ((section === 'common') && (method === 'ItemDestroyed')) {239 tokens.push({240 collectionId: parseInt(data[0].toString(), 10),241 tokenId: parseInt(data[1].toString(), 10),242 owner: data[2].toHuman(),243 amount: data[3].toBigInt(),244 });245 }246 });247 return {success, tokens};248 }249250 static findCollectionInEvents(events: { event: IEvent }[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {251 let eventId = null;252 events.forEach(({event: {data, method, section}}) => {253 if ((section === expectedSection) && (method === expectedMethod)) {254 eventId = parseInt(data[0].toString(), 10);255 }256 });257258 if (eventId === null) {259 throw Error(`No ${expectedMethod} event was found!`);260 }261 return eventId === collectionId;262 }263264 static isTokenTransferSuccess(events: { event: IEvent }[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {265 const normalizeAddress = (address: string | ICrossAccountId) => {266 if (typeof address === 'string') return address;267 const obj = {} as any;268 Object.keys(address).forEach(k => {269 obj[k.toLocaleLowerCase()] = (address as any)[k];270 });271 if (obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);272 if (obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();273 return address;274 };275 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;276 events.forEach(({event: {data, method, section}}) => {277 if ((section === 'common') && (method === 'Transfer')) {278 const hData = (data as any).toJSON();279 transfer = {280 collectionId: hData[0],281 tokenId: hData[1],282 from: normalizeAddress(hData[2]),283 to: normalizeAddress(hData[3]),284 amount: BigInt(hData[4]),285 };286 }287 });288 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;289 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);290 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);291 isSuccess = isSuccess && amount === transfer.amount;292 return isSuccess;293 }294295 static bigIntToDecimals(number: bigint, decimals = 18) {296 const numberStr = number.toString();297 const dotPos = numberStr.length - decimals;298299 if (dotPos <= 0) {300 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;301 } else {302 const intPart = numberStr.substring(0, dotPos);303 const fractPart = numberStr.substring(dotPos);304 return intPart + '.' + fractPart;305 }306 }307}308309class UniqueEventHelper {310 private static extractIndex(index: any): [number, number] | string {311 if (index.toRawType() === '[u8;2]') return [index[0], index[1]];312 return index.toJSON();313 }314315 private static extractSub(data: any, subTypes: any): { [key: string]: any } {316 let obj: any = {};317 let index = 0;318319 if (data.entries) {320 for (const [key, value] of data.entries()) {321 obj[key] = this.extractData(value, subTypes[index]);322 index++;323 }324 } else obj = data.toJSON();325326 return obj;327 }328329 private static toHuman(data: any) {330 return data && data.toHuman ? data.toHuman() : `${data}`;331 }332333 private static extractData(data: any, type: any): any {334 if (!type) return this.toHuman(data);335 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();336 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();337 if (type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);338 return this.toHuman(data);339 }340341 public static extractEvents(events: { event: any, phase: any }[]): IEvent[] {342 const parsedEvents: IEvent[] = [];343344 events.forEach((record) => {345 const {event, phase} = record;346 const types = event.typeDef;347348 const eventData: IEvent = {349 section: event.section.toString(),350 method: event.method.toString(),351 index: this.extractIndex(event.index),352 data: [],353 phase: phase.toJSON(),354 };355356 event.data.forEach((val: any, index: number) => {357 eventData.data.push(this.extractData(val, types[index]));358 });359360 parsedEvents.push(eventData);361 });362363 return parsedEvents;364 }365}366const InvalidTypeSymbol = Symbol('Invalid type');367// eslint-disable-next-line @typescript-eslint/no-unused-vars368export type Invalid<ErrorMessage> =369 | ((370 invalidType: typeof InvalidTypeSymbol,371 ..._: typeof InvalidTypeSymbol[]372 ) => typeof InvalidTypeSymbol)373 | null374 | undefined;375// Has slightly better error messages than Get376type Get2<T, P extends string, E> =377 P extends `${infer Key}.${infer Key2}` ? Key extends keyof T ? Key2 extends keyof T[Key] ? T[Key][Key2] : E : E : E;378type ForceFunction<T> = T extends (...args: any) => any ? T : (...args: any) => Invalid<'not a function'>;379380export class ChainHelperBase {381 helperBase: any;382383 transactionStatus = UniqueUtil.transactionStatus;384 chainLogType = UniqueUtil.chainLogType;385 util: typeof UniqueUtil;386 eventHelper: typeof UniqueEventHelper;387 logger: ILogger;388 api: ApiPromise | null;389 forcedNetwork: TNetworks | null;390 network: TNetworks | null;391 wsEndpoint: string | null;392 chainLog: IUniqueHelperLog[];393 children: ChainHelperBase[];394 address: AddressGroup;395 chain: ChainGroup;396397 constructor(logger?: ILogger, helperBase?: any) {398 this.helperBase = helperBase;399400 this.util = UniqueUtil;401 this.eventHelper = UniqueEventHelper;402 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();403 this.logger = logger;404 this.api = null;405 this.forcedNetwork = null;406 this.network = null;407 this.wsEndpoint = null;408 this.chainLog = [];409 this.children = [];410 this.address = new AddressGroup(this);411 this.chain = new ChainGroup(this);412 }413414 clone(helperCls: ChainHelperBaseConstructor, options: { [key: string]: any } = {}) {415 Object.setPrototypeOf(helperCls.prototype, this);416 const newHelper = new helperCls(this.logger, options);417418 newHelper.api = this.api;419 newHelper.network = this.network;420 newHelper.forceNetwork = this.forceNetwork;421422 this.children.push(newHelper);423424 return newHelper;425 }426427 getEndpoint(): string {428 if (this.wsEndpoint === null) throw Error('No connection was established');429 return this.wsEndpoint;430 }431432 getApi(): ApiPromise {433 if (this.api === null) throw Error('API not initialized');434 return this.api;435 }436437 async subscribeEvents(expectedEvents: { section: string, names: string[] }[]) {438 const collectedEvents: IEvent[] = [];439 const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {440 const ievents = this.eventHelper.extractEvents(events);441 ievents.forEach((event) => {442 expectedEvents.forEach((e => {443 if (event.section === e.section && e.names.includes(event.method)) {444 collectedEvents.push(event);445 }446 }));447 });448 });449 return {unsubscribe: unsubscribe as any, collectedEvents};450 }451452 clearChainLog(): void {453 this.chainLog = [];454 }455456 forceNetwork(value: TNetworks): void {457 this.forcedNetwork = value;458 }459460 async connect(wsEndpoint: string, listeners?: IApiListeners) {461 if (this.api !== null) throw Error('Already connected');462 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);463 this.wsEndpoint = wsEndpoint;464 this.api = api;465 this.network = network;466 }467468 async disconnect() {469 for (const child of this.children) {470 child.clearApi();471 }472473 if (this.api === null) return;474 await this.api.disconnect();475 this.clearApi();476 }477478 clearApi() {479 this.api = null;480 this.network = null;481 }482483 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {484 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;485 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];486487 if (xcmChains.indexOf(spec.specName) > -1) return spec.specName;488489 if (['quartz', 'unique', 'sapphire'].indexOf(spec.specName) > -1) return spec.specName;490 return 'opal';491 }492493 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {494 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});495 await api.isReady;496497 const network = await this.detectNetwork(api);498499 await api.disconnect();500501 return network;502 }503504 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{505 api: ApiPromise;506 network: TNetworks;507 }> {508 if (typeof network === 'undefined' || network === null) network = 'opal';509 const supportedRPC = {510 opal: {511 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,512 },513 quartz: {514 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,515 },516 unique: {517 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,518 },519 rococo: {},520 westend: {},521 moonbeam: {},522 moonriver: {},523 acala: {},524 karura: {},525 westmint: {},526 };527 if (!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);528 const rpc = supportedRPC[network];529530 // TODO: investigate how to replace rpc in runtime531 // api._rpcCore.addUserInterfaces(rpc);532533 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});534535 await api.isReadyOrError;536537 if (typeof listeners === 'undefined') listeners = {};538 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {539 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;540 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);541 }542543 return {api, network};544 }545546 getTransactionStatus(data: { events: { event: IEvent }[], status: any }) {547 const {events, status} = data;548 if (status.isReady) {549 return this.transactionStatus.NOT_READY;550 }551 if (status.isBroadcast) {552 return this.transactionStatus.NOT_READY;553 }554 if (status.isInBlock || status.isFinalized) {555 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');556 if (errors.length > 0) {557 return this.transactionStatus.FAIL;558 }559 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {560 return this.transactionStatus.SUCCESS;561 }562 }563564 return this.transactionStatus.FAIL;565 }566567 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {568 const sign = (callback: any) => {569 if (options !== null) return transaction.signAndSend(sender, options, callback);570 return transaction.signAndSend(sender, callback);571 };572 // eslint-disable-next-line no-async-promise-executor573 return new Promise(async (resolve, reject) => {574 try {575 const unsub = await sign((result: any) => {576 const status = this.getTransactionStatus(result);577578 if (status === this.transactionStatus.SUCCESS) {579 this.logger.log(`${label} successful`);580 unsub();581 resolve({result, status, blockHash: result.status.asInBlock.toHuman()});582 } else if (status === this.transactionStatus.FAIL) {583 let moduleError = null;584585 if (result.hasOwnProperty('dispatchError')) {586 const dispatchError = result['dispatchError'];587588 if (dispatchError) {589 if (dispatchError.isModule) {590 const modErr = dispatchError.asModule;591 const errorMeta = dispatchError.registry.findMetaError(modErr);592593 moduleError = `${errorMeta.section}.${errorMeta.name}`;594 } else if (dispatchError.isToken) {595 moduleError = `Token: ${dispatchError.asToken}`;596 } else {597 // May be [object Object] in case of unhandled non-unit enum598 moduleError = `Misc: ${dispatchError.toHuman()}`;599 }600 } else {601 this.logger.log(result, this.logger.level.ERROR);602 }603 }604605 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);606 unsub();607 reject({status, moduleError, result});608 }609 });610 } catch (e) {611 this.logger.log(e, this.logger.level.ERROR);612 reject(e);613 }614 });615 }616617 async signTransactionWithoutSending(signer: TSigner, tx: any) {618 const api = this.getApi();619 const signingInfo = await api.derive.tx.signingInfo(signer.address);620621 tx.sign(signer, {622 blockHash: api.genesisHash,623 genesisHash: api.genesisHash,624 runtimeVersion: api.runtimeVersion,625 nonce: signingInfo.nonce,626 });627628 return tx.toHex();629 }630631 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {632 const api = this.getApi();633 const signingInfo = await api.derive.tx.signingInfo(signer.address);634635 // We need to sign the tx because636 // unsigned transactions does not have an inclusion fee637 tx.sign(signer, {638 blockHash: api.genesisHash,639 genesisHash: api.genesisHash,640 runtimeVersion: api.runtimeVersion,641 nonce: signingInfo.nonce,642 });643644 if (len === null) {645 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;646 } else {647 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;648 }649 }650651 constructApiCall(apiCall: string, params: any[]) {652 if (!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);653 let call = this.getApi() as any;654 for (const part of apiCall.slice(4).split('.')) {655 call = call[part];656 if (!call) {657 const advice = part.includes('_') ? ' Looks like it needs to be converted to camel case.' : '';658 throw Error(`Function ${part} of api call ${apiCall} not found.${advice}`);659 }660 }661 return call(...params);662 }663664 encodeApiCall(apiCall: string, params: any[]) {665 return this.constructApiCall(apiCall, params).method.toHex();666 }667668 async executeExtrinsic<669 E extends string,670 V extends (671 ...args: any) => any = ForceFunction<672 Get2<673 AugmentedSubmittables<'promise'>,674 E, (...args: any) => Invalid<'not found'>675 >676 >677 >(678 sender: TSigner,679 extrinsic: `api.tx.${E}`,680 params: Parameters<V>,681 expectSuccess = true,682 options: Partial<SignerOptions> | null = null,/*, failureMessage='expected success'*/683 ): Promise<ITransactionResult> {684 if (this.api === null) throw Error('API not initialized');685 if (!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);686687 const startTime = (new Date()).getTime();688 let result: ITransactionResult;689 let events: IEvent[] = [];690 try {691 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;692 events = this.eventHelper.extractEvents(result.result.events);693 const errorEvent = events.find((event) => event.method == 'ExecutedFailed' || event.method == 'CreatedFailed');694 if (errorEvent)695 throw Error(errorEvent.method + ': ' + extrinsic);696 }697 catch (e) {698 if (!(e as object).hasOwnProperty('status')) throw e;699 result = e as ITransactionResult;700 }701702 const endTime = (new Date()).getTime();703704 const log = {705 executedAt: endTime,706 executionTime: endTime - startTime,707 type: this.chainLogType.EXTRINSIC,708 status: result.status,709 call: extrinsic,710 signer: this.getSignerAddress(sender),711 params,712 } as IUniqueHelperLog;713714 let errorMessage = '';715716 if (result.status !== this.transactionStatus.SUCCESS) {717 if (result.moduleError) {718 errorMessage = typeof result.moduleError === 'string'719 ? result.moduleError720 : `${Object.keys(result.moduleError)[0]}: ${Object.values(result.moduleError)[0]}`;721 log.moduleError = errorMessage;722 }723 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;724 }725 if (events.length > 0) log.events = events;726727 this.chainLog.push(log);728729 if (expectSuccess && result.status !== this.transactionStatus.SUCCESS) {730 if (result.moduleError) throw Error(`${errorMessage}`);731 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));732 }733 return result as any;734 }735736 async callRpc737 // <738 // K extends 'rpc' | 'query',739 // E extends string,740 // V extends (...args: any) => any = ForceFunction<741 // Get2<742 // K extends 'rpc' ? DecoratedRpc<'promise', RpcInterface> : QueryableStorage<'promise'>,743 // E, (...args: any) => Invalid<'not found'>744 // >745 // >,746 // P = Parameters<V>,747 // >748 (rpc: string, params?: any[]): Promise<any> {749750 if (typeof params === 'undefined') params = [] as any;751 if (this.api === null) throw Error('API not initialized');752 if (!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);753754 const startTime = (new Date()).getTime();755 let result;756 let error = null;757 const log = {758 type: this.chainLogType.RPC,759 call: rpc,760 params,761 } as any as IUniqueHelperLog;762763 try {764 result = await this.constructApiCall(rpc, params as any);765 }766 catch (e) {767 error = e;768 }769770 const endTime = (new Date()).getTime();771772 log.executedAt = endTime;773 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';774 log.executionTime = endTime - startTime;775776 this.chainLog.push(log);777778 if (error !== null) throw error;779780 return result;781 }782783 getSignerAddress(signer: IKeyringPair | string): string {784 if (typeof signer === 'string') return signer;785 return signer.address;786 }787788 fetchAllPalletNames(): string[] {789 if (this.api === null) throw Error('API not initialized');790 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase()).sort();791 }792793 fetchMissingPalletNames(requiredPallets: readonly string[]): string[] {794 const palletNames = this.fetchAllPalletNames();795 return requiredPallets.filter(p => !palletNames.includes(p));796 }797}798799800class HelperGroup<T extends ChainHelperBase> {801 helper: T;802803 constructor(uniqueHelper: T) {804 this.helper = uniqueHelper;805 }806}807808809class CollectionGroup extends HelperGroup<UniqueHelper> {810 /**811 * Get number of blocks when sponsored transaction is available.812 *813 * @param collectionId ID of collection814 * @param tokenId ID of token815 * @param addressObj address for which the sponsorship is checked816 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});817 * @returns number of blocks or null if sponsorship hasn't been set818 */819 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {820 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();821 }822823 /**824 * Get the number of created collections.825 *826 * @returns number of created collections827 */828 async getTotalCount(): Promise<number> {829 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();830 }831832 /**833 * Get information about the collection with additional data,834 * including the number of tokens it contains, its administrators,835 * the normalized address of the collection's owner, and decoded name and description.836 *837 * @param collectionId ID of collection838 * @example await getData(2)839 * @returns collection information object840 */841 async getData(collectionId: number): Promise<{842 id: number;843 name: string;844 description: string;845 tokensCount: number;846 admins: CrossAccountId[];847 normalizedOwner: TSubstrateAccount;848 raw: any849 } | null> {850 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);851 const humanCollection = collection.toHuman(), collectionData = {852 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],853 raw: humanCollection,854 } as any, jsonCollection = collection.toJSON();855 if (humanCollection === null) return null;856 collectionData.raw.limits = jsonCollection.limits;857 collectionData.raw.permissions = jsonCollection.permissions;858 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);859 for (const key of ['name', 'description']) {860 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);861 }862863 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))864 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)865 : 0;866 collectionData.admins = await this.getAdmins(collectionId);867868 return collectionData;869 }870871 /**872 * Get the addresses of the collection's administrators, optionally normalized.873 *874 * @param collectionId ID of collection875 * @param normalize whether to normalize the addresses to the default ss58 format876 * @example await getAdmins(1)877 * @returns array of administrators878 */879 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {880 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();881882 return normalize883 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())884 : admins;885 }886887 /**888 * Get the addresses added to the collection allow-list, optionally normalized.889 * @param collectionId ID of collection890 * @param normalize whether to normalize the addresses to the default ss58 format891 * @example await getAllowList(1)892 * @returns array of allow-listed addresses893 */894 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {895 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();896 return normalize897 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())898 : allowListed;899 }900901 /**902 * Get the effective limits of the collection instead of null for default values903 *904 * @param collectionId ID of collection905 * @example await getEffectiveLimits(2)906 * @returns object of collection limits907 */908 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {909 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();910 }911912 /**913 * Burns the collection if the signer has sufficient permissions and collection is empty.914 *915 * @param signer keyring of signer916 * @param collectionId ID of collection917 * @example await helper.collection.burn(aliceKeyring, 3);918 * @returns ```true``` if extrinsic success, otherwise ```false```919 */920 async burn(signer: TSigner, collectionId: number): Promise<boolean> {921 const result = await this.helper.executeExtrinsic(922 signer,923 'api.tx.unique.destroyCollection', [collectionId],924 true,925 );926927 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');928 }929930 /**931 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.932 *933 * @param signer keyring of signer934 * @param collectionId ID of collection935 * @param sponsorAddress Sponsor substrate address936 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")937 * @returns ```true``` if extrinsic success, otherwise ```false```938 */939 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {940 const result = await this.helper.executeExtrinsic(941 signer,942 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],943 true,944 );945946 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');947 }948949 /**950 * Confirms consent to sponsor the collection on behalf of the signer.951 *952 * @param signer keyring of signer953 * @param collectionId ID of collection954 * @example confirmSponsorship(aliceKeyring, 10)955 * @returns ```true``` if extrinsic success, otherwise ```false```956 */957 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {958 const result = await this.helper.executeExtrinsic(959 signer,960 'api.tx.unique.confirmSponsorship', [collectionId],961 true,962 );963964 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');965 }966967 /**968 * Removes the sponsor of a collection, regardless if it consented or not.969 *970 * @param signer keyring of signer971 * @param collectionId ID of collection972 * @example removeSponsor(aliceKeyring, 10)973 * @returns ```true``` if extrinsic success, otherwise ```false```974 */975 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {976 const result = await this.helper.executeExtrinsic(977 signer,978 'api.tx.unique.removeCollectionSponsor', [collectionId],979 true,980 );981982 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');983 }984985 /**986 * Sets the limits of the collection. At least one limit must be specified for a correct call.987 *988 * @param signer keyring of signer989 * @param collectionId ID of collection990 * @param limits collection limits object991 * @example992 * await setLimits(993 * aliceKeyring,994 * 10,995 * {996 * sponsorTransferTimeout: 0,997 * ownerCanDestroy: false998 * }999 * )1000 * @returns ```true``` if extrinsic success, otherwise ```false```1001 */1002 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {1003 const result = await this.helper.executeExtrinsic(1004 signer,1005 'api.tx.unique.setCollectionLimits', [collectionId, limits],1006 true,1007 );10081009 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');1010 }10111012 /**1013 * Changes the owner of the collection to the new Substrate address.1014 *1015 * @param signer keyring of signer1016 * @param collectionId ID of collection1017 * @param ownerAddress substrate address of new owner1018 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")1019 * @returns ```true``` if extrinsic success, otherwise ```false```1020 */1021 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {1022 const result = await this.helper.executeExtrinsic(1023 signer,1024 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],1025 true,1026 );10271028 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');1029 }10301031 /**1032 * Adds a collection administrator.1033 *1034 * @param signer keyring of signer1035 * @param collectionId ID of collection1036 * @param adminAddressObj Administrator address (substrate or ethereum)1037 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})1038 * @returns ```true``` if extrinsic success, otherwise ```false```1039 */1040 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1041 const result = await this.helper.executeExtrinsic(1042 signer,1043 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],1044 true,1045 );10461047 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');1048 }10491050 /**1051 * Removes a collection administrator.1052 *1053 * @param signer keyring of signer1054 * @param collectionId ID of collection1055 * @param adminAddressObj Administrator address (substrate or ethereum)1056 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})1057 * @returns ```true``` if extrinsic success, otherwise ```false```1058 */1059 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1060 const result = await this.helper.executeExtrinsic(1061 signer,1062 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],1063 true,1064 );10651066 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');1067 }10681069 /**1070 * Check if user is in allow list.1071 *1072 * @param collectionId ID of collection1073 * @param user Account to check1074 * @example await getAdmins(1)1075 * @returns is user in allow list1076 */1077 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {1078 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();1079 }10801081 /**1082 * Adds an address to allow list1083 * @param signer keyring of signer1084 * @param collectionId ID of collection1085 * @param addressObj address to add to the allow list1086 * @returns ```true``` if extrinsic success, otherwise ```false```1087 */1088 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1089 const result = await this.helper.executeExtrinsic(1090 signer,1091 'api.tx.unique.addToAllowList', [collectionId, addressObj],1092 true,1093 );10941095 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1096 }10971098 /**1099 * Removes an address from allow list1100 *1101 * @param signer keyring of signer1102 * @param collectionId ID of collection1103 * @param addressObj address to remove from the allow list1104 * @returns ```true``` if extrinsic success, otherwise ```false```1105 */1106 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1107 const result = await this.helper.executeExtrinsic(1108 signer,1109 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1110 true,1111 );11121113 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1114 }11151116 /**1117 * Sets onchain permissions for selected collection.1118 *1119 * @param signer keyring of signer1120 * @param collectionId ID of collection1121 * @param permissions collection permissions object1122 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1123 * @returns ```true``` if extrinsic success, otherwise ```false```1124 */1125 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1126 const result = await this.helper.executeExtrinsic(1127 signer,1128 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1129 true,1130 );11311132 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1133 }11341135 /**1136 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1137 *1138 * @param signer keyring of signer1139 * @param collectionId ID of collection1140 * @param permissions nesting permissions object1141 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1142 * @returns ```true``` if extrinsic success, otherwise ```false```1143 */1144 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1145 return await this.setPermissions(signer, collectionId, {nesting: permissions});1146 }11471148 /**1149 * Disables nesting for selected collection.1150 *1151 * @param signer keyring of signer1152 * @param collectionId ID of collection1153 * @example disableNesting(aliceKeyring, 10);1154 * @returns ```true``` if extrinsic success, otherwise ```false```1155 */1156 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1157 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1158 }11591160 /**1161 * Sets onchain properties to the collection.1162 *1163 * @param signer keyring of signer1164 * @param collectionId ID of collection1165 * @param properties array of property objects1166 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1167 * @returns ```true``` if extrinsic success, otherwise ```false```1168 */1169 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1170 const result = await this.helper.executeExtrinsic(1171 signer,1172 'api.tx.unique.setCollectionProperties', [collectionId, properties],1173 true,1174 );11751176 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1177 }11781179 /**1180 * Get collection properties.1181 *1182 * @param collectionId ID of collection1183 * @param propertyKeys optionally filter the returned properties to only these keys1184 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1185 * @returns array of key-value pairs1186 */1187 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1188 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1189 }11901191 async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1192 const api = this.helper.getApi();1193 const props = (await api.query.common.collectionProperties(collectionId)).toJSON();11941195 return (props! as any).consumedSpace;1196 }11971198 async getCollectionOptions(collectionId: number) {1199 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1200 }12011202 /**1203 * Deletes onchain properties from the collection.1204 *1205 * @param signer keyring of signer1206 * @param collectionId ID of collection1207 * @param propertyKeys array of property keys to delete1208 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1209 * @returns ```true``` if extrinsic success, otherwise ```false```1210 */1211 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1212 const result = await this.helper.executeExtrinsic(1213 signer,1214 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1215 true,1216 );12171218 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1219 }12201221 /**1222 * Changes the owner of the token.1223 *1224 * @param signer keyring of signer1225 * @param collectionId ID of collection1226 * @param tokenId ID of token1227 * @param addressObj address of a new owner1228 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1229 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1230 * @returns true if the token success, otherwise false1231 */1232 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1233 const result = await this.helper.executeExtrinsic(1234 signer,1235 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1236 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1237 );12381239 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1240 }12411242 /**1243 *1244 * Change ownership of a token(s) on behalf of the owner.1245 *1246 * @param signer keyring of signer1247 * @param collectionId ID of collection1248 * @param tokenId ID of token1249 * @param fromAddressObj address on behalf of which the token will be sent1250 * @param toAddressObj new token owner1251 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1252 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1253 * @returns true if the token success, otherwise false1254 */1255 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1256 const result = await this.helper.executeExtrinsic(1257 signer,1258 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1259 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1260 );1261 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1262 }12631264 /**1265 *1266 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1267 *1268 * @param signer keyring of signer1269 * @param collectionId ID of collection1270 * @param tokenId ID of token1271 * @param amount amount of tokens to be burned. For NFT must be set to 1n1272 * @example burnToken(aliceKeyring, 10, 5);1273 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1274 */1275 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount = 1n): Promise<boolean> {1276 const burnResult = await this.helper.executeExtrinsic(1277 signer,1278 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1279 true, // `Unable to burn token for ${label}`,1280 );1281 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1282 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1283 return burnedTokens.success;1284 }12851286 /**1287 * Destroys a concrete instance of NFT on behalf of the owner1288 *1289 * @param signer keyring of signer1290 * @param collectionId ID of collection1291 * @param tokenId ID of token1292 * @param fromAddressObj address on behalf of which the token will be burnt1293 * @param amount amount of tokens to be burned. For NFT must be set to 1n1294 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1295 * @returns ```true``` if extrinsic success, otherwise ```false```1296 */1297 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1298 const burnResult = await this.helper.executeExtrinsic(1299 signer,1300 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1301 true, // `Unable to burn token from for ${label}`,1302 );1303 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1304 return burnedTokens.success && burnedTokens.tokens.length > 0;1305 }13061307 /**1308 * Set, change, or remove approved address to transfer the ownership of the NFT.1309 *1310 * @param signer keyring of signer1311 * @param collectionId ID of collection1312 * @param tokenId ID of token1313 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1314 * @param amount amount of token to be approved. For NFT must be set to 1n1315 * @returns ```true``` if extrinsic success, otherwise ```false```1316 */1317 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1318 const approveResult = await this.helper.executeExtrinsic(1319 signer,1320 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1321 true, // `Unable to approve token for ${label}`,1322 );13231324 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1325 }13261327 /**1328 * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1329 *1330 * @param signer keyring of signer1331 * @param collectionId ID of collection1332 * @param tokenId ID of token1333 * @param fromAddressObj Signer's Ethereum address containing her tokens1334 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1335 * @param amount amount of token to be approved. For NFT must be set to 1n1336 * @returns ```true``` if extrinsic success, otherwise ```false```1337 */1338 async approveTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {1339 const approveResult = await this.helper.executeExtrinsic(1340 signer,1341 'api.tx.unique.approveFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1342 true, // `Unable to approve token for ${label}`,1343 );13441345 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1346 }13471348 /**1349 * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1350 *1351 * @param signer keyring of signer1352 * @param collectionId ID of collection1353 * @param tokenId ID of token1354 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1355 * @param amount amount of token to be approved. For NFT must be set to 1n1356 * @returns ```true``` if extrinsic success, otherwise ```false```1357 */1358 async approveTokenFromEth(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1359 const ethMirror = CrossAccountId.fromKeyring(signer).toEthereum();1360 return await this.approveTokenFrom(signer, collectionId, tokenId, ethMirror, toAddressObj, amount);1361 }13621363 /**1364 * Get the amount of token pieces approved to transfer or burn. Normally 0.1365 *1366 * @param collectionId ID of collection1367 * @param tokenId ID of token1368 * @param toAccountObj address which is approved to use token pieces1369 * @param fromAccountObj address which may have allowed the use of its owned tokens1370 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1371 * @returns number of approved to transfer pieces1372 */1373 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1374 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1375 }13761377 /**1378 * Get the last created token ID in a collection1379 *1380 * @param collectionId ID of collection1381 * @example getLastTokenId(10);1382 * @returns id of the last created token1383 */1384 async getLastTokenId(collectionId: number): Promise<number> {1385 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1386 }13871388 /**1389 * Check if token exists1390 *1391 * @param collectionId ID of collection1392 * @param tokenId ID of token1393 * @example doesTokenExist(10, 20);1394 * @returns true if the token exists, otherwise false1395 */1396 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1397 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1398 }1399}14001401class NFTnRFT extends CollectionGroup {1402 /**1403 * Get tokens owned by account1404 *1405 * @param collectionId ID of collection1406 * @param addressObj tokens owner1407 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1408 * @returns array of token ids owned by account1409 */1410 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1411 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1412 }14131414 /**1415 * Get token data1416 *1417 * @param collectionId ID of collection1418 * @param tokenId ID of token1419 * @param propertyKeys optionally filter the token properties to only these keys1420 * @param blockHashAt optionally query the data at some block with this hash1421 * @example getToken(10, 5);1422 * @returns human readable token data1423 */1424 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1425 properties: IProperty[];1426 owner: CrossAccountId;1427 normalizedOwner: CrossAccountId;1428 } | null> {1429 let tokenData;1430 if (typeof blockHashAt === 'undefined') {1431 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1432 }1433 else {1434 if (propertyKeys.length == 0) {1435 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1436 if (!collection) return null;1437 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1438 }1439 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1440 }1441 tokenData = tokenData.toHuman();1442 if (tokenData === null || tokenData.owner === null) return null;1443 const owner = {} as any;1444 for (const key of Object.keys(tokenData.owner)) {1445 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1446 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1447 : tokenData.owner[key];1448 }1449 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1450 return tokenData;1451 }14521453 /**1454 * Get token's owner1455 * @param collectionId ID of collection1456 * @param tokenId ID of token1457 * @param blockHashAt optionally query the data at the block with this hash1458 * @example getTokenOwner(10, 5);1459 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1460 */1461 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1462 let owner;1463 if (typeof blockHashAt === 'undefined') {1464 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1465 } else {1466 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1467 }1468 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1469 }14701471 /**1472 * Recursively find the address that owns the token1473 * @param collectionId ID of collection1474 * @param tokenId ID of token1475 * @param blockHashAt1476 * @example getTokenTopmostOwner(10, 5);1477 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1478 */1479 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1480 let owner;1481 if (typeof blockHashAt === 'undefined') {1482 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1483 } else {1484 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1485 }14861487 if (owner === null) return null;14881489 return owner.toHuman();1490 }14911492 /**1493 * Nest one token into another1494 * @param signer keyring of signer1495 * @param tokenObj token to be nested1496 * @param rootTokenObj token to be parent1497 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1498 * @returns ```true``` if extrinsic success, otherwise ```false```1499 */1500 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1501 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1502 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1503 if (!result) {1504 throw Error('Unable to nest token!');1505 }1506 return result;1507 }15081509 /**1510 * Remove token from nested state1511 * @param signer keyring of signer1512 * @param tokenObj token to unnest1513 * @param rootTokenObj parent of a token1514 * @param toAddressObj address of a new token owner1515 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1516 * @returns ```true``` if extrinsic success, otherwise ```false```1517 */1518 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1519 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1520 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1521 if (!result) {1522 throw Error('Unable to unnest token!');1523 }1524 return result;1525 }15261527 /**1528 * Set permissions to change token properties1529 *1530 * @param signer keyring of signer1531 * @param collectionId ID of collection1532 * @param permissions permissions to change a property by the collection admin or token owner1533 * @example setTokenPropertyPermissions(1534 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1535 * )1536 * @returns true if extrinsic success otherwise false1537 */1538 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1539 const result = await this.helper.executeExtrinsic(1540 signer,1541 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1542 true,1543 );15441545 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1546 }15471548 /**1549 * Get token property permissions.1550 *1551 * @param collectionId ID of collection1552 * @param propertyKeys optionally filter the returned property permissions to only these keys1553 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1554 * @returns array of key-permission pairs1555 */1556 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1557 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1558 }15591560 /**1561 * Set token properties1562 *1563 * @param signer keyring of signer1564 * @param collectionId ID of collection1565 * @param tokenId ID of token1566 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1567 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1568 * @returns ```true``` if extrinsic success, otherwise ```false```1569 */1570 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1571 const result = await this.helper.executeExtrinsic(1572 signer,1573 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1574 true,1575 );15761577 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1578 }15791580 /**1581 * Get properties, metadata assigned to a token.1582 *1583 * @param collectionId ID of collection1584 * @param tokenId ID of token1585 * @param propertyKeys optionally filter the returned properties to only these keys1586 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1587 * @returns array of key-value pairs1588 */1589 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1590 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1591 }15921593 /**1594 * Delete the provided properties of a token1595 * @param signer keyring of signer1596 * @param collectionId ID of collection1597 * @param tokenId ID of token1598 * @param propertyKeys property keys to be deleted1599 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1600 * @returns ```true``` if extrinsic success, otherwise ```false```1601 */1602 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1603 const result = await this.helper.executeExtrinsic(1604 signer,1605 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1606 true,1607 );16081609 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1610 }16111612 /**1613 * Mint new collection1614 *1615 * @param signer keyring of signer1616 * @param collectionOptions basic collection options and properties1617 * @param mode NFT or RFT type of a collection1618 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1619 * @returns object of the created collection1620 */1621 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1622 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1623 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1624 for (const key of ['name', 'description', 'tokenPrefix']) {1625 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1626 }1627 const creationResult = await this.helper.executeExtrinsic(1628 signer,1629 'api.tx.unique.createCollectionEx', [collectionOptions],1630 true, // errorLabel,1631 );1632 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1633 }16341635 getCollectionObject(_collectionId: number): any {1636 return null;1637 }16381639 getTokenObject(_collectionId: number, _tokenId: number): any {1640 return null;1641 }16421643 /**1644 * Tells whether the given `owner` approves the `operator`.1645 * @param collectionId ID of collection1646 * @param owner owner address1647 * @param operator operator addrees1648 * @returns true if operator is enabled1649 */1650 async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1651 return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1652 }16531654 /** Sets or unsets the approval of a given operator.1655 * The `operator` is allowed to transfer all tokens of the `caller` on their behalf.1656 * @param operator Operator1657 * @param approved Should operator status be granted or revoked?1658 * @returns ```true``` if extrinsic success, otherwise ```false```1659 */1660 async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1661 const result = await this.helper.executeExtrinsic(1662 signer,1663 'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1664 true,1665 );1666 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1667 }1668}166916701671class NFTGroup extends NFTnRFT {1672 /**1673 * Get collection object1674 * @param collectionId ID of collection1675 * @example getCollectionObject(2);1676 * @returns instance of UniqueNFTCollection1677 */1678 getCollectionObject(collectionId: number): UniqueNFTCollection {1679 return new UniqueNFTCollection(collectionId, this.helper);1680 }16811682 /**1683 * Get token object1684 * @param collectionId ID of collection1685 * @param tokenId ID of token1686 * @example getTokenObject(10, 5);1687 * @returns instance of UniqueNFTToken1688 */1689 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1690 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1691 }16921693 /**1694 * Is token approved to transfer1695 * @param collectionId ID of collection1696 * @param tokenId ID of token1697 * @param toAccountObj address to be approved1698 * @returns ```true``` if extrinsic success, otherwise ```false```1699 */1700 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1701 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1702 }17031704 /**1705 * Changes the owner of the token.1706 *1707 * @param signer keyring of signer1708 * @param collectionId ID of collection1709 * @param tokenId ID of token1710 * @param addressObj address of a new owner1711 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1712 * @returns ```true``` if extrinsic success, otherwise ```false```1713 */1714 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1715 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1716 }17171718 /**1719 *1720 * Change ownership of a NFT on behalf of the owner.1721 *1722 * @param signer keyring of signer1723 * @param collectionId ID of collection1724 * @param tokenId ID of token1725 * @param fromAddressObj address on behalf of which the token will be sent1726 * @param toAddressObj new token owner1727 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1728 * @returns ```true``` if extrinsic success, otherwise ```false```1729 */1730 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1731 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1732 }17331734 /**1735 * Get tokens nested in the provided token1736 * @param collectionId ID of collection1737 * @param tokenId ID of token1738 * @param blockHashAt optionally query the data at the block with this hash1739 * @example getTokenChildren(10, 5);1740 * @returns tokens whose depth of nesting is <= 51741 */1742 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1743 let children;1744 if (typeof blockHashAt === 'undefined') {1745 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1746 } else {1747 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1748 }17491750 return children.toJSON().map((x: any) => ({collectionId: x.collection, tokenId: x.token}));1751 }17521753 /**1754 * Mint new collection1755 * @param signer keyring of signer1756 * @param collectionOptions Collection options1757 * @example1758 * mintCollection(aliceKeyring, {1759 * name: 'New',1760 * description: 'New collection',1761 * tokenPrefix: 'NEW',1762 * })1763 * @returns object of the created collection1764 */1765 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1766 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1767 }17681769 /**1770 * Mint new token1771 * @param signer keyring of signer1772 * @param data token data1773 * @returns created token object1774 */1775 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1776 const creationResult = await this.helper.executeExtrinsic(1777 signer,1778 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1779 NFT: {1780 properties: data.properties,1781 },1782 }],1783 true,1784 );1785 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1786 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1787 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1788 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1789 }17901791 /**1792 * Mint multiple NFT tokens1793 * @param signer keyring of signer1794 * @param collectionId ID of collection1795 * @param tokens array of tokens with owner and properties1796 * @example1797 * mintMultipleTokens(aliceKeyring, 10, [{1798 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1799 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1800 * },{1801 * owner: {Ethereum: "0x9F0583DbB855d..."},1802 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1803 * }]);1804 * @returns ```true``` if extrinsic success, otherwise ```false```1805 */1806 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: { owner: ICrossAccountId, properties?: IProperty[] }[]): Promise<UniqueNFToken[]> {1807 const creationResult = await this.helper.executeExtrinsic(1808 signer,1809 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1810 true,1811 );1812 const collection = this.getCollectionObject(collectionId);1813 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1814 }18151816 /**1817 * Mint multiple NFT tokens with one owner1818 * @param signer keyring of signer1819 * @param collectionId ID of collection1820 * @param owner tokens owner1821 * @param tokens array of tokens with owner and properties1822 * @example1823 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1824 * properties: [{1825 * key: "gender",1826 * value: "female",1827 * },{1828 * key: "age",1829 * value: "33",1830 * }],1831 * }]);1832 * @returns array of newly created tokens1833 */1834 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: { properties?: IProperty[] }[]): Promise<UniqueNFToken[]> {1835 const rawTokens = [];1836 for (const token of tokens) {1837 const raw = {NFT: {properties: token.properties}};1838 rawTokens.push(raw);1839 }1840 const creationResult = await this.helper.executeExtrinsic(1841 signer,1842 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1843 true,1844 );1845 const collection = this.getCollectionObject(collectionId);1846 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1847 }18481849 /**1850 * Set, change, or remove approved address to transfer the ownership of the NFT.1851 *1852 * @param signer keyring of signer1853 * @param collectionId ID of collection1854 * @param tokenId ID of token1855 * @param toAddressObj address to approve1856 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1857 * @returns ```true``` if extrinsic success, otherwise ```false```1858 */1859 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1860 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1861 }1862}186318641865class RFTGroup extends NFTnRFT {1866 /**1867 * Get collection object1868 * @param collectionId ID of collection1869 * @example getCollectionObject(2);1870 * @returns instance of UniqueRFTCollection1871 */1872 getCollectionObject(collectionId: number): UniqueRFTCollection {1873 return new UniqueRFTCollection(collectionId, this.helper);1874 }18751876 /**1877 * Get token object1878 * @param collectionId ID of collection1879 * @param tokenId ID of token1880 * @example getTokenObject(10, 5);1881 * @returns instance of UniqueNFTToken1882 */1883 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1884 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1885 }18861887 /**1888 * Get top 10 token owners with the largest number of pieces1889 * @param collectionId ID of collection1890 * @param tokenId ID of token1891 * @example getTokenTop10Owners(10, 5);1892 * @returns array of top 10 owners1893 */1894 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1895 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1896 }18971898 /**1899 * Get number of pieces owned by address1900 * @param collectionId ID of collection1901 * @param tokenId ID of token1902 * @param addressObj address token owner1903 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1904 * @returns number of pieces ownerd by address1905 */1906 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1907 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1908 }19091910 /**1911 * Transfer pieces of token to another address1912 * @param signer keyring of signer1913 * @param collectionId ID of collection1914 * @param tokenId ID of token1915 * @param addressObj address of a new owner1916 * @param amount number of pieces to be transfered1917 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1918 * @returns ```true``` if extrinsic success, otherwise ```false```1919 */1920 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1921 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1922 }19231924 /**1925 * Change ownership of some pieces of RFT on behalf of the owner.1926 * @param signer keyring of signer1927 * @param collectionId ID of collection1928 * @param tokenId ID of token1929 * @param fromAddressObj address on behalf of which the token will be sent1930 * @param toAddressObj new token owner1931 * @param amount number of pieces to be transfered1932 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1933 * @returns ```true``` if extrinsic success, otherwise ```false```1934 */1935 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1936 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1937 }19381939 /**1940 * Mint new collection1941 * @param signer keyring of signer1942 * @param collectionOptions Collection options1943 * @example1944 * mintCollection(aliceKeyring, {1945 * name: 'New',1946 * description: 'New collection',1947 * tokenPrefix: 'NEW',1948 * })1949 * @returns object of the created collection1950 */1951 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1952 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1953 }19541955 /**1956 * Mint new token1957 * @param signer keyring of signer1958 * @param data token data1959 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1960 * @returns created token object1961 */1962 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1963 const creationResult = await this.helper.executeExtrinsic(1964 signer,1965 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1966 ReFungible: {1967 pieces: data.pieces,1968 properties: data.properties,1969 },1970 }],1971 true,1972 );1973 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1974 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1975 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1976 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1977 }19781979 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: { owner: ICrossAccountId, pieces: bigint, properties?: IProperty[] }[]): Promise<UniqueRFToken[]> {1980 throw Error('Not implemented');1981 const creationResult = await this.helper.executeExtrinsic(1982 signer,1983 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1984 true, // `Unable to mint RFT tokens for ${label}`,1985 );1986 const collection = this.getCollectionObject(collectionId);1987 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1988 }19891990 /**1991 * Mint multiple RFT tokens with one owner1992 * @param signer keyring of signer1993 * @param collectionId ID of collection1994 * @param owner tokens owner1995 * @param tokens array of tokens with properties and pieces1996 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1997 * @returns array of newly created RFT tokens1998 */1999 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: { pieces: bigint, properties?: IProperty[] }[]): Promise<UniqueRFToken[]> {2000 const rawTokens = [];2001 for (const token of tokens) {2002 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};2003 rawTokens.push(raw);2004 }2005 const creationResult = await this.helper.executeExtrinsic(2006 signer,2007 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2008 true,2009 );2010 const collection = this.getCollectionObject(collectionId);2011 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));2012 }20132014 /**2015 * Destroys a concrete instance of RFT.2016 * @param signer keyring of signer2017 * @param collectionId ID of collection2018 * @param tokenId ID of token2019 * @param amount number of pieces to be burnt2020 * @example burnToken(aliceKeyring, 10, 5);2021 * @returns ```true``` if the extrinsic is successful, otherwise ```false```2022 */2023 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount = 1n): Promise<boolean> {2024 return await super.burnToken(signer, collectionId, tokenId, amount);2025 }20262027 /**2028 * Destroys a concrete instance of RFT on behalf of the owner.2029 * @param signer keyring of signer2030 * @param collectionId ID of collection2031 * @param tokenId ID of token2032 * @param fromAddressObj address on behalf of which the token will be burnt2033 * @param amount number of pieces to be burnt2034 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)2035 * @returns ```true``` if extrinsic success, otherwise ```false```2036 */2037 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {2038 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);2039 }20402041 /**2042 * Set, change, or remove approved address to transfer the ownership of the RFT.2043 *2044 * @param signer keyring of signer2045 * @param collectionId ID of collection2046 * @param tokenId ID of token2047 * @param toAddressObj address to approve2048 * @param amount number of pieces to be approved2049 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);2050 * @returns true if the token success, otherwise false2051 */2052 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {2053 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);2054 }20552056 /**2057 * Get total number of pieces2058 * @param collectionId ID of collection2059 * @param tokenId ID of token2060 * @example getTokenTotalPieces(10, 5);2061 * @returns number of pieces2062 */2063 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {2064 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();2065 }20662067 /**2068 * Change number of token pieces. Signer must be the owner of all token pieces.2069 * @param signer keyring of signer2070 * @param collectionId ID of collection2071 * @param tokenId ID of token2072 * @param amount new number of pieces2073 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);2074 * @returns true if the repartion was success, otherwise false2075 */2076 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {2077 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);2078 const repartitionResult = await this.helper.executeExtrinsic(2079 signer,2080 'api.tx.unique.repartition', [collectionId, tokenId, amount],2081 true,2082 );2083 if (currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');2084 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');2085 }2086}208720882089class FTGroup extends CollectionGroup {2090 /**2091 * Get collection object2092 * @param collectionId ID of collection2093 * @example getCollectionObject(2);2094 * @returns instance of UniqueFTCollection2095 */2096 getCollectionObject(collectionId: number): UniqueFTCollection {2097 return new UniqueFTCollection(collectionId, this.helper);2098 }20992100 /**2101 * Mint new fungible collection2102 * @param signer keyring of signer2103 * @param collectionOptions Collection options2104 * @param decimalPoints number of token decimals2105 * @example2106 * mintCollection(aliceKeyring, {2107 * name: 'New',2108 * description: 'New collection',2109 * tokenPrefix: 'NEW',2110 * }, 18)2111 * @returns newly created fungible collection2112 */2113 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {2114 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object2115 if (collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');2116 collectionOptions.mode = {fungible: decimalPoints};2117 for (const key of ['name', 'description', 'tokenPrefix']) {2118 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);2119 }2120 const creationResult = await this.helper.executeExtrinsic(2121 signer,2122 'api.tx.unique.createCollectionEx', [collectionOptions],2123 true,2124 );2125 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2126 }21272128 /**2129 * Mint tokens2130 * @param signer keyring of signer2131 * @param collectionId ID of collection2132 * @param owner address owner of new tokens2133 * @param amount amount of tokens to be meanted2134 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);2135 * @returns ```true``` if extrinsic success, otherwise ```false```2136 */2137 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2138 const creationResult = await this.helper.executeExtrinsic(2139 signer,2140 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2141 Fungible: {2142 value: amount,2143 },2144 }],2145 true, // `Unable to mint fungible tokens for ${label}`,2146 );2147 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2148 }21492150 /**2151 * Mint multiple Fungible tokens with one owner2152 * @param signer keyring of signer2153 * @param collectionId ID of collection2154 * @param owner tokens owner2155 * @param tokens array of tokens with properties and pieces2156 * @returns ```true``` if extrinsic success, otherwise ```false```2157 */2158 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: { value: bigint }[], owner: ICrossAccountId): Promise<boolean> {2159 const rawTokens = [];2160 for (const token of tokens) {2161 const raw = {Fungible: {Value: token.value}};2162 rawTokens.push(raw);2163 }2164 const creationResult = await this.helper.executeExtrinsic(2165 signer,2166 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2167 true,2168 );2169 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2170 }21712172 /**2173 * Get the top 10 owners with the largest balance for the Fungible collection2174 * @param collectionId ID of collection2175 * @example getTop10Owners(10);2176 * @returns array of ```ICrossAccountId```2177 */2178 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2179 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2180 }21812182 /**2183 * Get account balance2184 * @param collectionId ID of collection2185 * @param addressObj address of owner2186 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2187 * @returns amount of fungible tokens owned by address2188 */2189 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2190 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2191 }21922193 /**2194 * Transfer tokens to address2195 * @param signer keyring of signer2196 * @param collectionId ID of collection2197 * @param toAddressObj address recipient2198 * @param amount amount of tokens to be sent2199 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2200 * @returns ```true``` if extrinsic success, otherwise ```false```2201 */2202 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount = 1n) {2203 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2204 }22052206 /**2207 * Transfer some tokens on behalf of the owner.2208 * @param signer keyring of signer2209 * @param collectionId ID of collection2210 * @param fromAddressObj address on behalf of which tokens will be sent2211 * @param toAddressObj address where token to be sent2212 * @param amount number of tokens to be sent2213 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2214 * @returns ```true``` if extrinsic success, otherwise ```false```2215 */2216 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {2217 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2218 }22192220 /**2221 * Destroy some amount of tokens2222 * @param signer keyring of signer2223 * @param collectionId ID of collection2224 * @param amount amount of tokens to be destroyed2225 * @example burnTokens(aliceKeyring, 10, 1000n);2226 * @returns ```true``` if extrinsic success, otherwise ```false```2227 */2228 async burnTokens(signer: IKeyringPair, collectionId: number, amount = 1n): Promise<boolean> {2229 return await super.burnToken(signer, collectionId, 0, amount);2230 }22312232 /**2233 * Burn some tokens on behalf of the owner.2234 * @param signer keyring of signer2235 * @param collectionId ID of collection2236 * @param fromAddressObj address on behalf of which tokens will be burnt2237 * @param amount amount of tokens to be burnt2238 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2239 * @returns ```true``` if extrinsic success, otherwise ```false```2240 */2241 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {2242 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2243 }22442245 /**2246 * Get total collection supply2247 * @param collectionId2248 * @returns2249 */2250 async getTotalPieces(collectionId: number): Promise<bigint> {2251 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2252 }22532254 /**2255 * Set, change, or remove approved address to transfer tokens.2256 *2257 * @param signer keyring of signer2258 * @param collectionId ID of collection2259 * @param toAddressObj address to be approved2260 * @param amount amount of tokens to be approved2261 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2262 * @returns ```true``` if extrinsic success, otherwise ```false```2263 */2264 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount = 1n) {2265 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2266 }22672268 /**2269 * Get amount of fungible tokens approved to transfer2270 * @param collectionId ID of collection2271 * @param fromAddressObj owner of tokens2272 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2273 * @returns number of tokens approved for the transfer2274 */2275 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2276 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2277 }2278}227922802281class ChainGroup extends HelperGroup<ChainHelperBase> {2282 /**2283 * Get system properties of a chain2284 * @example getChainProperties();2285 * @returns ss58Format, token decimals, and token symbol2286 */2287 getChainProperties(): IChainProperties {2288 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2289 return {2290 ss58Format: properties.ss58Format.toJSON(),2291 tokenDecimals: properties.tokenDecimals.toJSON(),2292 tokenSymbol: properties.tokenSymbol.toJSON(),2293 };2294 }22952296 /**2297 * Get chain header2298 * @example getLatestBlockNumber();2299 * @returns the number of the last block2300 */2301 async getLatestBlockNumber(): Promise<number> {2302 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2303 }23042305 /**2306 * Get block hash by block number2307 * @param blockNumber number of block2308 * @example getBlockHashByNumber(12345);2309 * @returns hash of a block2310 */2311 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2312 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2313 if (blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2314 return blockHash;2315 }23162317 // TODO add docs2318 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2319 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2320 if (!blockHash) return null;2321 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2322 }23232324 /**2325 * Get latest relay block2326 * @returns {number} relay block2327 */2328 async getRelayBlockNumber(): Promise<bigint> {2329 const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2330 return BigInt(blockNumber);2331 }23322333 /**2334 * Get account nonce2335 * @param address substrate address2336 * @example getNonce("5GrwvaEF5zXb26Fz...");2337 * @returns number, account's nonce2338 */2339 async getNonce(address: TSubstrateAccount): Promise<number> {2340 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2341 }2342}23432344class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2345 /**2346 * Get substrate address balance2347 * @param address substrate address2348 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2349 * @returns amount of tokens on address2350 */2351 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2352 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2353 }23542355 /**2356 * Transfer tokens to substrate address2357 * @param signer keyring of signer2358 * @param address substrate address of a recipient2359 * @param amount amount of tokens to be transfered2360 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2361 * @returns ```true``` if extrinsic success, otherwise ```false```2362 */2363 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2364 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}`*/);23652366 let transfer = {from: null, to: null, amount: 0n} as any;2367 result.result.events.forEach(({event: {data, method, section}}) => {2368 if ((section === 'balances') && (method === 'Transfer')) {2369 transfer = {2370 from: this.helper.address.normalizeSubstrate(data[0]),2371 to: this.helper.address.normalizeSubstrate(data[1]),2372 amount: BigInt(data[2]),2373 };2374 }2375 });2376 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2377 && this.helper.address.normalizeSubstrate(address) === transfer.to2378 && BigInt(amount) === transfer.amount;2379 return isSuccess;2380 }23812382 /**2383 * Get full substrate balance including free, frozen, and reserved2384 * @param address substrate address2385 * @returns2386 */2387 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2388 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2389 return {free: accountInfo.free.toBigInt(), frozen: accountInfo.frozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2390 }23912392 /**2393 * Get total issuance2394 * @returns2395 */2396 async getTotalIssuance(): Promise<bigint> {2397 const total = (await this.helper.callRpc('api.query.balances.totalIssuance', []));2398 return total.toBigInt();2399 }24002401 async getLocked(address: TSubstrateAccount): Promise<{ id: string, amount: bigint, reason: string }[]> {2402 const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2403 return locks.map((lock: any) => ({id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons}));2404 }2405 async getFrozen(address: TSubstrateAccount): Promise<{ id: string, amount: bigint }[]> {2406 const locks = await this.helper.api!.query.balances.freezes(address);2407 return locks.map(lock => ({id: lock.id.toUtf8(), amount: lock.amount.toBigInt()}));2408 }2409}24102411class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2412 /**2413 * Get ethereum address balance2414 * @param address ethereum address2415 * @example getEthereum("0x9F0583DbB855d...")2416 * @returns amount of tokens on address2417 */2418 async getEthereum(address: TEthereumAccount): Promise<bigint> {2419 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2420 }24212422 /**2423 * Transfer tokens to address2424 * @param signer keyring of signer2425 * @param address Ethereum address of a recipient2426 * @param amount amount of tokens to be transfered2427 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2428 * @returns ```true``` if extrinsic success, otherwise ```false```2429 */2430 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2431 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);24322433 let transfer = {from: null, to: null, amount: 0n} as any;2434 result.result.events.forEach(({event: {data, method, section}}) => {2435 if ((section === 'balances') && (method === 'Transfer')) {2436 transfer = {2437 from: data[0].toString(),2438 to: data[1].toString(),2439 amount: BigInt(data[2]),2440 };2441 }2442 });2443 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2444 && address === transfer.to2445 && BigInt(amount) === transfer.amount;2446 return isSuccess;2447 }2448}24492450class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2451 subBalanceGroup: SubstrateBalanceGroup<T>;2452 ethBalanceGroup: EthereumBalanceGroup<T>;24532454 constructor(helper: T) {2455 super(helper);2456 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2457 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2458 }24592460 getCollectionCreationPrice(): bigint {2461 return 2n * this.getOneTokenNominal();2462 }2463 /**2464 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2465 * @example getOneTokenNominal()2466 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2467 */2468 getOneTokenNominal(): bigint {2469 const chainProperties = this.helper.chain.getChainProperties();2470 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2471 }24722473 /**2474 * Get substrate address balance2475 * @param address substrate address2476 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2477 * @returns amount of tokens on address2478 */2479 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2480 return this.subBalanceGroup.getSubstrate(address);2481 }24822483 /**2484 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2485 * @param address substrate address2486 * @returns2487 */2488 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2489 return this.subBalanceGroup.getSubstrateFull(address);2490 }24912492 /**2493 * Get total issuance2494 * @returns2495 */2496 getTotalIssuance(): Promise<bigint> {2497 return this.subBalanceGroup.getTotalIssuance();2498 }24992500 /**2501 * Get locked balances2502 * @param address substrate address2503 * @returns locked balances with reason via api.query.balances.locks2504 * @deprecated all the methods should switch to getFrozen2505 */2506 getLocked(address: TSubstrateAccount) {2507 return this.subBalanceGroup.getLocked(address);2508 }25092510 /**2511 * Get frozen balances2512 * @param address substrate address2513 * @returns frozen balances with id via api.query.balances.freezes2514 */2515 getFrozen(address: TSubstrateAccount) {2516 return this.subBalanceGroup.getFrozen(address);2517 }25182519 /**2520 * Get ethereum address balance2521 * @param address ethereum address2522 * @example getEthereum("0x9F0583DbB855d...")2523 * @returns amount of tokens on address2524 */2525 getEthereum(address: TEthereumAccount): Promise<bigint> {2526 return this.ethBalanceGroup.getEthereum(address);2527 }25282529 async setBalanceSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint, reservedAmount = 0n) {2530 await this.helper.executeExtrinsic(signer, 'api.tx.balances.setBalance', [address, amount, reservedAmount], true);2531 }25322533 /**2534 * Transfer tokens to substrate address2535 * @param signer keyring of signer2536 * @param address substrate address of a recipient2537 * @param amount amount of tokens to be transfered2538 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2539 * @returns ```true``` if extrinsic success, otherwise ```false```2540 */2541 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2542 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2543 }25442545 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2546 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);25472548 let transfer = {from: null, to: null, amount: 0n} as any;2549 result.result.events.forEach(({event: {data, method, section}}) => {2550 if ((section === 'balances') && (method === 'Transfer')) {2551 transfer = {2552 from: this.helper.address.normalizeSubstrate(data[0]),2553 to: this.helper.address.normalizeSubstrate(data[1]),2554 amount: BigInt(data[2]),2555 };2556 }2557 });2558 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2559 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2560 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2561 return isSuccess;2562 }25632564 /**2565 * Transfer tokens with the unlock period2566 * @param signer signers Keyring2567 * @param address Substrate address of recipient2568 * @param schedule Schedule params2569 * @example vestedTransfer(signer, recepient.address, 20000, 100, 10, 50 * nominal); // total amount of vested tokens will be 100 * 50 = 50002570 */2571 async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: { start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint }): Promise<void> {2572 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2573 const event = result.result.events2574 .find(e => e.event.section === 'vesting' &&2575 e.event.method === 'VestingScheduleAdded' &&2576 e.event.data[0].toHuman() === signer.address);2577 if (!event) throw Error('Cannot find transfer in events');2578 }25792580 /**2581 * Get schedule for recepient of vested transfer2582 * @param address Substrate address of recipient2583 * @returns2584 */2585 async getVestingSchedules(address: TSubstrateAccount): Promise<{ start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint }[]> {2586 const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2587 return schedule.map((schedule: any) => ({2588 start: BigInt(schedule.start),2589 period: BigInt(schedule.period),2590 periodCount: BigInt(schedule.periodCount),2591 perPeriod: BigInt(schedule.perPeriod),2592 }));2593 }25942595 /**2596 * Claim vested tokens2597 * @param signer signers Keyring2598 */2599 async claim(signer: TSigner) {2600 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2601 const event = result.result.events2602 .find(e => e.event.section === 'vesting' &&2603 e.event.method === 'Claimed' &&2604 e.event.data[0].toHuman() === signer.address);2605 if (!event) throw Error('Cannot find claim in events');2606 }2607}26082609class AddressGroup extends HelperGroup<ChainHelperBase> {2610 /**2611 * Normalizes the address to the specified ss58 format, by default ```42```.2612 * @param address substrate address2613 * @param ss58Format format for address conversion, by default ```42```2614 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2615 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2616 */2617 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2618 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2619 }26202621 /**2622 * Get address in the connected chain format2623 * @param address substrate address2624 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2625 * @returns address in chain format2626 */2627 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2628 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2629 }26302631 /**2632 * Get substrate mirror of an ethereum address2633 * @param ethAddress ethereum address2634 * @param toChainFormat false for normalized account2635 * @example ethToSubstrate('0x9F0583DbB855d...')2636 * @returns substrate mirror of a provided ethereum address2637 */2638 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat = false): TSubstrateAccount {2639 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2640 }26412642 /**2643 * Get ethereum mirror of a substrate address2644 * @param subAddress substrate account2645 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2646 * @returns ethereum mirror of a provided substrate address2647 */2648 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2649 return CrossAccountId.translateSubToEth(subAddress);2650 }26512652 /**2653 * Encode key to substrate address2654 * @param key key for encoding address2655 * @param ss58Format prefix for encoding to the address of the corresponding network2656 * @returns encoded substrate address2657 */2658 encodeSubstrateAddress(key: Uint8Array | string | bigint, ss58Format = 42): string {2659 const u8a: Uint8Array = typeof key === 'string'2660 ? hexToU8a(key)2661 : typeof key === 'bigint'2662 ? hexToU8a(key.toString(16))2663 : key;26642665 if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2666 throw new Error(`ss58Format is not valid, received ${typeofss58Format} "${ss58Format}"`);2667 }26682669 const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2670 if (!allowedDecodedLengths.includes(u8a.length)) {2671 throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2672 }26732674 const u8aPrefix = ss58Format < 642675 ? new Uint8Array([ss58Format])2676 : new Uint8Array([2677 ((ss58Format & 0xfc) >> 2) | 0x40,2678 (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2679 ]);26802681 const input = u8aConcat(u8aPrefix, u8a);26822683 return base58Encode(u8aConcat(2684 input,2685 blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2686 ));2687 }26882689 /**2690 * Restore substrate address from bigint representation2691 * @param number decimal representation of substrate address2692 * @returns substrate address2693 */2694 restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2695 if (this.helper.api === null) {2696 throw 'Not connected';2697 }2698 const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2699 if (res === undefined || res === null) {2700 throw 'Restore address error';2701 }2702 return res.toString();2703 }27042705 /**2706 * Convert etherium cross account id to substrate cross account id2707 * @param ethCrossAccount etherium cross account2708 * @returns substrate cross account id2709 */2710 convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2711 if (ethCrossAccount.sub === '0') {2712 return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2713 }27142715 const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2716 return {Substrate: ss58};2717 }27182719 paraSiblingSovereignAccount(paraid: number) {2720 // We are getting a *sibling* parachain sovereign account,2721 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2722 const siblingPrefix = '0x7369626c';27232724 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2725 const suffix = '000000000000000000000000000000000000000000000000';27262727 return siblingPrefix + encodedParaId + suffix;2728 }2729}27302731class StakingGroup extends HelperGroup<UniqueHelper> {2732 /**2733 * Stake tokens for App Promotion2734 * @param signer keyring of signer2735 * @param amountToStake amount of tokens to stake2736 * @param label extra label for log2737 * @returns2738 */2739 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2740 if (typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2741 const _stakeResult = await this.helper.executeExtrinsic(2742 signer, 'api.tx.appPromotion.stake',2743 [amountToStake], true,2744 );2745 // TODO extract info from stakeResult2746 return true;2747 }27482749 /**2750 * Unstake all staked tokens2751 * @param signer keyring of signer2752 * @param amountToUnstake amount of tokens to unstake2753 * @param label extra label for log2754 * @returns block hash where unstake happened2755 */2756 async unstakeAll(signer: TSigner, label?: string): Promise<string> {2757 if (typeof label === 'undefined') label = `${signer.address}`;2758 const unstakeResult = await this.helper.executeExtrinsic(2759 signer, 'api.tx.appPromotion.unstakeAll',2760 [], true,2761 );2762 return unstakeResult.blockHash;2763 }27642765 /**2766 * Unstake the part of a staked tokens2767 * @param signer keyring of signer2768 * @param amount amount of tokens to unstake2769 * @param label extra label for log2770 * @returns block hash where unstake happened2771 */2772 async unstakePartial(signer: TSigner, amount: bigint, label?: string): Promise<string> {2773 if (typeof label === 'undefined') label = `${signer.address}`;2774 const unstakeResult = await this.helper.executeExtrinsic(2775 signer, 'api.tx.appPromotion.unstakePartial',2776 [amount], true,2777 );2778 return unstakeResult.blockHash;2779 }27802781 /**2782 * Get total number of active stakes2783 * @param address substrate address2784 * @returns {number}2785 */2786 async getStakesNumber(address: ICrossAccountId): Promise<number> {2787 if ('Ethereum' in address) throw Error('only substrate address');2788 return (await this.helper.callRpc('api.query.appPromotion.stakesPerAccount', [address.Substrate])).toNumber();2789 }27902791 /**2792 * Get total staked amount for address2793 * @param address substrate or ethereum address2794 * @returns total staked amount2795 */2796 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2797 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2798 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2799 }28002801 /**2802 * Get total staked per block2803 * @param address substrate or ethereum address2804 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2805 */2806 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2807 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2808 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => ({2809 block: block.toBigInt(),2810 amount: amount.toBigInt(),2811 }));2812 }28132814 /**2815 * Get total pending unstake amount for address2816 * @param address substrate or ethereum address2817 * @returns total pending unstake amount2818 */2819 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2820 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2821 }28222823 /**2824 * Get pending unstake amount per block for address2825 * @param address substrate or ethereum address2826 * @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 block2827 */2828 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2829 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2830 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => ({2831 block: block.toBigInt(),2832 amount: amount.toBigInt(),2833 }));2834 return result;2835 }2836}28372838class SchedulerGroup extends HelperGroup<UniqueHelper> {2839 constructor(helper: UniqueHelper) {2840 super(helper);2841 }28422843 cancelScheduled(signer: TSigner, scheduledId: string) {2844 return this.helper.executeExtrinsic(2845 signer,2846 'api.tx.scheduler.cancelNamed',2847 [scheduledId],2848 true,2849 );2850 }28512852 changePriority(signer: TSigner, scheduledId: string, priority: number) {2853 return this.helper.executeExtrinsic(2854 signer,2855 'api.tx.scheduler.changeNamedPriority',2856 [scheduledId, priority],2857 true,2858 );2859 }28602861 scheduleAt<T extends UniqueHelper>(2862 executionBlockNumber: number,2863 options: ISchedulerOptions = {},2864 ) {2865 return this.schedule<T>('schedule', executionBlockNumber, options);2866 }28672868 scheduleAfter<T extends UniqueHelper>(2869 blocksBeforeExecution: number,2870 options: ISchedulerOptions = {},2871 ) {2872 return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2873 }28742875 schedule<T extends UniqueHelper>(2876 scheduleFn: 'schedule' | 'scheduleAfter',2877 blocksNum: number,2878 options: ISchedulerOptions = {},2879 ) {2880 // eslint-disable-next-line @typescript-eslint/naming-convention2881 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2882 return this.helper.clone(ScheduledHelperType, {2883 scheduleFn,2884 blocksNum,2885 options,2886 }) as T;2887 }2888}28892890class CollatorSelectionGroup extends HelperGroup<UniqueHelper> {2891 //todo:collator documentation2892 addInvulnerable(signer: TSigner, address: string) {2893 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.addInvulnerable', [address]);2894 }28952896 removeInvulnerable(signer: TSigner, address: string) {2897 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.removeInvulnerable', [address]);2898 }28992900 async getInvulnerables(): Promise<string[]> {2901 return (await this.helper.callRpc('api.query.collatorSelection.invulnerables')).map((x: any) => x.toHuman());2902 }29032904 /** and also total max invulnerables */2905 maxCollators(): number {2906 return (this.helper.getApi().consts.configuration.defaultCollatorSelectionMaxCollators.toJSON() as number);2907 }29082909 async getDesiredCollators(): Promise<number> {2910 return (await this.helper.callRpc('api.query.configuration.collatorSelectionDesiredCollatorsOverride')).toNumber();2911 }29122913 setLicenseBond(signer: TSigner, amount: bigint) {2914 return this.helper.executeExtrinsic(signer, 'api.tx.configuration.setCollatorSelectionLicenseBond', [amount]);2915 }29162917 async getLicenseBond(): Promise<bigint> {2918 return (await this.helper.callRpc('api.query.configuration.collatorSelectionLicenseBondOverride')).toBigInt();2919 }29202921 obtainLicense(signer: TSigner) {2922 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.getLicense', []);2923 }29242925 releaseLicense(signer: TSigner) {2926 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.releaseLicense', []);2927 }29282929 forceReleaseLicense(signer: TSigner, released: string) {2930 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.forceReleaseLicense', [released]);2931 }29322933 async hasLicense(address: string): Promise<bigint> {2934 return (await this.helper.callRpc('api.query.collatorSelection.licenseDepositOf', [address])).toBigInt();2935 }29362937 onboard(signer: TSigner) {2938 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.onboard', []);2939 }29402941 offboard(signer: TSigner) {2942 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.offboard', []);2943 }29442945 async getCandidates(): Promise<string[]> {2946 return (await this.helper.callRpc('api.query.collatorSelection.candidates')).map((x: any) => x.toHuman());2947 }2948}29492950class PreimageGroup extends HelperGroup<UniqueHelper> {2951 async getPreimageInfo(h256: string) {2952 return (await this.helper.callRpc('api.query.preimage.statusFor', [h256])).toJSON();2953 }29542955 /**2956 * Create a preimage with a hex or a byte array.2957 * @param signer keyring of the signer.2958 * @param bytes preimage encoded in hex or a byte array, e.g. an extrinsic call.2959 * @example await notePreimage(preimageMaker,2960 * helper.constructApiCall('api.tx.identity.forceInsertIdentities', [identitiesToAdd]).method.toHex()2961 * );2962 * @returns promise of extrinsic execution.2963 */2964 notePreimage(signer: TSigner, bytes: string | Uint8Array) {2965 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.notePreimage', [bytes]);2966 }29672968 /**2969 * Delete an existing preimage and return the deposit.2970 * @param signer keyring of the signer - either the owner or the preimage manager (sudo).2971 * @param h256 hash of the preimage.2972 * @returns promise of extrinsic execution.2973 */2974 unnotePreimage(signer: TSigner, h256: string) {2975 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unnotePreimage', [h256]);2976 }29772978 /**2979 * Request a preimage be uploaded to the chain without paying any fees or deposits.2980 * @param signer keyring of the signer - either the owner or the preimage manager (sudo).2981 * @param h256 hash of the preimage.2982 * @returns promise of extrinsic execution.2983 */2984 requestPreimage(signer: TSigner, h256: string) {2985 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.requestPreimage', [h256]);2986 }29872988 /**2989 * Clear a previously made request for a preimage.2990 * @param signer keyring of the signer - either the owner or the preimage manager (sudo).2991 * @param h256 hash of the preimage.2992 * @returns promise of extrinsic execution.2993 */2994 unrequestPreimage(signer: TSigner, h256: string) {2995 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unrequestPreimage', [h256]);2996 }2997}29982999class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {3000 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {3001 await this.helper.executeExtrinsic(3002 signer,3003 'api.tx.foreignAssets.registerForeignAsset',3004 [ownerAddress, location, metadata],3005 true,3006 );3007 }30083009 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {3010 await this.helper.executeExtrinsic(3011 signer,3012 'api.tx.foreignAssets.updateForeignAsset',3013 [foreignAssetId, location, metadata],3014 true,3015 );3016 }3017}30183019class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {3020 palletName: string;30213022 constructor(helper: T, palletName: string) {3023 super(helper);30243025 this.palletName = palletName;3026 }30273028 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {3029 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);3030 }30313032 async setSafeXcmVersion(signer: TSigner, version: number) {3033 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.forceDefaultXcmVersion`, [version], true);3034 }30353036 async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {3037 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);3038 }30393040 async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint, xcmVersion = 3) {3041 const destinationContent = {3042 parents: 0,3043 interior: {3044 X1: {3045 Parachain: destinationParaId,3046 },3047 },3048 };30493050 const beneficiaryContent = {3051 parents: 0,3052 interior: {3053 X1: {3054 AccountId32: {3055 network: 'Any',3056 id: targetAccount,3057 },3058 },3059 },3060 };30613062 const assetsContent = [3063 {3064 id: {3065 Concrete: {3066 parents: 0,3067 interior: 'Here',3068 },3069 },3070 fun: {3071 Fungible: amount,3072 },3073 },3074 ];30753076 let destination;3077 let beneficiary;3078 let assets;30793080 if (xcmVersion == 2) {3081 destination = {V1: destinationContent};3082 beneficiary = {V1: beneficiaryContent};3083 assets = {V1: assetsContent};30843085 } else if (xcmVersion == 3) {3086 destination = {V2: destinationContent};3087 beneficiary = {V2: beneficiaryContent};3088 assets = {V2: assetsContent};30893090 } else {3091 throw Error('Unknown XCM version: ' + xcmVersion);3092 }30933094 const feeAssetItem = 0;30953096 await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);3097 }30983099 async send(signer: IKeyringPair, destination: any, message: any) {3100 await this.helper.executeExtrinsic(3101 signer,3102 `api.tx.${this.palletName}.send`,3103 [3104 destination,3105 message,3106 ],3107 true,3108 );3109 }3110}31113112class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {3113 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {3114 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);3115 }31163117 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {3118 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);3119 }31203121 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {3122 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);3123 }3124}31253126class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {3127 async accounts(address: string, currencyId: any) {3128 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;3129 return BigInt(free);3130 }3131}31323133class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {3134 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {3135 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);3136 }31373138 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {3139 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);3140 }31413142 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {3143 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);3144 }31453146 async account(assetId: string | number, address: string) {3147 const accountAsset = (3148 await this.helper.callRpc('api.query.assets.account', [assetId, address])3149 ).toJSON()! as any;31503151 if (accountAsset !== null) {3152 return BigInt(accountAsset['balance']);3153 } else {3154 return null;3155 }3156 }3157}31583159class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {3160 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {3161 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);3162 }3163}31643165class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {3166 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {3167 const apiPrefix = 'api.tx.assetManager.';31683169 const registerTx = this.helper.constructApiCall(3170 apiPrefix + 'registerForeignAsset',3171 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],3172 );31733174 const setUnitsTx = this.helper.constructApiCall(3175 apiPrefix + 'setAssetUnitsPerSecond',3176 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],3177 );31783179 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);3180 const encodedProposal = batchCall?.method.toHex() || '';3181 return encodedProposal;3182 }31833184 async assetTypeId(location: any) {3185 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);3186 }3187}31883189class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {3190 notePreimagePallet: string;31913192 constructor(helper: MoonbeamHelper, options: { [key: string]: any } = {}) {3193 super(helper);3194 this.notePreimagePallet = options.notePreimagePallet;3195 }31963197 async notePreimage(signer: TSigner, encodedProposal: string) {3198 await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);3199 }32003201 externalProposeMajority(proposal: any) {3202 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);3203 }32043205 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {3206 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);3207 }32083209 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {3210 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);3211 }3212}32133214class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {3215 collective: string;32163217 constructor(helper: MoonbeamHelper, collective: string) {3218 super(helper);32193220 this.collective = collective;3221 }32223223 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {3224 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);3225 }32263227 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {3228 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);3229 }32303231 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {3232 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);3233 }32343235 async proposalCount() {3236 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));3237 }3238}32393240export type ChainHelperBaseConstructor = new (...args: any[]) => ChainHelperBase;3241export type UniqueHelperConstructor = new (...args: any[]) => UniqueHelper;32423243export class UniqueHelper extends ChainHelperBase {3244 balance: BalanceGroup<UniqueHelper>;3245 collection: CollectionGroup;3246 nft: NFTGroup;3247 rft: RFTGroup;3248 ft: FTGroup;3249 staking: StakingGroup;3250 scheduler: SchedulerGroup;3251 collatorSelection: CollatorSelectionGroup;3252 preimage: PreimageGroup;3253 foreignAssets: ForeignAssetsGroup;3254 xcm: XcmGroup<UniqueHelper>;3255 xTokens: XTokensGroup<UniqueHelper>;3256 tokens: TokensGroup<UniqueHelper>;32573258 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3259 super(logger, options.helperBase ?? UniqueHelper);32603261 this.balance = new BalanceGroup(this);3262 this.collection = new CollectionGroup(this);3263 this.nft = new NFTGroup(this);3264 this.rft = new RFTGroup(this);3265 this.ft = new FTGroup(this);3266 this.staking = new StakingGroup(this);3267 this.scheduler = new SchedulerGroup(this);3268 this.collatorSelection = new CollatorSelectionGroup(this);3269 this.preimage = new PreimageGroup(this);3270 this.foreignAssets = new ForeignAssetsGroup(this);3271 this.xcm = new XcmGroup(this, 'polkadotXcm');3272 this.xTokens = new XTokensGroup(this);3273 this.tokens = new TokensGroup(this);3274 }32753276 getSudo<T extends UniqueHelper>() {3277 // eslint-disable-next-line @typescript-eslint/naming-convention3278 const SudoHelperType = SudoHelper(this.helperBase);3279 return this.clone(SudoHelperType) as T;3280 }3281}32823283export class XcmChainHelper extends ChainHelperBase {3284 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {3285 const wsProvider = new WsProvider(wsEndpoint);3286 this.api = new ApiPromise({3287 provider: wsProvider,3288 });3289 await this.api.isReadyOrError;3290 this.network = await UniqueHelper.detectNetwork(this.api);3291 }3292}32933294export class RelayHelper extends XcmChainHelper {3295 balance: SubstrateBalanceGroup<RelayHelper>;3296 xcm: XcmGroup<RelayHelper>;32973298 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3299 super(logger, options.helperBase ?? RelayHelper);33003301 this.balance = new SubstrateBalanceGroup(this);3302 this.xcm = new XcmGroup(this, 'xcmPallet');3303 }3304}33053306export class WestmintHelper extends XcmChainHelper {3307 balance: SubstrateBalanceGroup<WestmintHelper>;3308 xcm: XcmGroup<WestmintHelper>;3309 assets: AssetsGroup<WestmintHelper>;3310 xTokens: XTokensGroup<WestmintHelper>;33113312 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3313 super(logger, options.helperBase ?? WestmintHelper);33143315 this.balance = new SubstrateBalanceGroup(this);3316 this.xcm = new XcmGroup(this, 'polkadotXcm');3317 this.assets = new AssetsGroup(this);3318 this.xTokens = new XTokensGroup(this);3319 }3320}33213322export class MoonbeamHelper extends XcmChainHelper {3323 balance: EthereumBalanceGroup<MoonbeamHelper>;3324 assetManager: MoonbeamAssetManagerGroup;3325 assets: AssetsGroup<MoonbeamHelper>;3326 xTokens: XTokensGroup<MoonbeamHelper>;3327 democracy: MoonbeamDemocracyGroup;3328 collective: {3329 council: MoonbeamCollectiveGroup,3330 techCommittee: MoonbeamCollectiveGroup,3331 };33323333 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3334 super(logger, options.helperBase ?? MoonbeamHelper);33353336 this.balance = new EthereumBalanceGroup(this);3337 this.assetManager = new MoonbeamAssetManagerGroup(this);3338 this.assets = new AssetsGroup(this);3339 this.xTokens = new XTokensGroup(this);3340 this.democracy = new MoonbeamDemocracyGroup(this, options);3341 this.collective = {3342 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),3343 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),3344 };3345 }3346}33473348export class AstarHelper extends XcmChainHelper {3349 balance: SubstrateBalanceGroup<AstarHelper>;3350 assets: AssetsGroup<AstarHelper>;3351 xcm: XcmGroup<AstarHelper>;33523353 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3354 super(logger, options.helperBase ?? AstarHelper);33553356 this.balance = new SubstrateBalanceGroup(this);3357 this.assets = new AssetsGroup(this);3358 this.xcm = new XcmGroup(this, 'polkadotXcm');3359 }33603361 getSudo<T extends UniqueHelper>() {3362 // eslint-disable-next-line @typescript-eslint/naming-convention3363 const SudoHelperType = SudoHelper(this.helperBase);3364 return this.clone(SudoHelperType) as T;3365 }3366}33673368export class AcalaHelper extends XcmChainHelper {3369 balance: SubstrateBalanceGroup<AcalaHelper>;3370 assetRegistry: AcalaAssetRegistryGroup;3371 xTokens: XTokensGroup<AcalaHelper>;3372 tokens: TokensGroup<AcalaHelper>;3373 xcm: XcmGroup<AcalaHelper>;33743375 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3376 super(logger, options.helperBase ?? AcalaHelper);33773378 this.balance = new SubstrateBalanceGroup(this);3379 this.assetRegistry = new AcalaAssetRegistryGroup(this);3380 this.xTokens = new XTokensGroup(this);3381 this.tokens = new TokensGroup(this);3382 this.xcm = new XcmGroup(this, 'polkadotXcm');3383 }33843385 getSudo<T extends AcalaHelper>() {3386 // eslint-disable-next-line @typescript-eslint/naming-convention3387 const SudoHelperType = SudoHelper(this.helperBase);3388 return this.clone(SudoHelperType) as T;3389 }3390}33913392// eslint-disable-next-line @typescript-eslint/naming-convention3393function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3394 return class extends Base {3395 scheduleFn: 'schedule' | 'scheduleAfter';3396 blocksNum: number;3397 options: ISchedulerOptions;33983399 constructor(...args: any[]) {3400 const logger = args[0] as ILogger;3401 const options = args[1] as {3402 scheduleFn: 'schedule' | 'scheduleAfter',3403 blocksNum: number,3404 options: ISchedulerOptions3405 };34063407 super(logger);34083409 this.scheduleFn = options.scheduleFn;3410 this.blocksNum = options.blocksNum;3411 this.options = options.options;3412 }34133414 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3415 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);34163417 const mandatorySchedArgs = [3418 this.blocksNum,3419 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3420 this.options.priority ?? null,3421 scheduledTx,3422 ];34233424 let schedArgs;3425 let scheduleFn;34263427 if (this.options.scheduledId) {3428 schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];34293430 if (this.scheduleFn == 'schedule') {3431 scheduleFn = 'scheduleNamed';3432 } else if (this.scheduleFn == 'scheduleAfter') {3433 scheduleFn = 'scheduleNamedAfter';3434 }3435 } else {3436 schedArgs = mandatorySchedArgs;3437 scheduleFn = this.scheduleFn;3438 }34393440 const extrinsic = 'api.tx.scheduler.' + scheduleFn;34413442 return super.executeExtrinsic(3443 sender,3444 extrinsic as any,3445 schedArgs,3446 expectSuccess,3447 );3448 }3449 };3450}34513452// eslint-disable-next-line @typescript-eslint/naming-convention3453function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3454 return class extends Base {3455 constructor(...args: any[]) {3456 super(...args);3457 }34583459 async executeExtrinsic(3460 sender: IKeyringPair,3461 extrinsic: string,3462 params: any[],3463 expectSuccess?: boolean,3464 options: Partial<SignerOptions> | null = null,3465 ): Promise<ITransactionResult> {3466 const call = this.constructApiCall(extrinsic, params);3467 const result = await super.executeExtrinsic(3468 sender,3469 'api.tx.sudo.sudo',3470 [call],3471 expectSuccess,3472 options,3473 );34743475 if (result.status === 'Fail') return result;34763477 const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;3478 if (data.isErr) {3479 if (data.asErr.isModule) {3480 const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;3481 const metaError = super.getApi()?.registry.findMetaError(error);3482 throw new Error(`${metaError.section}.${metaError.name}`);3483 } else if (data.asErr.isToken) {3484 throw new Error(`Token: ${data.asErr.asToken}`);3485 }3486 // May be [object Object] in case of unhandled non-unit enum3487 throw new Error(`Misc: ${data.asErr.toHuman()}`);3488 }3489 return result;3490 }3491 };3492}34933494export class UniqueBaseCollection {3495 helper: UniqueHelper;3496 collectionId: number;34973498 constructor(collectionId: number, uniqueHelper: UniqueHelper) {3499 this.collectionId = collectionId;3500 this.helper = uniqueHelper;3501 }35023503 async getData() {3504 return await this.helper.collection.getData(this.collectionId);3505 }35063507 async getLastTokenId() {3508 return await this.helper.collection.getLastTokenId(this.collectionId);3509 }35103511 async doesTokenExist(tokenId: number) {3512 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3513 }35143515 async getAdmins() {3516 return await this.helper.collection.getAdmins(this.collectionId);3517 }35183519 async getAllowList() {3520 return await this.helper.collection.getAllowList(this.collectionId);3521 }35223523 async getEffectiveLimits() {3524 return await this.helper.collection.getEffectiveLimits(this.collectionId);3525 }35263527 async getProperties(propertyKeys?: string[] | null) {3528 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3529 }35303531 async getPropertiesConsumedSpace() {3532 return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3533 }35343535 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3536 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3537 }35383539 async getOptions() {3540 return await this.helper.collection.getCollectionOptions(this.collectionId);3541 }35423543 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3544 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3545 }35463547 async confirmSponsorship(signer: TSigner) {3548 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3549 }35503551 async removeSponsor(signer: TSigner) {3552 return await this.helper.collection.removeSponsor(signer, this.collectionId);3553 }35543555 async setLimits(signer: TSigner, limits: ICollectionLimits) {3556 return await this.helper.collection.setLimits(signer, this.collectionId, limits);3557 }35583559 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3560 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3561 }35623563 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3564 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3565 }35663567 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3568 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3569 }35703571 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3572 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3573 }35743575 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3576 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3577 }35783579 async setProperties(signer: TSigner, properties: IProperty[]) {3580 return await this.helper.collection.setProperties(signer, this.collectionId, properties);3581 }35823583 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3584 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3585 }35863587 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3588 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3589 }35903591 async enableNesting(signer: TSigner, permissions: INestingPermissions) {3592 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3593 }35943595 async disableNesting(signer: TSigner) {3596 return await this.helper.collection.disableNesting(signer, this.collectionId);3597 }35983599 async burn(signer: TSigner) {3600 return await this.helper.collection.burn(signer, this.collectionId);3601 }36023603 scheduleAt<T extends UniqueHelper>(3604 executionBlockNumber: number,3605 options: ISchedulerOptions = {},3606 ) {3607 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3608 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3609 }36103611 scheduleAfter<T extends UniqueHelper>(3612 blocksBeforeExecution: number,3613 options: ISchedulerOptions = {},3614 ) {3615 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3616 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3617 }36183619 getSudo<T extends UniqueHelper>() {3620 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3621 }3622}362336243625export class UniqueNFTCollection extends UniqueBaseCollection {3626 getTokenObject(tokenId: number) {3627 return new UniqueNFToken(tokenId, this);3628 }36293630 async getTokensByAddress(addressObj: ICrossAccountId) {3631 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3632 }36333634 async getToken(tokenId: number, blockHashAt?: string) {3635 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3636 }36373638 async getTokenOwner(tokenId: number, blockHashAt?: string) {3639 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3640 }36413642 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3643 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3644 }36453646 async getTokenChildren(tokenId: number, blockHashAt?: string) {3647 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3648 }36493650 async getPropertyPermissions(propertyKeys: string[] | null = null) {3651 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3652 }36533654 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3655 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3656 }36573658 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3659 const api = this.helper.getApi();3660 const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();36613662 return (props! as any).consumedSpace;3663 }36643665 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3666 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3667 }36683669 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3670 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3671 }36723673 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3674 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3675 }36763677 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3678 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3679 }36803681 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3682 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3683 }36843685 async mintMultipleTokens(signer: TSigner, tokens: { owner: ICrossAccountId, properties?: IProperty[] }[]) {3686 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3687 }36883689 async burnToken(signer: TSigner, tokenId: number) {3690 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3691 }36923693 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3694 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3695 }36963697 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3698 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3699 }37003701 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3702 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3703 }37043705 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3706 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3707 }37083709 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3710 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3711 }37123713 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3714 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3715 }37163717 scheduleAt<T extends UniqueHelper>(3718 executionBlockNumber: number,3719 options: ISchedulerOptions = {},3720 ) {3721 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3722 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3723 }37243725 scheduleAfter<T extends UniqueHelper>(3726 blocksBeforeExecution: number,3727 options: ISchedulerOptions = {},3728 ) {3729 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3730 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3731 }37323733 getSudo<T extends UniqueHelper>() {3734 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3735 }3736}373737383739export class UniqueRFTCollection extends UniqueBaseCollection {3740 getTokenObject(tokenId: number) {3741 return new UniqueRFToken(tokenId, this);3742 }37433744 async getToken(tokenId: number, blockHashAt?: string) {3745 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3746 }37473748 async getTokenOwner(tokenId: number, blockHashAt?: string) {3749 return await this.helper.rft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3750 }37513752 async getTokensByAddress(addressObj: ICrossAccountId) {3753 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3754 }37553756 async getTop10TokenOwners(tokenId: number) {3757 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3758 }37593760 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3761 return await this.helper.rft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3762 }37633764 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3765 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3766 }37673768 async getTokenTotalPieces(tokenId: number) {3769 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3770 }37713772 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3773 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3774 }37753776 async getPropertyPermissions(propertyKeys: string[] | null = null) {3777 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3778 }37793780 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3781 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3782 }37833784 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3785 const api = this.helper.getApi();3786 const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();37873788 return (props! as any).consumedSpace;3789 }37903791 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount = 1n) {3792 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3793 }37943795 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {3796 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3797 }37983799 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {3800 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3801 }38023803 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3804 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3805 }38063807 async mintToken(signer: TSigner, pieces = 1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3808 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3809 }38103811 async mintMultipleTokens(signer: TSigner, tokens: { pieces: bigint, owner: ICrossAccountId, properties?: IProperty[] }[]) {3812 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3813 }38143815 async burnToken(signer: TSigner, tokenId: number, amount = 1n) {3816 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3817 }38183819 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n) {3820 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3821 }38223823 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3824 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3825 }38263827 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3828 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3829 }38303831 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3832 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3833 }38343835 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3836 return await this.helper.rft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3837 }38383839 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3840 return await this.helper.rft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3841 }38423843 scheduleAt<T extends UniqueHelper>(3844 executionBlockNumber: number,3845 options: ISchedulerOptions = {},3846 ) {3847 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3848 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3849 }38503851 scheduleAfter<T extends UniqueHelper>(3852 blocksBeforeExecution: number,3853 options: ISchedulerOptions = {},3854 ) {3855 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3856 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3857 }38583859 getSudo<T extends UniqueHelper>() {3860 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3861 }3862}386338643865export class UniqueFTCollection extends UniqueBaseCollection {3866 async getBalance(addressObj: ICrossAccountId) {3867 return await this.helper.ft.getBalance(this.collectionId, addressObj);3868 }38693870 async getTotalPieces() {3871 return await this.helper.ft.getTotalPieces(this.collectionId);3872 }38733874 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3875 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3876 }38773878 async getTop10Owners() {3879 return await this.helper.ft.getTop10Owners(this.collectionId);3880 }38813882 async mint(signer: TSigner, amount = 1n, owner: ICrossAccountId = {Substrate: signer.address}) {3883 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3884 }38853886 async mintWithOneOwner(signer: TSigner, tokens: { value: bigint }[], owner: ICrossAccountId = {Substrate: signer.address}) {3887 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3888 }38893890 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {3891 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3892 }38933894 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {3895 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3896 }38973898 async burnTokens(signer: TSigner, amount = 1n) {3899 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3900 }39013902 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount = 1n) {3903 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3904 }39053906 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {3907 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3908 }39093910 scheduleAt<T extends UniqueHelper>(3911 executionBlockNumber: number,3912 options: ISchedulerOptions = {},3913 ) {3914 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3915 return new UniqueFTCollection(this.collectionId, scheduledHelper);3916 }39173918 scheduleAfter<T extends UniqueHelper>(3919 blocksBeforeExecution: number,3920 options: ISchedulerOptions = {},3921 ) {3922 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3923 return new UniqueFTCollection(this.collectionId, scheduledHelper);3924 }39253926 getSudo<T extends UniqueHelper>() {3927 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3928 }3929}393039313932export class UniqueBaseToken {3933 collection: UniqueNFTCollection | UniqueRFTCollection;3934 collectionId: number;3935 tokenId: number;39363937 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3938 this.collection = collection;3939 this.collectionId = collection.collectionId;3940 this.tokenId = tokenId;3941 }39423943 async getNextSponsored(addressObj: ICrossAccountId) {3944 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3945 }39463947 async getProperties(propertyKeys?: string[] | null) {3948 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3949 }39503951 async getTokenPropertiesConsumedSpace() {3952 return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3953 }39543955 async setProperties(signer: TSigner, properties: IProperty[]) {3956 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3957 }39583959 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3960 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3961 }39623963 async doesExist() {3964 return await this.collection.doesTokenExist(this.tokenId);3965 }39663967 nestingAccount() {3968 return this.collection.helper.util.getTokenAccount(this);3969 }39703971 scheduleAt<T extends UniqueHelper>(3972 executionBlockNumber: number,3973 options: ISchedulerOptions = {},3974 ) {3975 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3976 return new UniqueBaseToken(this.tokenId, scheduledCollection);3977 }39783979 scheduleAfter<T extends UniqueHelper>(3980 blocksBeforeExecution: number,3981 options: ISchedulerOptions = {},3982 ) {3983 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3984 return new UniqueBaseToken(this.tokenId, scheduledCollection);3985 }39863987 getSudo<T extends UniqueHelper>() {3988 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3989 }3990}399139923993export class UniqueNFToken extends UniqueBaseToken {3994 collection: UniqueNFTCollection;39953996 constructor(tokenId: number, collection: UniqueNFTCollection) {3997 super(tokenId, collection);3998 this.collection = collection;3999 }40004001 async getData(blockHashAt?: string) {4002 return await this.collection.getToken(this.tokenId, blockHashAt);4003 }40044005 async getOwner(blockHashAt?: string) {4006 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);4007 }40084009 async getTopmostOwner(blockHashAt?: string) {4010 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);4011 }40124013 async getChildren(blockHashAt?: string) {4014 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);4015 }40164017 async nest(signer: TSigner, toTokenObj: IToken) {4018 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);4019 }40204021 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {4022 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);4023 }40244025 async transfer(signer: TSigner, addressObj: ICrossAccountId) {4026 return await this.collection.transferToken(signer, this.tokenId, addressObj);4027 }40284029 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {4030 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);4031 }40324033 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {4034 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);4035 }40364037 async isApproved(toAddressObj: ICrossAccountId) {4038 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);4039 }40404041 async burn(signer: TSigner) {4042 return await this.collection.burnToken(signer, this.tokenId);4043 }40444045 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {4046 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);4047 }40484049 scheduleAt<T extends UniqueHelper>(4050 executionBlockNumber: number,4051 options: ISchedulerOptions = {},4052 ) {4053 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);4054 return new UniqueNFToken(this.tokenId, scheduledCollection);4055 }40564057 scheduleAfter<T extends UniqueHelper>(4058 blocksBeforeExecution: number,4059 options: ISchedulerOptions = {},4060 ) {4061 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);4062 return new UniqueNFToken(this.tokenId, scheduledCollection);4063 }40644065 getSudo<T extends UniqueHelper>() {4066 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());4067 }4068}40694070export class UniqueRFToken extends UniqueBaseToken {4071 collection: UniqueRFTCollection;40724073 constructor(tokenId: number, collection: UniqueRFTCollection) {4074 super(tokenId, collection);4075 this.collection = collection;4076 }40774078 async getData(blockHashAt?: string) {4079 return await this.collection.getToken(this.tokenId, blockHashAt);4080 }40814082 async getOwner(blockHashAt?: string) {4083 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);4084 }40854086 async getTop10Owners() {4087 return await this.collection.getTop10TokenOwners(this.tokenId);4088 }40894090 async getTopmostOwner(blockHashAt?: string) {4091 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);4092 }40934094 async nest(signer: TSigner, toTokenObj: IToken) {4095 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);4096 }40974098 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {4099 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);4100 }41014102 async getBalance(addressObj: ICrossAccountId) {4103 return await this.collection.getTokenBalance(this.tokenId, addressObj);4104 }41054106 async getTotalPieces() {4107 return await this.collection.getTokenTotalPieces(this.tokenId);4108 }41094110 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {4111 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);4112 }41134114 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount = 1n) {4115 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);4116 }41174118 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {4119 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);4120 }41214122 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {4123 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);4124 }41254126 async repartition(signer: TSigner, amount: bigint) {4127 return await this.collection.repartitionToken(signer, this.tokenId, amount);4128 }41294130 async burn(signer: TSigner, amount = 1n) {4131 return await this.collection.burnToken(signer, this.tokenId, amount);4132 }41334134 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount = 1n) {4135 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);4136 }41374138 scheduleAt<T extends UniqueHelper>(4139 executionBlockNumber: number,4140 options: ISchedulerOptions = {},4141 ) {4142 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);4143 return new UniqueRFToken(this.tokenId, scheduledCollection);4144 }41454146 scheduleAfter<T extends UniqueHelper>(4147 blocksBeforeExecution: number,4148 options: ISchedulerOptions = {},4149 ) {4150 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);4151 return new UniqueRFToken(this.tokenId, scheduledCollection);4152 }41534154 getSudo<T extends UniqueHelper>() {4155 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());4156 }4157}