difftreelog
Merge pull request #915 from UniqueNetwork/test/additional-xcm-tests
in: master
Test/additional xcm tests
4 files changed
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -420,6 +420,100 @@
return capture;
}
+
+ makeXcmProgramWithdrawDeposit(beneficiary: Uint8Array, id: any, amount: bigint) {
+ return {
+ V2: [
+ {
+ WithdrawAsset: [
+ {
+ id,
+ fun: {
+ Fungible: amount,
+ },
+ },
+ ],
+ },
+ {
+ BuyExecution: {
+ fees: {
+ id,
+ fun: {
+ Fungible: amount,
+ },
+ },
+ weightLimit: 'Unlimited',
+ },
+ },
+ {
+ DepositAsset: {
+ assets: {
+ Wild: 'All',
+ },
+ maxAssets: 1,
+ beneficiary: {
+ parents: 0,
+ interior: {
+ X1: {
+ AccountId32: {
+ network: 'Any',
+ id: beneficiary,
+ },
+ },
+ },
+ },
+ },
+ },
+ ],
+ };
+ }
+
+ makeXcmProgramReserveAssetDeposited(beneficiary: Uint8Array, id: any, amount: bigint) {
+ return {
+ V2: [
+ {
+ ReserveAssetDeposited: [
+ {
+ id,
+ fun: {
+ Fungible: amount,
+ },
+ },
+ ],
+ },
+ {
+ BuyExecution: {
+ fees: {
+ id,
+ fun: {
+ Fungible: amount,
+ },
+ },
+ weightLimit: 'Unlimited',
+ },
+ },
+ {
+ DepositAsset: {
+ assets: {
+ Wild: 'All',
+ },
+ maxAssets: 1,
+ beneficiary: {
+ parents: 0,
+ interior: {
+ X1: {
+ AccountId32: {
+ network: 'Any',
+ id: beneficiary,
+ },
+ },
+ },
+ },
+ },
+ },
+ ],
+ };
+ }
}
class MoonbeamAccountGroup {
@@ -632,6 +726,19 @@
});
return promise;
}
+
+ async eventOutcome<EventT>(maxBlocksToWait: number, eventSection: string, eventMethod: string) {
+ const eventRecord = await this.event(maxBlocksToWait, eventSection, eventMethod);
+
+ if (eventRecord == null) {
+ return null;
+ }
+
+ const event = eventRecord!.event;
+ const outcome = event.data[1] as EventT;
+
+ return outcome;
+ }
}
class SessionGroup {
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 {ApiInterfaceEvents} from '@polkadot/api/types';11import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';12import {IKeyringPair} from '@polkadot/types/types';13import {hexToU8a} from '@polkadot/util/hex';14import {u8aConcat} from '@polkadot/util/u8a';15import {16 IApiListeners,17 IBlock,18 IEvent,19 IChainProperties,20 ICollectionCreationOptions,21 ICollectionLimits,22 ICollectionPermissions,23 ICrossAccountId,24 ICrossAccountIdLower,25 ILogger,26 INestingPermissions,27 IProperty,28 IStakingInfo,29 ISchedulerOptions,30 ISubstrateBalance,31 IToken,32 ITokenPropertyPermission,33 ITransactionResult,34 IUniqueHelperLog,35 TApiAllowedListeners,36 TEthereumAccount,37 TSigner,38 TSubstrateAccount,39 TNetworks,40 IForeignAssetMetadata,41 AcalaAssetMetadata,42 MoonbeamAssetInfo,43 DemocracyStandardAccountVote,44 IEthCrossAccountId,45} from './types';46import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';47import type {Vec} from '@polkadot/types-codec';48import {FrameSystemEventRecord} from '@polkadot/types/lookup';4950export class CrossAccountId implements ICrossAccountId {51 Substrate?: TSubstrateAccount;52 Ethereum?: TEthereumAccount;5354 constructor(account: ICrossAccountId) {55 if (account.Substrate) this.Substrate = account.Substrate;56 if (account.Ethereum) this.Ethereum = account.Ethereum;57 }5859 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {60 switch (domain) {61 case 'Substrate': return new CrossAccountId({Substrate: account.address});62 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();63 }64 }6566 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {67 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});68 }6970 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {71 return encodeAddress(decodeAddress(address), ss58Format);72 }7374 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {75 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});76 }7778 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {79 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);80 return this;81 }8283 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {84 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));85 }8687 toEthereum(): CrossAccountId {88 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});89 return this;90 }9192 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {93 return evmToAddress(address, ss58Format);94 }9596 toSubstrate(ss58Format?: number): CrossAccountId {97 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});98 return this;99 }100101 toLowerCase(): CrossAccountId {102 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();103 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();104 return this;105 }106}107108const nesting = {109 toChecksumAddress(address: string): string {110 if (typeof address === 'undefined') return '';111112 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);113114 address = address.toLowerCase().replace(/^0x/i,'');115 const addressHash = keccakAsHex(address).replace(/^0x/i,'');116 const checksumAddress = ['0x'];117118 for (let i = 0; i < address.length; i++) {119 // If ith character is 8 to f then make it uppercase120 if (parseInt(addressHash[i], 16) > 7) {121 checksumAddress.push(address[i].toUpperCase());122 } else {123 checksumAddress.push(address[i]);124 }125 }126 return checksumAddress.join('');127 },128 tokenIdToAddress(collectionId: number, tokenId: number) {129 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);130 },131};132133class UniqueUtil {134 static transactionStatus = {135 NOT_READY: 'NotReady',136 FAIL: 'Fail',137 SUCCESS: 'Success',138 };139140 static chainLogType = {141 EXTRINSIC: 'extrinsic',142 RPC: 'rpc',143 };144145 static getTokenAccount(token: IToken): CrossAccountId {146 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});147 }148149 static getTokenAddress(token: IToken): string {150 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);151 }152153 static getDefaultLogger(): ILogger {154 return {155 log(msg: any, level = 'INFO') {156 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));157 },158 level: {159 ERROR: 'ERROR',160 WARNING: 'WARNING',161 INFO: 'INFO',162 },163 };164 }165166 static vec2str(arr: string[] | number[]) {167 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');168 }169170 static str2vec(string: string) {171 if (typeof string !== 'string') return string;172 return Array.from(string).map(x => x.charCodeAt(0));173 }174175 static fromSeed(seed: string, ss58Format = 42) {176 const keyring = new Keyring({type: 'sr25519', ss58Format});177 return keyring.addFromUri(seed);178 }179180 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {181 if (creationResult.status !== this.transactionStatus.SUCCESS) {182 throw Error('Unable to create collection!');183 }184185 let collectionId = null;186 creationResult.result.events.forEach(({event: {data, method, section}}) => {187 if ((section === 'common') && (method === 'CollectionCreated')) {188 collectionId = parseInt(data[0].toString(), 10);189 }190 });191192 if (collectionId === null) {193 throw Error('No CollectionCreated event was found!');194 }195196 return collectionId;197 }198199 static extractTokensFromCreationResult(creationResult: ITransactionResult): {200 success: boolean,201 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],202 } {203 if (creationResult.status !== this.transactionStatus.SUCCESS) {204 throw Error('Unable to create tokens!');205 }206 let success = false;207 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];208 creationResult.result.events.forEach(({event: {data, method, section}}) => {209 if (method === 'ExtrinsicSuccess') {210 success = true;211 } else if ((section === 'common') && (method === 'ItemCreated')) {212 tokens.push({213 collectionId: parseInt(data[0].toString(), 10),214 tokenId: parseInt(data[1].toString(), 10),215 owner: data[2].toHuman(),216 amount: data[3].toBigInt(),217 });218 }219 });220 return {success, tokens};221 }222223 static extractTokensFromBurnResult(burnResult: ITransactionResult): {224 success: boolean,225 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],226 } {227 if (burnResult.status !== this.transactionStatus.SUCCESS) {228 throw Error('Unable to burn tokens!');229 }230 let success = false;231 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];232 burnResult.result.events.forEach(({event: {data, method, section}}) => {233 if (method === 'ExtrinsicSuccess') {234 success = true;235 } else if ((section === 'common') && (method === 'ItemDestroyed')) {236 tokens.push({237 collectionId: parseInt(data[0].toString(), 10),238 tokenId: parseInt(data[1].toString(), 10),239 owner: data[2].toHuman(),240 amount: data[3].toBigInt(),241 });242 }243 });244 return {success, tokens};245 }246247 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {248 let eventId = null;249 events.forEach(({event: {data, method, section}}) => {250 if ((section === expectedSection) && (method === expectedMethod)) {251 eventId = parseInt(data[0].toString(), 10);252 }253 });254255 if (eventId === null) {256 throw Error(`No ${expectedMethod} event was found!`);257 }258 return eventId === collectionId;259 }260261 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {262 const normalizeAddress = (address: string | ICrossAccountId) => {263 if(typeof address === 'string') return address;264 const obj = {} as any;265 Object.keys(address).forEach(k => {266 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];267 });268 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);269 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();270 return address;271 };272 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;273 events.forEach(({event: {data, method, section}}) => {274 if ((section === 'common') && (method === 'Transfer')) {275 const hData = (data as any).toJSON();276 transfer = {277 collectionId: hData[0],278 tokenId: hData[1],279 from: normalizeAddress(hData[2]),280 to: normalizeAddress(hData[3]),281 amount: BigInt(hData[4]),282 };283 }284 });285 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;286 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);287 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);288 isSuccess = isSuccess && amount === transfer.amount;289 return isSuccess;290 }291292 static bigIntToDecimals(number: bigint, decimals = 18) {293 const numberStr = number.toString();294 const dotPos = numberStr.length - decimals;295296 if (dotPos <= 0) {297 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;298 } else {299 const intPart = numberStr.substring(0, dotPos);300 const fractPart = numberStr.substring(dotPos);301 return intPart + '.' + fractPart;302 }303 }304}305306class UniqueEventHelper {307 private static extractIndex(index: any): [number, number] | string {308 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];309 return index.toJSON();310 }311312 private static extractSub(data: any, subTypes: any): {[key: string]: any} {313 let obj: any = {};314 let index = 0;315316 if (data.entries) {317 for(const [key, value] of data.entries()) {318 obj[key] = this.extractData(value, subTypes[index]);319 index++;320 }321 } else obj = data.toJSON();322323 return obj;324 }325326 private static toHuman(data: any) {327 return data && data.toHuman ? data.toHuman() : `${data}`;328 }329330 private static extractData(data: any, type: any): any {331 if(!type) return this.toHuman(data);332 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();333 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();334 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);335 return this.toHuman(data);336 }337338 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {339 const parsedEvents: IEvent[] = [];340341 events.forEach((record) => {342 const {event, phase} = record;343 const types = event.typeDef;344345 const eventData: IEvent = {346 section: event.section.toString(),347 method: event.method.toString(),348 index: this.extractIndex(event.index),349 data: [],350 phase: phase.toJSON(),351 };352353 event.data.forEach((val: any, index: number) => {354 eventData.data.push(this.extractData(val, types[index]));355 });356357 parsedEvents.push(eventData);358 });359360 return parsedEvents;361 }362}363364export class ChainHelperBase {365 helperBase: any;366367 transactionStatus = UniqueUtil.transactionStatus;368 chainLogType = UniqueUtil.chainLogType;369 util: typeof UniqueUtil;370 eventHelper: typeof UniqueEventHelper;371 logger: ILogger;372 api: ApiPromise | null;373 forcedNetwork: TNetworks | null;374 network: TNetworks | null;375 wsEndpoint: string | null;376 chainLog: IUniqueHelperLog[];377 children: ChainHelperBase[];378 address: AddressGroup;379 chain: ChainGroup;380381 constructor(logger?: ILogger, helperBase?: any) {382 this.helperBase = helperBase;383384 this.util = UniqueUtil;385 this.eventHelper = UniqueEventHelper;386 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();387 this.logger = logger;388 this.api = null;389 this.forcedNetwork = null;390 this.network = null;391 this.wsEndpoint = null;392 this.chainLog = [];393 this.children = [];394 this.address = new AddressGroup(this);395 this.chain = new ChainGroup(this);396 }397398 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {399 Object.setPrototypeOf(helperCls.prototype, this);400 const newHelper = new helperCls(this.logger, options);401402 newHelper.api = this.api;403 newHelper.network = this.network;404 newHelper.forceNetwork = this.forceNetwork;405406 this.children.push(newHelper);407408 return newHelper;409 }410411 getEndpoint(): string {412 if (this.wsEndpoint === null) throw Error('No connection was established');413 return this.wsEndpoint;414 }415416 getApi(): ApiPromise {417 if(this.api === null) throw Error('API not initialized');418 return this.api;419 }420421 async subscribeEvents(expectedEvents: {section: string, names: string[]}[]) {422 const collectedEvents: IEvent[] = [];423 const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {424 const ievents = this.eventHelper.extractEvents(events);425 ievents.forEach((event) => {426 expectedEvents.forEach((e => {427 if (event.section === e.section && e.names.includes(event.method)) {428 collectedEvents.push(event);429 }430 }));431 });432 });433 return {unsubscribe: unsubscribe as any, collectedEvents};434 }435436 clearChainLog(): void {437 this.chainLog = [];438 }439440 forceNetwork(value: TNetworks): void {441 this.forcedNetwork = value;442 }443444 async connect(wsEndpoint: string, listeners?: IApiListeners) {445 if (this.api !== null) throw Error('Already connected');446 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);447 this.wsEndpoint = wsEndpoint;448 this.api = api;449 this.network = network;450 }451452 async disconnect() {453 for (const child of this.children) {454 child.clearApi();455 }456457 if (this.api === null) return;458 await this.api.disconnect();459 this.clearApi();460 }461462 clearApi() {463 this.api = null;464 this.network = null;465 }466467 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {468 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;469 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];470471 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;472473 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;474 return 'opal';475 }476477 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {478 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});479 await api.isReady;480481 const network = await this.detectNetwork(api);482483 await api.disconnect();484485 return network;486 }487488 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{489 api: ApiPromise;490 network: TNetworks;491 }> {492 if(typeof network === 'undefined' || network === null) network = 'opal';493 const supportedRPC = {494 opal: {495 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,496 },497 quartz: {498 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,499 },500 unique: {501 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,502 },503 rococo: {},504 westend: {},505 moonbeam: {},506 moonriver: {},507 acala: {},508 karura: {},509 westmint: {},510 };511 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);512 const rpc = supportedRPC[network];513514 // TODO: investigate how to replace rpc in runtime515 // api._rpcCore.addUserInterfaces(rpc);516517 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});518519 await api.isReadyOrError;520521 if (typeof listeners === 'undefined') listeners = {};522 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {523 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;524 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);525 }526527 return {api, network};528 }529530 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {531 const {events, status} = data;532 if (status.isReady) {533 return this.transactionStatus.NOT_READY;534 }535 if (status.isBroadcast) {536 return this.transactionStatus.NOT_READY;537 }538 if (status.isInBlock || status.isFinalized) {539 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');540 if (errors.length > 0) {541 return this.transactionStatus.FAIL;542 }543 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {544 return this.transactionStatus.SUCCESS;545 }546 }547548 return this.transactionStatus.FAIL;549 }550551 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {552 const sign = (callback: any) => {553 if(options !== null) return transaction.signAndSend(sender, options, callback);554 return transaction.signAndSend(sender, callback);555 };556 // eslint-disable-next-line no-async-promise-executor557 return new Promise(async (resolve, reject) => {558 try {559 const unsub = await sign((result: any) => {560 const status = this.getTransactionStatus(result);561562 if (status === this.transactionStatus.SUCCESS) {563 this.logger.log(`${label} successful`);564 unsub();565 resolve({result, status, blockHash: result.status.asInBlock.toHuman()});566 } else if (status === this.transactionStatus.FAIL) {567 let moduleError = null;568569 if (result.hasOwnProperty('dispatchError')) {570 const dispatchError = result['dispatchError'];571572 if (dispatchError) {573 if (dispatchError.isModule) {574 const modErr = dispatchError.asModule;575 const errorMeta = dispatchError.registry.findMetaError(modErr);576577 moduleError = `${errorMeta.section}.${errorMeta.name}`;578 } else {579 moduleError = dispatchError.toHuman();580 }581 } else {582 this.logger.log(result, this.logger.level.ERROR);583 }584 }585586 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);587 unsub();588 reject({status, moduleError, result});589 }590 });591 } catch (e) {592 this.logger.log(e, this.logger.level.ERROR);593 reject(e);594 }595 });596 }597598 async signTransactionWithoutSending(signer: TSigner, tx: any) {599 const api = this.getApi();600 const signingInfo = await api.derive.tx.signingInfo(signer.address);601602 tx.sign(signer, {603 blockHash: api.genesisHash,604 genesisHash: api.genesisHash,605 runtimeVersion: api.runtimeVersion,606 nonce: signingInfo.nonce,607 });608609 return tx.toHex();610 }611612 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {613 const api = this.getApi();614 const signingInfo = await api.derive.tx.signingInfo(signer.address);615616 // We need to sign the tx because617 // unsigned transactions does not have an inclusion fee618 tx.sign(signer, {619 blockHash: api.genesisHash,620 genesisHash: api.genesisHash,621 runtimeVersion: api.runtimeVersion,622 nonce: signingInfo.nonce,623 });624625 if (len === null) {626 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;627 } else {628 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;629 }630 }631632 constructApiCall(apiCall: string, params: any[]) {633 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);634 let call = this.getApi() as any;635 for(const part of apiCall.slice(4).split('.')) {636 call = call[part];637 if (!call) {638 const advice = part.includes('_') ? ' Looks like it needs to be converted to camel case.' : '';639 throw Error(`Function ${part} of api call ${apiCall} not found.${advice}`);640 }641 }642 return call(...params);643 }644645 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {646 if(this.api === null) throw Error('API not initialized');647 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);648649 const startTime = (new Date()).getTime();650 let result: ITransactionResult;651 let events: IEvent[] = [];652 try {653 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;654 events = this.eventHelper.extractEvents(result.result.events);655 const errorEvent = events.find((event) => event.method == 'ExecutedFailed' || event.method == 'CreatedFailed');656 if (errorEvent)657 throw Error(errorEvent.method + ': ' + extrinsic);658 }659 catch(e) {660 if(!(e as object).hasOwnProperty('status')) throw e;661 result = e as ITransactionResult;662 }663664 const endTime = (new Date()).getTime();665666 const log = {667 executedAt: endTime,668 executionTime: endTime - startTime,669 type: this.chainLogType.EXTRINSIC,670 status: result.status,671 call: extrinsic,672 signer: this.getSignerAddress(sender),673 params,674 } as IUniqueHelperLog;675676 let errorMessage = '';677678 if(result.status !== this.transactionStatus.SUCCESS) {679 if (result.moduleError) {680 errorMessage = typeof result.moduleError === 'string'681 ? result.moduleError682 : `${Object.keys(result.moduleError)[0]}: ${Object.values(result.moduleError)[0]}`;683 log.moduleError = errorMessage;684 }685 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;686 }687 if(events.length > 0) log.events = events;688689 this.chainLog.push(log);690691 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {692 if (result.moduleError) throw Error(`${errorMessage}`);693 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));694 }695 return result;696 }697698 async callRpc(rpc: string, params?: any[]) {699 if(typeof params === 'undefined') params = [];700 if(this.api === null) throw Error('API not initialized');701 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);702703 const startTime = (new Date()).getTime();704 let result;705 let error = null;706 const log = {707 type: this.chainLogType.RPC,708 call: rpc,709 params,710 } as IUniqueHelperLog;711712 try {713 result = await this.constructApiCall(rpc, params);714 }715 catch(e) {716 error = e;717 }718719 const endTime = (new Date()).getTime();720721 log.executedAt = endTime;722 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';723 log.executionTime = endTime - startTime;724725 this.chainLog.push(log);726727 if(error !== null) throw error;728729 return result;730 }731732 getSignerAddress(signer: IKeyringPair | string): string {733 if(typeof signer === 'string') return signer;734 return signer.address;735 }736737 fetchAllPalletNames(): string[] {738 if(this.api === null) throw Error('API not initialized');739 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase()).sort();740 }741742 fetchMissingPalletNames(requiredPallets: string[]): string[] {743 const palletNames = this.fetchAllPalletNames();744 return requiredPallets.filter(p => !palletNames.includes(p));745 }746}747748749class HelperGroup<T extends ChainHelperBase> {750 helper: T;751752 constructor(uniqueHelper: T) {753 this.helper = uniqueHelper;754 }755}756757758class CollectionGroup extends HelperGroup<UniqueHelper> {759 /**760 * Get number of blocks when sponsored transaction is available.761 *762 * @param collectionId ID of collection763 * @param tokenId ID of token764 * @param addressObj address for which the sponsorship is checked765 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});766 * @returns number of blocks or null if sponsorship hasn't been set767 */768 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {769 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();770 }771772 /**773 * Get the number of created collections.774 *775 * @returns number of created collections776 */777 async getTotalCount(): Promise<number> {778 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();779 }780781 /**782 * Get information about the collection with additional data,783 * including the number of tokens it contains, its administrators,784 * the normalized address of the collection's owner, and decoded name and description.785 *786 * @param collectionId ID of collection787 * @example await getData(2)788 * @returns collection information object789 */790 async getData(collectionId: number): Promise<{791 id: number;792 name: string;793 description: string;794 tokensCount: number;795 admins: CrossAccountId[];796 normalizedOwner: TSubstrateAccount;797 raw: any798 } | null> {799 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);800 const humanCollection = collection.toHuman(), collectionData = {801 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],802 raw: humanCollection,803 } as any, jsonCollection = collection.toJSON();804 if (humanCollection === null) return null;805 collectionData.raw.limits = jsonCollection.limits;806 collectionData.raw.permissions = jsonCollection.permissions;807 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);808 for (const key of ['name', 'description']) {809 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);810 }811812 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))813 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)814 : 0;815 collectionData.admins = await this.getAdmins(collectionId);816817 return collectionData;818 }819820 /**821 * Get the addresses of the collection's administrators, optionally normalized.822 *823 * @param collectionId ID of collection824 * @param normalize whether to normalize the addresses to the default ss58 format825 * @example await getAdmins(1)826 * @returns array of administrators827 */828 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {829 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();830831 return normalize832 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())833 : admins;834 }835836 /**837 * Get the addresses added to the collection allow-list, optionally normalized.838 * @param collectionId ID of collection839 * @param normalize whether to normalize the addresses to the default ss58 format840 * @example await getAllowList(1)841 * @returns array of allow-listed addresses842 */843 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {844 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();845 return normalize846 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())847 : allowListed;848 }849850 /**851 * Get the effective limits of the collection instead of null for default values852 *853 * @param collectionId ID of collection854 * @example await getEffectiveLimits(2)855 * @returns object of collection limits856 */857 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {858 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();859 }860861 /**862 * Burns the collection if the signer has sufficient permissions and collection is empty.863 *864 * @param signer keyring of signer865 * @param collectionId ID of collection866 * @example await helper.collection.burn(aliceKeyring, 3);867 * @returns ```true``` if extrinsic success, otherwise ```false```868 */869 async burn(signer: TSigner, collectionId: number): Promise<boolean> {870 const result = await this.helper.executeExtrinsic(871 signer,872 'api.tx.unique.destroyCollection', [collectionId],873 true,874 );875876 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');877 }878879 /**880 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.881 *882 * @param signer keyring of signer883 * @param collectionId ID of collection884 * @param sponsorAddress Sponsor substrate address885 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")886 * @returns ```true``` if extrinsic success, otherwise ```false```887 */888 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {889 const result = await this.helper.executeExtrinsic(890 signer,891 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],892 true,893 );894895 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');896 }897898 /**899 * Confirms consent to sponsor the collection on behalf of the signer.900 *901 * @param signer keyring of signer902 * @param collectionId ID of collection903 * @example confirmSponsorship(aliceKeyring, 10)904 * @returns ```true``` if extrinsic success, otherwise ```false```905 */906 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {907 const result = await this.helper.executeExtrinsic(908 signer,909 'api.tx.unique.confirmSponsorship', [collectionId],910 true,911 );912913 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');914 }915916 /**917 * Removes the sponsor of a collection, regardless if it consented or not.918 *919 * @param signer keyring of signer920 * @param collectionId ID of collection921 * @example removeSponsor(aliceKeyring, 10)922 * @returns ```true``` if extrinsic success, otherwise ```false```923 */924 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {925 const result = await this.helper.executeExtrinsic(926 signer,927 'api.tx.unique.removeCollectionSponsor', [collectionId],928 true,929 );930931 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');932 }933934 /**935 * Sets the limits of the collection. At least one limit must be specified for a correct call.936 *937 * @param signer keyring of signer938 * @param collectionId ID of collection939 * @param limits collection limits object940 * @example941 * await setLimits(942 * aliceKeyring,943 * 10,944 * {945 * sponsorTransferTimeout: 0,946 * ownerCanDestroy: false947 * }948 * )949 * @returns ```true``` if extrinsic success, otherwise ```false```950 */951 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {952 const result = await this.helper.executeExtrinsic(953 signer,954 'api.tx.unique.setCollectionLimits', [collectionId, limits],955 true,956 );957958 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');959 }960961 /**962 * Changes the owner of the collection to the new Substrate address.963 *964 * @param signer keyring of signer965 * @param collectionId ID of collection966 * @param ownerAddress substrate address of new owner967 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")968 * @returns ```true``` if extrinsic success, otherwise ```false```969 */970 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {971 const result = await this.helper.executeExtrinsic(972 signer,973 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],974 true,975 );976977 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');978 }979980 /**981 * Adds a collection administrator.982 *983 * @param signer keyring of signer984 * @param collectionId ID of collection985 * @param adminAddressObj Administrator address (substrate or ethereum)986 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})987 * @returns ```true``` if extrinsic success, otherwise ```false```988 */989 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {990 const result = await this.helper.executeExtrinsic(991 signer,992 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],993 true,994 );995996 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');997 }998999 /**1000 * Removes a collection administrator.1001 *1002 * @param signer keyring of signer1003 * @param collectionId ID of collection1004 * @param adminAddressObj Administrator address (substrate or ethereum)1005 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})1006 * @returns ```true``` if extrinsic success, otherwise ```false```1007 */1008 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1009 const result = await this.helper.executeExtrinsic(1010 signer,1011 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],1012 true,1013 );10141015 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');1016 }10171018 /**1019 * Check if user is in allow list.1020 *1021 * @param collectionId ID of collection1022 * @param user Account to check1023 * @example await getAdmins(1)1024 * @returns is user in allow list1025 */1026 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {1027 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();1028 }10291030 /**1031 * Adds an address to allow list1032 * @param signer keyring of signer1033 * @param collectionId ID of collection1034 * @param addressObj address to add to the allow list1035 * @returns ```true``` if extrinsic success, otherwise ```false```1036 */1037 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1038 const result = await this.helper.executeExtrinsic(1039 signer,1040 'api.tx.unique.addToAllowList', [collectionId, addressObj],1041 true,1042 );10431044 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1045 }10461047 /**1048 * Removes an address from allow list1049 *1050 * @param signer keyring of signer1051 * @param collectionId ID of collection1052 * @param addressObj address to remove from the allow list1053 * @returns ```true``` if extrinsic success, otherwise ```false```1054 */1055 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1056 const result = await this.helper.executeExtrinsic(1057 signer,1058 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1059 true,1060 );10611062 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1063 }10641065 /**1066 * Sets onchain permissions for selected collection.1067 *1068 * @param signer keyring of signer1069 * @param collectionId ID of collection1070 * @param permissions collection permissions object1071 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1072 * @returns ```true``` if extrinsic success, otherwise ```false```1073 */1074 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1075 const result = await this.helper.executeExtrinsic(1076 signer,1077 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1078 true,1079 );10801081 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1082 }10831084 /**1085 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1086 *1087 * @param signer keyring of signer1088 * @param collectionId ID of collection1089 * @param permissions nesting permissions object1090 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1091 * @returns ```true``` if extrinsic success, otherwise ```false```1092 */1093 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1094 return await this.setPermissions(signer, collectionId, {nesting: permissions});1095 }10961097 /**1098 * Disables nesting for selected collection.1099 *1100 * @param signer keyring of signer1101 * @param collectionId ID of collection1102 * @example disableNesting(aliceKeyring, 10);1103 * @returns ```true``` if extrinsic success, otherwise ```false```1104 */1105 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1106 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1107 }11081109 /**1110 * Sets onchain properties to the collection.1111 *1112 * @param signer keyring of signer1113 * @param collectionId ID of collection1114 * @param properties array of property objects1115 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1116 * @returns ```true``` if extrinsic success, otherwise ```false```1117 */1118 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1119 const result = await this.helper.executeExtrinsic(1120 signer,1121 'api.tx.unique.setCollectionProperties', [collectionId, properties],1122 true,1123 );11241125 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1126 }11271128 /**1129 * Get collection properties.1130 *1131 * @param collectionId ID of collection1132 * @param propertyKeys optionally filter the returned properties to only these keys1133 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1134 * @returns array of key-value pairs1135 */1136 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1137 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1138 }11391140 async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1141 const api = this.helper.getApi();1142 const props = (await api.query.common.collectionProperties(collectionId)).toJSON();11431144 return (props! as any).consumedSpace;1145 }11461147 async getCollectionOptions(collectionId: number) {1148 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1149 }11501151 /**1152 * Deletes onchain properties from the collection.1153 *1154 * @param signer keyring of signer1155 * @param collectionId ID of collection1156 * @param propertyKeys array of property keys to delete1157 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1158 * @returns ```true``` if extrinsic success, otherwise ```false```1159 */1160 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1161 const result = await this.helper.executeExtrinsic(1162 signer,1163 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1164 true,1165 );11661167 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1168 }11691170 /**1171 * Changes the owner of the token.1172 *1173 * @param signer keyring of signer1174 * @param collectionId ID of collection1175 * @param tokenId ID of token1176 * @param addressObj address of a new owner1177 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1178 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1179 * @returns true if the token success, otherwise false1180 */1181 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1182 const result = await this.helper.executeExtrinsic(1183 signer,1184 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1185 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1186 );11871188 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1189 }11901191 /**1192 *1193 * Change ownership of a token(s) on behalf of the owner.1194 *1195 * @param signer keyring of signer1196 * @param collectionId ID of collection1197 * @param tokenId ID of token1198 * @param fromAddressObj address on behalf of which the token will be sent1199 * @param toAddressObj new token owner1200 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1201 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1202 * @returns true if the token success, otherwise false1203 */1204 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1205 const result = await this.helper.executeExtrinsic(1206 signer,1207 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1208 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1209 );1210 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1211 }12121213 /**1214 *1215 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1216 *1217 * @param signer keyring of signer1218 * @param collectionId ID of collection1219 * @param tokenId ID of token1220 * @param amount amount of tokens to be burned. For NFT must be set to 1n1221 * @example burnToken(aliceKeyring, 10, 5);1222 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1223 */1224 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1225 const burnResult = await this.helper.executeExtrinsic(1226 signer,1227 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1228 true, // `Unable to burn token for ${label}`,1229 );1230 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1231 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1232 return burnedTokens.success;1233 }12341235 /**1236 * Destroys a concrete instance of NFT on behalf of the owner1237 *1238 * @param signer keyring of signer1239 * @param collectionId ID of collection1240 * @param tokenId ID of token1241 * @param fromAddressObj address on behalf of which the token will be burnt1242 * @param amount amount of tokens to be burned. For NFT must be set to 1n1243 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1244 * @returns ```true``` if extrinsic success, otherwise ```false```1245 */1246 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1247 const burnResult = await this.helper.executeExtrinsic(1248 signer,1249 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1250 true, // `Unable to burn token from for ${label}`,1251 );1252 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1253 return burnedTokens.success && burnedTokens.tokens.length > 0;1254 }12551256 /**1257 * Set, change, or remove approved address to transfer the ownership of the NFT.1258 *1259 * @param signer keyring of signer1260 * @param collectionId ID of collection1261 * @param tokenId ID of token1262 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1263 * @param amount amount of token to be approved. For NFT must be set to 1n1264 * @returns ```true``` if extrinsic success, otherwise ```false```1265 */1266 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1267 const approveResult = await this.helper.executeExtrinsic(1268 signer,1269 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1270 true, // `Unable to approve token for ${label}`,1271 );12721273 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1274 }12751276 /**1277 * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1278 *1279 * @param signer keyring of signer1280 * @param collectionId ID of collection1281 * @param tokenId ID of token1282 * @param fromAddressObj Signer's Ethereum address containing her tokens1283 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1284 * @param amount amount of token to be approved. For NFT must be set to 1n1285 * @returns ```true``` if extrinsic success, otherwise ```false```1286 */1287 async approveTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1288 const approveResult = await this.helper.executeExtrinsic(1289 signer,1290 'api.tx.unique.approveFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1291 true, // `Unable to approve token for ${label}`,1292 );12931294 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1295 }12961297 /**1298 * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1299 *1300 * @param signer keyring of signer1301 * @param collectionId ID of collection1302 * @param tokenId ID of token1303 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1304 * @param amount amount of token to be approved. For NFT must be set to 1n1305 * @returns ```true``` if extrinsic success, otherwise ```false```1306 */1307 async approveTokenFromEth(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1308 const ethMirror = CrossAccountId.fromKeyring(signer).toEthereum();1309 return await this.approveTokenFrom(signer, collectionId, tokenId, ethMirror, toAddressObj, amount);1310 }13111312 /**1313 * Get the amount of token pieces approved to transfer or burn. Normally 0.1314 *1315 * @param collectionId ID of collection1316 * @param tokenId ID of token1317 * @param toAccountObj address which is approved to use token pieces1318 * @param fromAccountObj address which may have allowed the use of its owned tokens1319 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1320 * @returns number of approved to transfer pieces1321 */1322 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1323 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1324 }13251326 /**1327 * Get the last created token ID in a collection1328 *1329 * @param collectionId ID of collection1330 * @example getLastTokenId(10);1331 * @returns id of the last created token1332 */1333 async getLastTokenId(collectionId: number): Promise<number> {1334 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1335 }13361337 /**1338 * Check if token exists1339 *1340 * @param collectionId ID of collection1341 * @param tokenId ID of token1342 * @example doesTokenExist(10, 20);1343 * @returns true if the token exists, otherwise false1344 */1345 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1346 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1347 }1348}13491350class NFTnRFT extends CollectionGroup {1351 /**1352 * Get tokens owned by account1353 *1354 * @param collectionId ID of collection1355 * @param addressObj tokens owner1356 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1357 * @returns array of token ids owned by account1358 */1359 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1360 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1361 }13621363 /**1364 * Get token data1365 *1366 * @param collectionId ID of collection1367 * @param tokenId ID of token1368 * @param propertyKeys optionally filter the token properties to only these keys1369 * @param blockHashAt optionally query the data at some block with this hash1370 * @example getToken(10, 5);1371 * @returns human readable token data1372 */1373 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1374 properties: IProperty[];1375 owner: CrossAccountId;1376 normalizedOwner: CrossAccountId;1377 }| null> {1378 let tokenData;1379 if(typeof blockHashAt === 'undefined') {1380 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1381 }1382 else {1383 if(propertyKeys.length == 0) {1384 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1385 if(!collection) return null;1386 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1387 }1388 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1389 }1390 tokenData = tokenData.toHuman();1391 if (tokenData === null || tokenData.owner === null) return null;1392 const owner = {} as any;1393 for (const key of Object.keys(tokenData.owner)) {1394 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1395 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1396 : tokenData.owner[key];1397 }1398 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1399 return tokenData;1400 }14011402 /**1403 * Get token's owner1404 * @param collectionId ID of collection1405 * @param tokenId ID of token1406 * @param blockHashAt optionally query the data at the block with this hash1407 * @example getTokenOwner(10, 5);1408 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1409 */1410 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1411 let owner;1412 if (typeof blockHashAt === 'undefined') {1413 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1414 } else {1415 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1416 }1417 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1418 }14191420 /**1421 * Recursively find the address that owns the token1422 * @param collectionId ID of collection1423 * @param tokenId ID of token1424 * @param blockHashAt1425 * @example getTokenTopmostOwner(10, 5);1426 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1427 */1428 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1429 let owner;1430 if (typeof blockHashAt === 'undefined') {1431 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1432 } else {1433 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1434 }14351436 if (owner === null) return null;14371438 return owner.toHuman();1439 }14401441 /**1442 * Nest one token into another1443 * @param signer keyring of signer1444 * @param tokenObj token to be nested1445 * @param rootTokenObj token to be parent1446 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1447 * @returns ```true``` if extrinsic success, otherwise ```false```1448 */1449 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1450 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1451 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1452 if(!result) {1453 throw Error('Unable to nest token!');1454 }1455 return result;1456 }14571458 /**1459 * Remove token from nested state1460 * @param signer keyring of signer1461 * @param tokenObj token to unnest1462 * @param rootTokenObj parent of a token1463 * @param toAddressObj address of a new token owner1464 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1465 * @returns ```true``` if extrinsic success, otherwise ```false```1466 */1467 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1468 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1469 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1470 if(!result) {1471 throw Error('Unable to unnest token!');1472 }1473 return result;1474 }14751476 /**1477 * Set permissions to change token properties1478 *1479 * @param signer keyring of signer1480 * @param collectionId ID of collection1481 * @param permissions permissions to change a property by the collection admin or token owner1482 * @example setTokenPropertyPermissions(1483 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1484 * )1485 * @returns true if extrinsic success otherwise false1486 */1487 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1488 const result = await this.helper.executeExtrinsic(1489 signer,1490 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1491 true,1492 );14931494 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1495 }14961497 /**1498 * Get token property permissions.1499 *1500 * @param collectionId ID of collection1501 * @param propertyKeys optionally filter the returned property permissions to only these keys1502 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1503 * @returns array of key-permission pairs1504 */1505 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1506 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1507 }15081509 /**1510 * Set token properties1511 *1512 * @param signer keyring of signer1513 * @param collectionId ID of collection1514 * @param tokenId ID of token1515 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1516 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1517 * @returns ```true``` if extrinsic success, otherwise ```false```1518 */1519 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1520 const result = await this.helper.executeExtrinsic(1521 signer,1522 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1523 true,1524 );15251526 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1527 }15281529 /**1530 * Get properties, metadata assigned to a token.1531 *1532 * @param collectionId ID of collection1533 * @param tokenId ID of token1534 * @param propertyKeys optionally filter the returned properties to only these keys1535 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1536 * @returns array of key-value pairs1537 */1538 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1539 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1540 }15411542 /**1543 * Delete the provided properties of a token1544 * @param signer keyring of signer1545 * @param collectionId ID of collection1546 * @param tokenId ID of token1547 * @param propertyKeys property keys to be deleted1548 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1549 * @returns ```true``` if extrinsic success, otherwise ```false```1550 */1551 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1552 const result = await this.helper.executeExtrinsic(1553 signer,1554 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1555 true,1556 );15571558 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1559 }15601561 /**1562 * Mint new collection1563 *1564 * @param signer keyring of signer1565 * @param collectionOptions basic collection options and properties1566 * @param mode NFT or RFT type of a collection1567 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1568 * @returns object of the created collection1569 */1570 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1571 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1572 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1573 for (const key of ['name', 'description', 'tokenPrefix']) {1574 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);1575 }1576 const creationResult = await this.helper.executeExtrinsic(1577 signer,1578 'api.tx.unique.createCollectionEx', [collectionOptions],1579 true, // errorLabel,1580 );1581 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1582 }15831584 getCollectionObject(_collectionId: number): any {1585 return null;1586 }15871588 getTokenObject(_collectionId: number, _tokenId: number): any {1589 return null;1590 }15911592 /**1593 * Tells whether the given `owner` approves the `operator`.1594 * @param collectionId ID of collection1595 * @param owner owner address1596 * @param operator operator addrees1597 * @returns true if operator is enabled1598 */1599 async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1600 return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1601 }16021603 /** Sets or unsets the approval of a given operator.1604 * The `operator` is allowed to transfer all tokens of the `caller` on their behalf.1605 * @param operator Operator1606 * @param approved Should operator status be granted or revoked?1607 * @returns ```true``` if extrinsic success, otherwise ```false```1608 */1609 async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1610 const result = await this.helper.executeExtrinsic(1611 signer,1612 'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1613 true,1614 );1615 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1616 }1617}161816191620class NFTGroup extends NFTnRFT {1621 /**1622 * Get collection object1623 * @param collectionId ID of collection1624 * @example getCollectionObject(2);1625 * @returns instance of UniqueNFTCollection1626 */1627 getCollectionObject(collectionId: number): UniqueNFTCollection {1628 return new UniqueNFTCollection(collectionId, this.helper);1629 }16301631 /**1632 * Get token object1633 * @param collectionId ID of collection1634 * @param tokenId ID of token1635 * @example getTokenObject(10, 5);1636 * @returns instance of UniqueNFTToken1637 */1638 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1639 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1640 }16411642 /**1643 * Is token approved to transfer1644 * @param collectionId ID of collection1645 * @param tokenId ID of token1646 * @param toAccountObj address to be approved1647 * @returns ```true``` if extrinsic success, otherwise ```false```1648 */1649 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1650 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1651 }16521653 /**1654 * Changes the owner of the token.1655 *1656 * @param signer keyring of signer1657 * @param collectionId ID of collection1658 * @param tokenId ID of token1659 * @param addressObj address of a new owner1660 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1661 * @returns ```true``` if extrinsic success, otherwise ```false```1662 */1663 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1664 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1665 }16661667 /**1668 *1669 * Change ownership of a NFT on behalf of the owner.1670 *1671 * @param signer keyring of signer1672 * @param collectionId ID of collection1673 * @param tokenId ID of token1674 * @param fromAddressObj address on behalf of which the token will be sent1675 * @param toAddressObj new token owner1676 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1677 * @returns ```true``` if extrinsic success, otherwise ```false```1678 */1679 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1680 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1681 }16821683 /**1684 * Get tokens nested in the provided token1685 * @param collectionId ID of collection1686 * @param tokenId ID of token1687 * @param blockHashAt optionally query the data at the block with this hash1688 * @example getTokenChildren(10, 5);1689 * @returns tokens whose depth of nesting is <= 51690 */1691 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1692 let children;1693 if(typeof blockHashAt === 'undefined') {1694 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1695 } else {1696 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1697 }16981699 return children.toJSON().map((x: any) => {1700 return {collectionId: x.collection, tokenId: x.token};1701 });1702 }17031704 /**1705 * Mint new collection1706 * @param signer keyring of signer1707 * @param collectionOptions Collection options1708 * @example1709 * mintCollection(aliceKeyring, {1710 * name: 'New',1711 * description: 'New collection',1712 * tokenPrefix: 'NEW',1713 * })1714 * @returns object of the created collection1715 */1716 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1717 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1718 }17191720 /**1721 * Mint new token1722 * @param signer keyring of signer1723 * @param data token data1724 * @returns created token object1725 */1726 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1727 const creationResult = await this.helper.executeExtrinsic(1728 signer,1729 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1730 nft: {1731 properties: data.properties,1732 },1733 }],1734 true,1735 );1736 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1737 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1738 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1739 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1740 }17411742 /**1743 * Mint multiple NFT tokens1744 * @param signer keyring of signer1745 * @param collectionId ID of collection1746 * @param tokens array of tokens with owner and properties1747 * @example1748 * mintMultipleTokens(aliceKeyring, 10, [{1749 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1750 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1751 * },{1752 * owner: {Ethereum: "0x9F0583DbB855d..."},1753 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1754 * }]);1755 * @returns ```true``` if extrinsic success, otherwise ```false```1756 */1757 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1758 const creationResult = await this.helper.executeExtrinsic(1759 signer,1760 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1761 true,1762 );1763 const collection = this.getCollectionObject(collectionId);1764 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1765 }17661767 /**1768 * Mint multiple NFT tokens with one owner1769 * @param signer keyring of signer1770 * @param collectionId ID of collection1771 * @param owner tokens owner1772 * @param tokens array of tokens with owner and properties1773 * @example1774 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1775 * properties: [{1776 * key: "gender",1777 * value: "female",1778 * },{1779 * key: "age",1780 * value: "33",1781 * }],1782 * }]);1783 * @returns array of newly created tokens1784 */1785 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1786 const rawTokens = [];1787 for (const token of tokens) {1788 const raw = {NFT: {properties: token.properties}};1789 rawTokens.push(raw);1790 }1791 const creationResult = await this.helper.executeExtrinsic(1792 signer,1793 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1794 true,1795 );1796 const collection = this.getCollectionObject(collectionId);1797 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1798 }17991800 /**1801 * Set, change, or remove approved address to transfer the ownership of the NFT.1802 *1803 * @param signer keyring of signer1804 * @param collectionId ID of collection1805 * @param tokenId ID of token1806 * @param toAddressObj address to approve1807 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1808 * @returns ```true``` if extrinsic success, otherwise ```false```1809 */1810 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1811 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1812 }1813}181418151816class RFTGroup extends NFTnRFT {1817 /**1818 * Get collection object1819 * @param collectionId ID of collection1820 * @example getCollectionObject(2);1821 * @returns instance of UniqueRFTCollection1822 */1823 getCollectionObject(collectionId: number): UniqueRFTCollection {1824 return new UniqueRFTCollection(collectionId, this.helper);1825 }18261827 /**1828 * Get token object1829 * @param collectionId ID of collection1830 * @param tokenId ID of token1831 * @example getTokenObject(10, 5);1832 * @returns instance of UniqueNFTToken1833 */1834 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1835 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1836 }18371838 /**1839 * Get top 10 token owners with the largest number of pieces1840 * @param collectionId ID of collection1841 * @param tokenId ID of token1842 * @example getTokenTop10Owners(10, 5);1843 * @returns array of top 10 owners1844 */1845 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1846 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1847 }18481849 /**1850 * Get number of pieces owned by address1851 * @param collectionId ID of collection1852 * @param tokenId ID of token1853 * @param addressObj address token owner1854 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1855 * @returns number of pieces ownerd by address1856 */1857 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1858 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1859 }18601861 /**1862 * Transfer pieces of token to another address1863 * @param signer keyring of signer1864 * @param collectionId ID of collection1865 * @param tokenId ID of token1866 * @param addressObj address of a new owner1867 * @param amount number of pieces to be transfered1868 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1869 * @returns ```true``` if extrinsic success, otherwise ```false```1870 */1871 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1872 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1873 }18741875 /**1876 * Change ownership of some pieces of RFT on behalf of the owner.1877 * @param signer keyring of signer1878 * @param collectionId ID of collection1879 * @param tokenId ID of token1880 * @param fromAddressObj address on behalf of which the token will be sent1881 * @param toAddressObj new token owner1882 * @param amount number of pieces to be transfered1883 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1884 * @returns ```true``` if extrinsic success, otherwise ```false```1885 */1886 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1887 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1888 }18891890 /**1891 * Mint new collection1892 * @param signer keyring of signer1893 * @param collectionOptions Collection options1894 * @example1895 * mintCollection(aliceKeyring, {1896 * name: 'New',1897 * description: 'New collection',1898 * tokenPrefix: 'NEW',1899 * })1900 * @returns object of the created collection1901 */1902 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1903 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1904 }19051906 /**1907 * Mint new token1908 * @param signer keyring of signer1909 * @param data token data1910 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1911 * @returns created token object1912 */1913 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1914 const creationResult = await this.helper.executeExtrinsic(1915 signer,1916 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1917 refungible: {1918 pieces: data.pieces,1919 properties: data.properties,1920 },1921 }],1922 true,1923 );1924 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1925 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1926 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1927 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1928 }19291930 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1931 throw Error('Not implemented');1932 const creationResult = await this.helper.executeExtrinsic(1933 signer,1934 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1935 true, // `Unable to mint RFT tokens for ${label}`,1936 );1937 const collection = this.getCollectionObject(collectionId);1938 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1939 }19401941 /**1942 * Mint multiple RFT tokens with one owner1943 * @param signer keyring of signer1944 * @param collectionId ID of collection1945 * @param owner tokens owner1946 * @param tokens array of tokens with properties and pieces1947 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1948 * @returns array of newly created RFT tokens1949 */1950 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1951 const rawTokens = [];1952 for (const token of tokens) {1953 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1954 rawTokens.push(raw);1955 }1956 const creationResult = await this.helper.executeExtrinsic(1957 signer,1958 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1959 true,1960 );1961 const collection = this.getCollectionObject(collectionId);1962 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1963 }19641965 /**1966 * Destroys a concrete instance of RFT.1967 * @param signer keyring of signer1968 * @param collectionId ID of collection1969 * @param tokenId ID of token1970 * @param amount number of pieces to be burnt1971 * @example burnToken(aliceKeyring, 10, 5);1972 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1973 */1974 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1975 return await super.burnToken(signer, collectionId, tokenId, amount);1976 }19771978 /**1979 * Destroys a concrete instance of RFT on behalf of the owner.1980 * @param signer keyring of signer1981 * @param collectionId ID of collection1982 * @param tokenId ID of token1983 * @param fromAddressObj address on behalf of which the token will be burnt1984 * @param amount number of pieces to be burnt1985 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1986 * @returns ```true``` if extrinsic success, otherwise ```false```1987 */1988 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1989 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1990 }19911992 /**1993 * Set, change, or remove approved address to transfer the ownership of the RFT.1994 *1995 * @param signer keyring of signer1996 * @param collectionId ID of collection1997 * @param tokenId ID of token1998 * @param toAddressObj address to approve1999 * @param amount number of pieces to be approved2000 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);2001 * @returns true if the token success, otherwise false2002 */2003 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2004 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);2005 }20062007 /**2008 * Get total number of pieces2009 * @param collectionId ID of collection2010 * @param tokenId ID of token2011 * @example getTokenTotalPieces(10, 5);2012 * @returns number of pieces2013 */2014 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {2015 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();2016 }20172018 /**2019 * Change number of token pieces. Signer must be the owner of all token pieces.2020 * @param signer keyring of signer2021 * @param collectionId ID of collection2022 * @param tokenId ID of token2023 * @param amount new number of pieces2024 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);2025 * @returns true if the repartion was success, otherwise false2026 */2027 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {2028 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);2029 const repartitionResult = await this.helper.executeExtrinsic(2030 signer,2031 'api.tx.unique.repartition', [collectionId, tokenId, amount],2032 true,2033 );2034 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');2035 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');2036 }2037}203820392040class FTGroup extends CollectionGroup {2041 /**2042 * Get collection object2043 * @param collectionId ID of collection2044 * @example getCollectionObject(2);2045 * @returns instance of UniqueFTCollection2046 */2047 getCollectionObject(collectionId: number): UniqueFTCollection {2048 return new UniqueFTCollection(collectionId, this.helper);2049 }20502051 /**2052 * Mint new fungible collection2053 * @param signer keyring of signer2054 * @param collectionOptions Collection options2055 * @param decimalPoints number of token decimals2056 * @example2057 * mintCollection(aliceKeyring, {2058 * name: 'New',2059 * description: 'New collection',2060 * tokenPrefix: 'NEW',2061 * }, 18)2062 * @returns newly created fungible collection2063 */2064 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {2065 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object2066 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');2067 collectionOptions.mode = {fungible: decimalPoints};2068 for (const key of ['name', 'description', 'tokenPrefix']) {2069 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);2070 }2071 const creationResult = await this.helper.executeExtrinsic(2072 signer,2073 'api.tx.unique.createCollectionEx', [collectionOptions],2074 true,2075 );2076 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2077 }20782079 /**2080 * Mint tokens2081 * @param signer keyring of signer2082 * @param collectionId ID of collection2083 * @param owner address owner of new tokens2084 * @param amount amount of tokens to be meanted2085 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);2086 * @returns ```true``` if extrinsic success, otherwise ```false```2087 */2088 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2089 const creationResult = await this.helper.executeExtrinsic(2090 signer,2091 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2092 fungible: {2093 value: amount,2094 },2095 }],2096 true, // `Unable to mint fungible tokens for ${label}`,2097 );2098 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2099 }21002101 /**2102 * Mint multiple Fungible tokens with one owner2103 * @param signer keyring of signer2104 * @param collectionId ID of collection2105 * @param owner tokens owner2106 * @param tokens array of tokens with properties and pieces2107 * @returns ```true``` if extrinsic success, otherwise ```false```2108 */2109 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {2110 const rawTokens = [];2111 for (const token of tokens) {2112 const raw = {Fungible: {Value: token.value}};2113 rawTokens.push(raw);2114 }2115 const creationResult = await this.helper.executeExtrinsic(2116 signer,2117 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2118 true,2119 );2120 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2121 }21222123 /**2124 * Get the top 10 owners with the largest balance for the Fungible collection2125 * @param collectionId ID of collection2126 * @example getTop10Owners(10);2127 * @returns array of ```ICrossAccountId```2128 */2129 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2130 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2131 }21322133 /**2134 * Get account balance2135 * @param collectionId ID of collection2136 * @param addressObj address of owner2137 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2138 * @returns amount of fungible tokens owned by address2139 */2140 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2141 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2142 }21432144 /**2145 * Transfer tokens to address2146 * @param signer keyring of signer2147 * @param collectionId ID of collection2148 * @param toAddressObj address recipient2149 * @param amount amount of tokens to be sent2150 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2151 * @returns ```true``` if extrinsic success, otherwise ```false```2152 */2153 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2154 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2155 }21562157 /**2158 * Transfer some tokens on behalf of the owner.2159 * @param signer keyring of signer2160 * @param collectionId ID of collection2161 * @param fromAddressObj address on behalf of which tokens will be sent2162 * @param toAddressObj address where token to be sent2163 * @param amount number of tokens to be sent2164 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2165 * @returns ```true``` if extrinsic success, otherwise ```false```2166 */2167 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2168 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2169 }21702171 /**2172 * Destroy some amount of tokens2173 * @param signer keyring of signer2174 * @param collectionId ID of collection2175 * @param amount amount of tokens to be destroyed2176 * @example burnTokens(aliceKeyring, 10, 1000n);2177 * @returns ```true``` if extrinsic success, otherwise ```false```2178 */2179 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2180 return await super.burnToken(signer, collectionId, 0, amount);2181 }21822183 /**2184 * Burn some tokens on behalf of the owner.2185 * @param signer keyring of signer2186 * @param collectionId ID of collection2187 * @param fromAddressObj address on behalf of which tokens will be burnt2188 * @param amount amount of tokens to be burnt2189 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2190 * @returns ```true``` if extrinsic success, otherwise ```false```2191 */2192 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2193 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2194 }21952196 /**2197 * Get total collection supply2198 * @param collectionId2199 * @returns2200 */2201 async getTotalPieces(collectionId: number): Promise<bigint> {2202 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2203 }22042205 /**2206 * Set, change, or remove approved address to transfer tokens.2207 *2208 * @param signer keyring of signer2209 * @param collectionId ID of collection2210 * @param toAddressObj address to be approved2211 * @param amount amount of tokens to be approved2212 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2213 * @returns ```true``` if extrinsic success, otherwise ```false```2214 */2215 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2216 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2217 }22182219 /**2220 * Get amount of fungible tokens approved to transfer2221 * @param collectionId ID of collection2222 * @param fromAddressObj owner of tokens2223 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2224 * @returns number of tokens approved for the transfer2225 */2226 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2227 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2228 }2229}223022312232class ChainGroup extends HelperGroup<ChainHelperBase> {2233 /**2234 * Get system properties of a chain2235 * @example getChainProperties();2236 * @returns ss58Format, token decimals, and token symbol2237 */2238 getChainProperties(): IChainProperties {2239 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2240 return {2241 ss58Format: properties.ss58Format.toJSON(),2242 tokenDecimals: properties.tokenDecimals.toJSON(),2243 tokenSymbol: properties.tokenSymbol.toJSON(),2244 };2245 }22462247 /**2248 * Get chain header2249 * @example getLatestBlockNumber();2250 * @returns the number of the last block2251 */2252 async getLatestBlockNumber(): Promise<number> {2253 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2254 }22552256 /**2257 * Get block hash by block number2258 * @param blockNumber number of block2259 * @example getBlockHashByNumber(12345);2260 * @returns hash of a block2261 */2262 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2263 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2264 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2265 return blockHash;2266 }22672268 // TODO add docs2269 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2270 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2271 if (!blockHash) return null;2272 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2273 }22742275 /**2276 * Get latest relay block2277 * @returns {number} relay block2278 */2279 async getRelayBlockNumber(): Promise<bigint> {2280 const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2281 return BigInt(blockNumber);2282 }22832284 /**2285 * Get account nonce2286 * @param address substrate address2287 * @example getNonce("5GrwvaEF5zXb26Fz...");2288 * @returns number, account's nonce2289 */2290 async getNonce(address: TSubstrateAccount): Promise<number> {2291 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2292 }2293}22942295class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2296 /**2297 * Get substrate address balance2298 * @param address substrate address2299 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2300 * @returns amount of tokens on address2301 */2302 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2303 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2304 }23052306 /**2307 * Transfer tokens to substrate address2308 * @param signer keyring of signer2309 * @param address substrate address of a recipient2310 * @param amount amount of tokens to be transfered2311 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2312 * @returns ```true``` if extrinsic success, otherwise ```false```2313 */2314 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2315 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}`*/);23162317 let transfer = {from: null, to: null, amount: 0n} as any;2318 result.result.events.forEach(({event: {data, method, section}}) => {2319 if ((section === 'balances') && (method === 'Transfer')) {2320 transfer = {2321 from: this.helper.address.normalizeSubstrate(data[0]),2322 to: this.helper.address.normalizeSubstrate(data[1]),2323 amount: BigInt(data[2]),2324 };2325 }2326 });2327 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2328 && this.helper.address.normalizeSubstrate(address) === transfer.to2329 && BigInt(amount) === transfer.amount;2330 return isSuccess;2331 }23322333 /**2334 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2335 * @param address substrate address2336 * @returns2337 */2338 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2339 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2340 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2341 }23422343 async getLocked(address: TSubstrateAccount): Promise<[{id: string, amount: bigint, reason: string}]> {2344 const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2345 return locks.map((lock: any) => {return {id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons};});2346 }2347}23482349class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2350 /**2351 * Get ethereum address balance2352 * @param address ethereum address2353 * @example getEthereum("0x9F0583DbB855d...")2354 * @returns amount of tokens on address2355 */2356 async getEthereum(address: TEthereumAccount): Promise<bigint> {2357 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2358 }23592360 /**2361 * Transfer tokens to address2362 * @param signer keyring of signer2363 * @param address Ethereum address of a recipient2364 * @param amount amount of tokens to be transfered2365 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2366 * @returns ```true``` if extrinsic success, otherwise ```false```2367 */2368 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2369 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);23702371 let transfer = {from: null, to: null, amount: 0n} as any;2372 result.result.events.forEach(({event: {data, method, section}}) => {2373 if ((section === 'balances') && (method === 'Transfer')) {2374 transfer = {2375 from: data[0].toString(),2376 to: data[1].toString(),2377 amount: BigInt(data[2]),2378 };2379 }2380 });2381 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2382 && address === transfer.to2383 && BigInt(amount) === transfer.amount;2384 return isSuccess;2385 }2386}23872388class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2389 subBalanceGroup: SubstrateBalanceGroup<T>;2390 ethBalanceGroup: EthereumBalanceGroup<T>;23912392 constructor(helper: T) {2393 super(helper);2394 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2395 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2396 }23972398 getCollectionCreationPrice(): bigint {2399 return 2n * this.getOneTokenNominal();2400 }2401 /**2402 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2403 * @example getOneTokenNominal()2404 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2405 */2406 getOneTokenNominal(): bigint {2407 const chainProperties = this.helper.chain.getChainProperties();2408 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2409 }24102411 /**2412 * Get substrate address balance2413 * @param address substrate address2414 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2415 * @returns amount of tokens on address2416 */2417 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2418 return this.subBalanceGroup.getSubstrate(address);2419 }24202421 /**2422 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2423 * @param address substrate address2424 * @returns2425 */2426 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2427 return this.subBalanceGroup.getSubstrateFull(address);2428 }24292430 /**2431 * Get locked balances2432 * @param address substrate address2433 * @returns locked balances with reason via api.query.balances.locks2434 */2435 getLocked(address: TSubstrateAccount) {2436 return this.subBalanceGroup.getLocked(address);2437 }24382439 /**2440 * Get ethereum address balance2441 * @param address ethereum address2442 * @example getEthereum("0x9F0583DbB855d...")2443 * @returns amount of tokens on address2444 */2445 getEthereum(address: TEthereumAccount): Promise<bigint> {2446 return this.ethBalanceGroup.getEthereum(address);2447 }24482449 /**2450 * Transfer tokens to substrate address2451 * @param signer keyring of signer2452 * @param address substrate address of a recipient2453 * @param amount amount of tokens to be transfered2454 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2455 * @returns ```true``` if extrinsic success, otherwise ```false```2456 */2457 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2458 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2459 }24602461 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2462 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);24632464 let transfer = {from: null, to: null, amount: 0n} as any;2465 result.result.events.forEach(({event: {data, method, section}}) => {2466 if ((section === 'balances') && (method === 'Transfer')) {2467 transfer = {2468 from: this.helper.address.normalizeSubstrate(data[0]),2469 to: this.helper.address.normalizeSubstrate(data[1]),2470 amount: BigInt(data[2]),2471 };2472 }2473 });2474 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2475 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2476 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2477 return isSuccess;2478 }24792480 /**2481 * Transfer tokens with the unlock period2482 * @param signer signers Keyring2483 * @param address Substrate address of recipient2484 * @param schedule Schedule params2485 * @example vestedTransfer(signer, recepient.address, 20000, 100, 10, 50 * nominal); // total amount of vested tokens will be 100 * 50 = 50002486 */2487 async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: {start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}): Promise<void> {2488 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2489 const event = result.result.events2490 .find(e => e.event.section === 'vesting' &&2491 e.event.method === 'VestingScheduleAdded' &&2492 e.event.data[0].toHuman() === signer.address);2493 if (!event) throw Error('Cannot find transfer in events');2494 }24952496 /**2497 * Get schedule for recepient of vested transfer2498 * @param address Substrate address of recipient2499 * @returns2500 */2501 async getVestingSchedules(address: TSubstrateAccount): Promise<{start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}[]> {2502 const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2503 return schedule.map((schedule: any) => {2504 return {2505 start: BigInt(schedule.start),2506 period: BigInt(schedule.period),2507 periodCount: BigInt(schedule.periodCount),2508 perPeriod: BigInt(schedule.perPeriod),2509 };2510 });2511 }25122513 /**2514 * Claim vested tokens2515 * @param signer signers Keyring2516 */2517 async claim(signer: TSigner) {2518 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2519 const event = result.result.events2520 .find(e => e.event.section === 'vesting' &&2521 e.event.method === 'Claimed' &&2522 e.event.data[0].toHuman() === signer.address);2523 if (!event) throw Error('Cannot find claim in events');2524 }2525}25262527class AddressGroup extends HelperGroup<ChainHelperBase> {2528 /**2529 * Normalizes the address to the specified ss58 format, by default ```42```.2530 * @param address substrate address2531 * @param ss58Format format for address conversion, by default ```42```2532 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2533 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2534 */2535 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2536 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2537 }25382539 /**2540 * Get address in the connected chain format2541 * @param address substrate address2542 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2543 * @returns address in chain format2544 */2545 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2546 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2547 }25482549 /**2550 * Get substrate mirror of an ethereum address2551 * @param ethAddress ethereum address2552 * @param toChainFormat false for normalized account2553 * @example ethToSubstrate('0x9F0583DbB855d...')2554 * @returns substrate mirror of a provided ethereum address2555 */2556 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2557 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2558 }25592560 /**2561 * Get ethereum mirror of a substrate address2562 * @param subAddress substrate account2563 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2564 * @returns ethereum mirror of a provided substrate address2565 */2566 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2567 return CrossAccountId.translateSubToEth(subAddress);2568 }25692570 /**2571 * Encode key to substrate address2572 * @param key key for encoding address2573 * @param ss58Format prefix for encoding to the address of the corresponding network2574 * @returns encoded substrate address2575 */2576 encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2577 const u8a :Uint8Array = typeof key === 'string'2578 ? hexToU8a(key)2579 : typeof key === 'bigint'2580 ? hexToU8a(key.toString(16))2581 : key;25822583 if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2584 throw new Error(`ss58Format is not valid, received ${typeofss58Format} "${ss58Format}"`);2585 }25862587 const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2588 if (!allowedDecodedLengths.includes(u8a.length)) {2589 throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2590 }25912592 const u8aPrefix = ss58Format < 642593 ? new Uint8Array([ss58Format])2594 : new Uint8Array([2595 ((ss58Format & 0xfc) >> 2) | 0x40,2596 (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2597 ]);25982599 const input = u8aConcat(u8aPrefix, u8a);26002601 return base58Encode(u8aConcat(2602 input,2603 blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2604 ));2605 }26062607 /**2608 * Restore substrate address from bigint representation2609 * @param number decimal representation of substrate address2610 * @returns substrate address2611 */2612 restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2613 if (this.helper.api === null) {2614 throw 'Not connected';2615 }2616 const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2617 if (res === undefined || res === null) {2618 throw 'Restore address error';2619 }2620 return res.toString();2621 }26222623 /**2624 * Convert etherium cross account id to substrate cross account id2625 * @param ethCrossAccount etherium cross account2626 * @returns substrate cross account id2627 */2628 convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2629 if (ethCrossAccount.sub === '0') {2630 return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2631 }26322633 const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2634 return {Substrate: ss58};2635 }26362637 paraSiblingSovereignAccount(paraid: number) {2638 // We are getting a *sibling* parachain sovereign account,2639 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2640 const siblingPrefix = '0x7369626c';26412642 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2643 const suffix = '000000000000000000000000000000000000000000000000';26442645 return siblingPrefix + encodedParaId + suffix;2646 }2647}26482649class StakingGroup extends HelperGroup<UniqueHelper> {2650 /**2651 * Stake tokens for App Promotion2652 * @param signer keyring of signer2653 * @param amountToStake amount of tokens to stake2654 * @param label extra label for log2655 * @returns2656 */2657 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2658 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2659 const _stakeResult = await this.helper.executeExtrinsic(2660 signer, 'api.tx.appPromotion.stake',2661 [amountToStake], true,2662 );2663 // TODO extract info from stakeResult2664 return true;2665 }26662667 /**2668 * Unstake all staked tokens2669 * @param signer keyring of signer2670 * @param amountToUnstake amount of tokens to unstake2671 * @param label extra label for log2672 * @returns block hash where unstake happened2673 */2674 async unstakeAll(signer: TSigner, label?: string): Promise<string> {2675 if(typeof label === 'undefined') label = `${signer.address}`;2676 const unstakeResult = await this.helper.executeExtrinsic(2677 signer, 'api.tx.appPromotion.unstakeAll',2678 [], true,2679 );2680 return unstakeResult.blockHash;2681 }26822683 /**2684 * Unstake the part of a staked tokens2685 * @param signer keyring of signer2686 * @param amount amount of tokens to unstake2687 * @param label extra label for log2688 * @returns block hash where unstake happened2689 */2690 async unstakePartial(signer: TSigner, amount: bigint, label?: string): Promise<string> {2691 if(typeof label === 'undefined') label = `${signer.address}`;2692 const unstakeResult = await this.helper.executeExtrinsic(2693 signer, 'api.tx.appPromotion.unstakePartial',2694 [amount], true,2695 );2696 return unstakeResult.blockHash;2697 }26982699 /**2700 * Get total number of active stakes2701 * @param address substrate address2702 * @returns {number}2703 */2704 async getStakesNumber(address: ICrossAccountId): Promise<number> {2705 if (address.Ethereum) throw Error('only substrate address');2706 return (await this.helper.callRpc('api.query.appPromotion.stakesPerAccount', [address.Substrate])).toNumber();2707 }27082709 /**2710 * Get total staked amount for address2711 * @param address substrate or ethereum address2712 * @returns total staked amount2713 */2714 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2715 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2716 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2717 }27182719 /**2720 * Get total staked per block2721 * @param address substrate or ethereum address2722 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2723 */2724 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2725 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2726 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2727 return {2728 block: block.toBigInt(),2729 amount: amount.toBigInt(),2730 };2731 });2732 }27332734 /**2735 * Get total pending unstake amount for address2736 * @param address substrate or ethereum address2737 * @returns total pending unstake amount2738 */2739 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2740 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2741 }27422743 /**2744 * Get pending unstake amount per block for address2745 * @param address substrate or ethereum address2746 * @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 block2747 */2748 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2749 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2750 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2751 return {2752 block: block.toBigInt(),2753 amount: amount.toBigInt(),2754 };2755 });2756 return result;2757 }2758}27592760class SchedulerGroup extends HelperGroup<UniqueHelper> {2761 constructor(helper: UniqueHelper) {2762 super(helper);2763 }27642765 cancelScheduled(signer: TSigner, scheduledId: string) {2766 return this.helper.executeExtrinsic(2767 signer,2768 'api.tx.scheduler.cancelNamed',2769 [scheduledId],2770 true,2771 );2772 }27732774 changePriority(signer: TSigner, scheduledId: string, priority: number) {2775 return this.helper.executeExtrinsic(2776 signer,2777 'api.tx.scheduler.changeNamedPriority',2778 [scheduledId, priority],2779 true,2780 );2781 }27822783 scheduleAt<T extends UniqueHelper>(2784 executionBlockNumber: number,2785 options: ISchedulerOptions = {},2786 ) {2787 return this.schedule<T>('schedule', executionBlockNumber, options);2788 }27892790 scheduleAfter<T extends UniqueHelper>(2791 blocksBeforeExecution: number,2792 options: ISchedulerOptions = {},2793 ) {2794 return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2795 }27962797 schedule<T extends UniqueHelper>(2798 scheduleFn: 'schedule' | 'scheduleAfter',2799 blocksNum: number,2800 options: ISchedulerOptions = {},2801 ) {2802 // eslint-disable-next-line @typescript-eslint/naming-convention2803 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2804 return this.helper.clone(ScheduledHelperType, {2805 scheduleFn,2806 blocksNum,2807 options,2808 }) as T;2809 }2810}28112812class CollatorSelectionGroup extends HelperGroup<UniqueHelper> {2813 //todo:collator documentation2814 addInvulnerable(signer: TSigner, address: string) {2815 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.addInvulnerable', [address]);2816 }28172818 removeInvulnerable(signer: TSigner, address: string) {2819 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.removeInvulnerable', [address]);2820 }28212822 async getInvulnerables(): Promise<string[]> {2823 return (await this.helper.callRpc('api.query.collatorSelection.invulnerables')).map((x: any) => x.toHuman());2824 }28252826 /** and also total max invulnerables */2827 maxCollators(): number {2828 return (this.helper.getApi().consts.configuration.defaultCollatorSelectionMaxCollators.toJSON() as number);2829 }28302831 async getDesiredCollators(): Promise<number> {2832 return (await this.helper.callRpc('api.query.configuration.collatorSelectionDesiredCollatorsOverride')).toNumber();2833 }28342835 setLicenseBond(signer: TSigner, amount: bigint) {2836 return this.helper.executeExtrinsic(signer, 'api.tx.configuration.setCollatorSelectionLicenseBond', [amount]);2837 }28382839 async getLicenseBond(): Promise<bigint> {2840 return (await this.helper.callRpc('api.query.configuration.collatorSelectionLicenseBondOverride')).toBigInt();2841 }28422843 obtainLicense(signer: TSigner) {2844 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.getLicense', []);2845 }28462847 releaseLicense(signer: TSigner) {2848 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.releaseLicense', []);2849 }28502851 forceReleaseLicense(signer: TSigner, released: string) {2852 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.forceReleaseLicense', [released]);2853 }28542855 async hasLicense(address: string): Promise<bigint> {2856 return (await this.helper.callRpc('api.query.collatorSelection.licenseDepositOf', [address])).toBigInt();2857 }28582859 onboard(signer: TSigner) {2860 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.onboard', []);2861 }28622863 offboard(signer: TSigner) {2864 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.offboard', []);2865 }28662867 async getCandidates(): Promise<string[]> {2868 return (await this.helper.callRpc('api.query.collatorSelection.candidates')).map((x: any) => x.toHuman());2869 }2870}28712872class PreimageGroup extends HelperGroup<UniqueHelper> {2873 async getPreimageInfo(h256: string) {2874 return (await this.helper.callRpc('api.query.preimage.statusFor', [h256])).toJSON();2875 }28762877 /**2878 * Create a preimage with a hex or a byte array.2879 * @param signer keyring of the signer.2880 * @param bytes preimage encoded in hex or a byte array, e.g. an extrinsic call.2881 * @example await notePreimage(preimageMaker,2882 * helper.constructApiCall('api.tx.identity.forceInsertIdentities', [identitiesToAdd]).method.toHex()2883 * );2884 * @returns promise of extrinsic execution.2885 */2886 notePreimage(signer: TSigner, bytes: string | Uint8Array) {2887 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.notePreimage', [bytes]);2888 }28892890 /**2891 * Delete an existing preimage and return the deposit.2892 * @param signer keyring of the signer - either the owner or the preimage manager (sudo).2893 * @param h256 hash of the preimage.2894 * @returns promise of extrinsic execution.2895 */2896 unnotePreimage(signer: TSigner, h256: string) {2897 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unnotePreimage', [h256]);2898 }28992900 /**2901 * Request a preimage be uploaded to the chain without paying any fees or deposits.2902 * @param signer keyring of the signer - either the owner or the preimage manager (sudo).2903 * @param h256 hash of the preimage.2904 * @returns promise of extrinsic execution.2905 */2906 requestPreimage(signer: TSigner, h256: string) {2907 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.requestPreimage', [h256]);2908 }29092910 /**2911 * Clear a previously made request for a preimage.2912 * @param signer keyring of the signer - either the owner or the preimage manager (sudo).2913 * @param h256 hash of the preimage.2914 * @returns promise of extrinsic execution.2915 */2916 unrequestPreimage(signer: TSigner, h256: string) {2917 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unrequestPreimage', [h256]);2918 }2919}29202921class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2922 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2923 await this.helper.executeExtrinsic(2924 signer,2925 'api.tx.foreignAssets.registerForeignAsset',2926 [ownerAddress, location, metadata],2927 true,2928 );2929 }29302931 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2932 await this.helper.executeExtrinsic(2933 signer,2934 'api.tx.foreignAssets.updateForeignAsset',2935 [foreignAssetId, location, metadata],2936 true,2937 );2938 }2939}29402941class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2942 palletName: string;29432944 constructor(helper: T, palletName: string) {2945 super(helper);29462947 this.palletName = palletName;2948 }29492950 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {2951 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);2952 }29532954 async setSafeXcmVersion(signer: TSigner, version: number) {2955 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.forceDefaultXcmVersion`, [version], true);2956 }29572958 async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {2959 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);2960 }29612962 async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint, xcmVersion = 3) {2963 const destinationContent = {2964 parents: 0,2965 interior: {2966 X1: {2967 Parachain: destinationParaId,2968 },2969 },2970 };29712972 const beneficiaryContent = {2973 parents: 0,2974 interior: {2975 X1: {2976 AccountId32: {2977 network: 'Any',2978 id: targetAccount,2979 },2980 },2981 },2982 };29832984 const assetsContent = [2985 {2986 id: {2987 Concrete: {2988 parents: 0,2989 interior: 'Here',2990 },2991 },2992 fun: {2993 Fungible: amount,2994 },2995 },2996 ];29972998 let destination;2999 let beneficiary;3000 let assets;30013002 if (xcmVersion == 2) {3003 destination = {V1: destinationContent};3004 beneficiary = {V1: beneficiaryContent};3005 assets = {V1: assetsContent};30063007 } else if (xcmVersion == 3) {3008 destination = {V2: destinationContent};3009 beneficiary = {V2: beneficiaryContent};3010 assets = {V2: assetsContent};30113012 } else {3013 throw Error('Unknown XCM version: ' + xcmVersion);3014 }30153016 const feeAssetItem = 0;30173018 await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);3019 }3020}30213022class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {3023 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {3024 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);3025 }30263027 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {3028 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);3029 }30303031 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {3032 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);3033 }3034}30353036class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {3037 async accounts(address: string, currencyId: any) {3038 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;3039 return BigInt(free);3040 }3041}30423043class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {3044 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {3045 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);3046 }30473048 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {3049 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);3050 }30513052 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {3053 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);3054 }30553056 async account(assetId: string | number, address: string) {3057 const accountAsset = (3058 await this.helper.callRpc('api.query.assets.account', [assetId, address])3059 ).toJSON()! as any;30603061 if (accountAsset !== null) {3062 return BigInt(accountAsset['balance']);3063 } else {3064 return null;3065 }3066 }3067}30683069class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {3070 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {3071 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);3072 }3073}30743075class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {3076 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {3077 const apiPrefix = 'api.tx.assetManager.';30783079 const registerTx = this.helper.constructApiCall(3080 apiPrefix + 'registerForeignAsset',3081 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],3082 );30833084 const setUnitsTx = this.helper.constructApiCall(3085 apiPrefix + 'setAssetUnitsPerSecond',3086 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],3087 );30883089 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);3090 const encodedProposal = batchCall?.method.toHex() || '';3091 return encodedProposal;3092 }30933094 async assetTypeId(location: any) {3095 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);3096 }3097}30983099class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {3100 notePreimagePallet: string;31013102 constructor(helper: MoonbeamHelper, options: {[key: string]: any} = {}) {3103 super(helper);3104 this.notePreimagePallet = options.notePreimagePallet;3105 }31063107 async notePreimage(signer: TSigner, encodedProposal: string) {3108 await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);3109 }31103111 externalProposeMajority(proposal: any) {3112 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);3113 }31143115 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {3116 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);3117 }31183119 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {3120 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);3121 }3122}31233124class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {3125 collective: string;31263127 constructor(helper: MoonbeamHelper, collective: string) {3128 super(helper);31293130 this.collective = collective;3131 }31323133 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {3134 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);3135 }31363137 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {3138 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);3139 }31403141 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {3142 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);3143 }31443145 async proposalCount() {3146 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));3147 }3148}31493150export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;3151export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;31523153export class UniqueHelper extends ChainHelperBase {3154 balance: BalanceGroup<UniqueHelper>;3155 collection: CollectionGroup;3156 nft: NFTGroup;3157 rft: RFTGroup;3158 ft: FTGroup;3159 staking: StakingGroup;3160 scheduler: SchedulerGroup;3161 collatorSelection: CollatorSelectionGroup;3162 preimage: PreimageGroup;3163 foreignAssets: ForeignAssetsGroup;3164 xcm: XcmGroup<UniqueHelper>;3165 xTokens: XTokensGroup<UniqueHelper>;3166 tokens: TokensGroup<UniqueHelper>;31673168 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3169 super(logger, options.helperBase ?? UniqueHelper);31703171 this.balance = new BalanceGroup(this);3172 this.collection = new CollectionGroup(this);3173 this.nft = new NFTGroup(this);3174 this.rft = new RFTGroup(this);3175 this.ft = new FTGroup(this);3176 this.staking = new StakingGroup(this);3177 this.scheduler = new SchedulerGroup(this);3178 this.collatorSelection = new CollatorSelectionGroup(this);3179 this.preimage = new PreimageGroup(this);3180 this.foreignAssets = new ForeignAssetsGroup(this);3181 this.xcm = new XcmGroup(this, 'polkadotXcm');3182 this.xTokens = new XTokensGroup(this);3183 this.tokens = new TokensGroup(this);3184 }31853186 getSudo<T extends UniqueHelper>() {3187 // eslint-disable-next-line @typescript-eslint/naming-convention3188 const SudoHelperType = SudoHelper(this.helperBase);3189 return this.clone(SudoHelperType) as T;3190 }3191}31923193export class XcmChainHelper extends ChainHelperBase {3194 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {3195 const wsProvider = new WsProvider(wsEndpoint);3196 this.api = new ApiPromise({3197 provider: wsProvider,3198 });3199 await this.api.isReadyOrError;3200 this.network = await UniqueHelper.detectNetwork(this.api);3201 }3202}32033204export class RelayHelper extends XcmChainHelper {3205 balance: SubstrateBalanceGroup<RelayHelper>;3206 xcm: XcmGroup<RelayHelper>;32073208 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3209 super(logger, options.helperBase ?? RelayHelper);32103211 this.balance = new SubstrateBalanceGroup(this);3212 this.xcm = new XcmGroup(this, 'xcmPallet');3213 }3214}32153216export class WestmintHelper extends XcmChainHelper {3217 balance: SubstrateBalanceGroup<WestmintHelper>;3218 xcm: XcmGroup<WestmintHelper>;3219 assets: AssetsGroup<WestmintHelper>;3220 xTokens: XTokensGroup<WestmintHelper>;32213222 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3223 super(logger, options.helperBase ?? WestmintHelper);32243225 this.balance = new SubstrateBalanceGroup(this);3226 this.xcm = new XcmGroup(this, 'polkadotXcm');3227 this.assets = new AssetsGroup(this);3228 this.xTokens = new XTokensGroup(this);3229 }3230}32313232export class MoonbeamHelper extends XcmChainHelper {3233 balance: EthereumBalanceGroup<MoonbeamHelper>;3234 assetManager: MoonbeamAssetManagerGroup;3235 assets: AssetsGroup<MoonbeamHelper>;3236 xTokens: XTokensGroup<MoonbeamHelper>;3237 democracy: MoonbeamDemocracyGroup;3238 collective: {3239 council: MoonbeamCollectiveGroup,3240 techCommittee: MoonbeamCollectiveGroup,3241 };32423243 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3244 super(logger, options.helperBase ?? MoonbeamHelper);32453246 this.balance = new EthereumBalanceGroup(this);3247 this.assetManager = new MoonbeamAssetManagerGroup(this);3248 this.assets = new AssetsGroup(this);3249 this.xTokens = new XTokensGroup(this);3250 this.democracy = new MoonbeamDemocracyGroup(this, options);3251 this.collective = {3252 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),3253 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),3254 };3255 }3256}32573258export class AstarHelper extends XcmChainHelper {3259 balance: SubstrateBalanceGroup<AstarHelper>;3260 assets: AssetsGroup<AstarHelper>;3261 xcm: XcmGroup<AstarHelper>;32623263 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3264 super(logger, options.helperBase ?? AstarHelper);32653266 this.balance = new SubstrateBalanceGroup(this);3267 this.assets = new AssetsGroup(this);3268 this.xcm = new XcmGroup(this, 'polkadotXcm');3269 }32703271 getSudo<T extends UniqueHelper>() {3272 // eslint-disable-next-line @typescript-eslint/naming-convention3273 const SudoHelperType = SudoHelper(this.helperBase);3274 return this.clone(SudoHelperType) as T;3275 }3276}32773278export class AcalaHelper extends XcmChainHelper {3279 balance: SubstrateBalanceGroup<AcalaHelper>;3280 assetRegistry: AcalaAssetRegistryGroup;3281 xTokens: XTokensGroup<AcalaHelper>;3282 tokens: TokensGroup<AcalaHelper>;32833284 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3285 super(logger, options.helperBase ?? AcalaHelper);32863287 this.balance = new SubstrateBalanceGroup(this);3288 this.assetRegistry = new AcalaAssetRegistryGroup(this);3289 this.xTokens = new XTokensGroup(this);3290 this.tokens = new TokensGroup(this);3291 }32923293 getSudo<T extends AcalaHelper>() {3294 // eslint-disable-next-line @typescript-eslint/naming-convention3295 const SudoHelperType = SudoHelper(this.helperBase);3296 return this.clone(SudoHelperType) as T;3297 }3298}32993300// eslint-disable-next-line @typescript-eslint/naming-convention3301function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3302 return class extends Base {3303 scheduleFn: 'schedule' | 'scheduleAfter';3304 blocksNum: number;3305 options: ISchedulerOptions;33063307 constructor(...args: any[]) {3308 const logger = args[0] as ILogger;3309 const options = args[1] as {3310 scheduleFn: 'schedule' | 'scheduleAfter',3311 blocksNum: number,3312 options: ISchedulerOptions3313 };33143315 super(logger);33163317 this.scheduleFn = options.scheduleFn;3318 this.blocksNum = options.blocksNum;3319 this.options = options.options;3320 }33213322 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3323 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);33243325 const mandatorySchedArgs = [3326 this.blocksNum,3327 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3328 this.options.priority ?? null,3329 scheduledTx,3330 ];33313332 let schedArgs;3333 let scheduleFn;33343335 if (this.options.scheduledId) {3336 schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];33373338 if (this.scheduleFn == 'schedule') {3339 scheduleFn = 'scheduleNamed';3340 } else if (this.scheduleFn == 'scheduleAfter') {3341 scheduleFn = 'scheduleNamedAfter';3342 }3343 } else {3344 schedArgs = mandatorySchedArgs;3345 scheduleFn = this.scheduleFn;3346 }33473348 const extrinsic = 'api.tx.scheduler.' + scheduleFn;33493350 return super.executeExtrinsic(3351 sender,3352 extrinsic,3353 schedArgs,3354 expectSuccess,3355 );3356 }3357 };3358}33593360// eslint-disable-next-line @typescript-eslint/naming-convention3361function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3362 return class extends Base {3363 constructor(...args: any[]) {3364 super(...args);3365 }33663367 async executeExtrinsic(3368 sender: IKeyringPair,3369 extrinsic: string,3370 params: any[],3371 expectSuccess?: boolean,3372 options: Partial<SignerOptions>|null = null,3373 ): Promise<ITransactionResult> {3374 const call = this.constructApiCall(extrinsic, params);3375 const result = await super.executeExtrinsic(3376 sender,3377 'api.tx.sudo.sudo',3378 [call],3379 expectSuccess,3380 options,3381 );33823383 if (result.status === 'Fail') return result;33843385 const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;3386 if (data.isErr) {3387 if (data.asErr.isModule) {3388 const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;3389 const metaError = super.getApi()?.registry.findMetaError(error);3390 throw new Error(`${metaError.section}.${metaError.name}`);3391 } else {3392 throw new Error(data.asErr.toHuman());3393 }3394 }3395 return result;3396 }3397 };3398}33993400export class UniqueBaseCollection {3401 helper: UniqueHelper;3402 collectionId: number;34033404 constructor(collectionId: number, uniqueHelper: UniqueHelper) {3405 this.collectionId = collectionId;3406 this.helper = uniqueHelper;3407 }34083409 async getData() {3410 return await this.helper.collection.getData(this.collectionId);3411 }34123413 async getLastTokenId() {3414 return await this.helper.collection.getLastTokenId(this.collectionId);3415 }34163417 async doesTokenExist(tokenId: number) {3418 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3419 }34203421 async getAdmins() {3422 return await this.helper.collection.getAdmins(this.collectionId);3423 }34243425 async getAllowList() {3426 return await this.helper.collection.getAllowList(this.collectionId);3427 }34283429 async getEffectiveLimits() {3430 return await this.helper.collection.getEffectiveLimits(this.collectionId);3431 }34323433 async getProperties(propertyKeys?: string[] | null) {3434 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3435 }34363437 async getPropertiesConsumedSpace() {3438 return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3439 }34403441 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3442 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3443 }34443445 async getOptions() {3446 return await this.helper.collection.getCollectionOptions(this.collectionId);3447 }34483449 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3450 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3451 }34523453 async confirmSponsorship(signer: TSigner) {3454 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3455 }34563457 async removeSponsor(signer: TSigner) {3458 return await this.helper.collection.removeSponsor(signer, this.collectionId);3459 }34603461 async setLimits(signer: TSigner, limits: ICollectionLimits) {3462 return await this.helper.collection.setLimits(signer, this.collectionId, limits);3463 }34643465 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3466 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3467 }34683469 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3470 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3471 }34723473 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3474 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3475 }34763477 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3478 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3479 }34803481 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3482 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3483 }34843485 async setProperties(signer: TSigner, properties: IProperty[]) {3486 return await this.helper.collection.setProperties(signer, this.collectionId, properties);3487 }34883489 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3490 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3491 }34923493 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3494 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3495 }34963497 async enableNesting(signer: TSigner, permissions: INestingPermissions) {3498 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3499 }35003501 async disableNesting(signer: TSigner) {3502 return await this.helper.collection.disableNesting(signer, this.collectionId);3503 }35043505 async burn(signer: TSigner) {3506 return await this.helper.collection.burn(signer, this.collectionId);3507 }35083509 scheduleAt<T extends UniqueHelper>(3510 executionBlockNumber: number,3511 options: ISchedulerOptions = {},3512 ) {3513 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3514 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3515 }35163517 scheduleAfter<T extends UniqueHelper>(3518 blocksBeforeExecution: number,3519 options: ISchedulerOptions = {},3520 ) {3521 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3522 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3523 }35243525 getSudo<T extends UniqueHelper>() {3526 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3527 }3528}352935303531export class UniqueNFTCollection extends UniqueBaseCollection {3532 getTokenObject(tokenId: number) {3533 return new UniqueNFToken(tokenId, this);3534 }35353536 async getTokensByAddress(addressObj: ICrossAccountId) {3537 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3538 }35393540 async getToken(tokenId: number, blockHashAt?: string) {3541 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3542 }35433544 async getTokenOwner(tokenId: number, blockHashAt?: string) {3545 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3546 }35473548 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3549 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3550 }35513552 async getTokenChildren(tokenId: number, blockHashAt?: string) {3553 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3554 }35553556 async getPropertyPermissions(propertyKeys: string[] | null = null) {3557 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3558 }35593560 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3561 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3562 }35633564 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3565 const api = this.helper.getApi();3566 const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();35673568 return (props! as any).consumedSpace;3569 }35703571 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3572 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3573 }35743575 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3576 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3577 }35783579 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3580 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3581 }35823583 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3584 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3585 }35863587 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3588 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3589 }35903591 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3592 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3593 }35943595 async burnToken(signer: TSigner, tokenId: number) {3596 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3597 }35983599 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3600 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3601 }36023603 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3604 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3605 }36063607 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3608 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3609 }36103611 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3612 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3613 }36143615 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3616 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3617 }36183619 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3620 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3621 }36223623 scheduleAt<T extends UniqueHelper>(3624 executionBlockNumber: number,3625 options: ISchedulerOptions = {},3626 ) {3627 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3628 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3629 }36303631 scheduleAfter<T extends UniqueHelper>(3632 blocksBeforeExecution: number,3633 options: ISchedulerOptions = {},3634 ) {3635 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3636 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3637 }36383639 getSudo<T extends UniqueHelper>() {3640 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3641 }3642}364336443645export class UniqueRFTCollection extends UniqueBaseCollection {3646 getTokenObject(tokenId: number) {3647 return new UniqueRFToken(tokenId, this);3648 }36493650 async getToken(tokenId: number, blockHashAt?: string) {3651 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3652 }36533654 async getTokenOwner(tokenId: number, blockHashAt?: string) {3655 return await this.helper.rft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3656 }36573658 async getTokensByAddress(addressObj: ICrossAccountId) {3659 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3660 }36613662 async getTop10TokenOwners(tokenId: number) {3663 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3664 }36653666 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3667 return await this.helper.rft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3668 }36693670 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3671 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3672 }36733674 async getTokenTotalPieces(tokenId: number) {3675 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3676 }36773678 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3679 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3680 }36813682 async getPropertyPermissions(propertyKeys: string[] | null = null) {3683 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3684 }36853686 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3687 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3688 }36893690 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3691 const api = this.helper.getApi();3692 const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();36933694 return (props! as any).consumedSpace;3695 }36963697 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3698 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3699 }37003701 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3702 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3703 }37043705 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3706 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3707 }37083709 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3710 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3711 }37123713 async mintToken(signer: TSigner, pieces = 1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3714 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3715 }37163717 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3718 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3719 }37203721 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3722 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3723 }37243725 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3726 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3727 }37283729 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3730 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3731 }37323733 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3734 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3735 }37363737 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3738 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3739 }37403741 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3742 return await this.helper.rft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3743 }37443745 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3746 return await this.helper.rft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3747 }37483749 scheduleAt<T extends UniqueHelper>(3750 executionBlockNumber: number,3751 options: ISchedulerOptions = {},3752 ) {3753 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3754 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3755 }37563757 scheduleAfter<T extends UniqueHelper>(3758 blocksBeforeExecution: number,3759 options: ISchedulerOptions = {},3760 ) {3761 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3762 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3763 }37643765 getSudo<T extends UniqueHelper>() {3766 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3767 }3768}376937703771export class UniqueFTCollection extends UniqueBaseCollection {3772 async getBalance(addressObj: ICrossAccountId) {3773 return await this.helper.ft.getBalance(this.collectionId, addressObj);3774 }37753776 async getTotalPieces() {3777 return await this.helper.ft.getTotalPieces(this.collectionId);3778 }37793780 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3781 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3782 }37833784 async getTop10Owners() {3785 return await this.helper.ft.getTop10Owners(this.collectionId);3786 }37873788 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3789 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3790 }37913792 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3793 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3794 }37953796 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3797 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3798 }37993800 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3801 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3802 }38033804 async burnTokens(signer: TSigner, amount=1n) {3805 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3806 }38073808 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3809 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3810 }38113812 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3813 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3814 }38153816 scheduleAt<T extends UniqueHelper>(3817 executionBlockNumber: number,3818 options: ISchedulerOptions = {},3819 ) {3820 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3821 return new UniqueFTCollection(this.collectionId, scheduledHelper);3822 }38233824 scheduleAfter<T extends UniqueHelper>(3825 blocksBeforeExecution: number,3826 options: ISchedulerOptions = {},3827 ) {3828 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3829 return new UniqueFTCollection(this.collectionId, scheduledHelper);3830 }38313832 getSudo<T extends UniqueHelper>() {3833 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3834 }3835}383638373838export class UniqueBaseToken {3839 collection: UniqueNFTCollection | UniqueRFTCollection;3840 collectionId: number;3841 tokenId: number;38423843 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3844 this.collection = collection;3845 this.collectionId = collection.collectionId;3846 this.tokenId = tokenId;3847 }38483849 async getNextSponsored(addressObj: ICrossAccountId) {3850 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3851 }38523853 async getProperties(propertyKeys?: string[] | null) {3854 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3855 }38563857 async getTokenPropertiesConsumedSpace() {3858 return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3859 }38603861 async setProperties(signer: TSigner, properties: IProperty[]) {3862 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3863 }38643865 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3866 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3867 }38683869 async doesExist() {3870 return await this.collection.doesTokenExist(this.tokenId);3871 }38723873 nestingAccount() {3874 return this.collection.helper.util.getTokenAccount(this);3875 }38763877 scheduleAt<T extends UniqueHelper>(3878 executionBlockNumber: number,3879 options: ISchedulerOptions = {},3880 ) {3881 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3882 return new UniqueBaseToken(this.tokenId, scheduledCollection);3883 }38843885 scheduleAfter<T extends UniqueHelper>(3886 blocksBeforeExecution: number,3887 options: ISchedulerOptions = {},3888 ) {3889 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3890 return new UniqueBaseToken(this.tokenId, scheduledCollection);3891 }38923893 getSudo<T extends UniqueHelper>() {3894 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3895 }3896}389738983899export class UniqueNFToken extends UniqueBaseToken {3900 collection: UniqueNFTCollection;39013902 constructor(tokenId: number, collection: UniqueNFTCollection) {3903 super(tokenId, collection);3904 this.collection = collection;3905 }39063907 async getData(blockHashAt?: string) {3908 return await this.collection.getToken(this.tokenId, blockHashAt);3909 }39103911 async getOwner(blockHashAt?: string) {3912 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3913 }39143915 async getTopmostOwner(blockHashAt?: string) {3916 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3917 }39183919 async getChildren(blockHashAt?: string) {3920 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3921 }39223923 async nest(signer: TSigner, toTokenObj: IToken) {3924 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3925 }39263927 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3928 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3929 }39303931 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3932 return await this.collection.transferToken(signer, this.tokenId, addressObj);3933 }39343935 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3936 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3937 }39383939 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3940 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3941 }39423943 async isApproved(toAddressObj: ICrossAccountId) {3944 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3945 }39463947 async burn(signer: TSigner) {3948 return await this.collection.burnToken(signer, this.tokenId);3949 }39503951 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3952 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3953 }39543955 scheduleAt<T extends UniqueHelper>(3956 executionBlockNumber: number,3957 options: ISchedulerOptions = {},3958 ) {3959 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3960 return new UniqueNFToken(this.tokenId, scheduledCollection);3961 }39623963 scheduleAfter<T extends UniqueHelper>(3964 blocksBeforeExecution: number,3965 options: ISchedulerOptions = {},3966 ) {3967 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3968 return new UniqueNFToken(this.tokenId, scheduledCollection);3969 }39703971 getSudo<T extends UniqueHelper>() {3972 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3973 }3974}39753976export class UniqueRFToken extends UniqueBaseToken {3977 collection: UniqueRFTCollection;39783979 constructor(tokenId: number, collection: UniqueRFTCollection) {3980 super(tokenId, collection);3981 this.collection = collection;3982 }39833984 async getData(blockHashAt?: string) {3985 return await this.collection.getToken(this.tokenId, blockHashAt);3986 }39873988 async getOwner(blockHashAt?: string) {3989 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3990 }39913992 async getTop10Owners() {3993 return await this.collection.getTop10TokenOwners(this.tokenId);3994 }39953996 async getTopmostOwner(blockHashAt?: string) {3997 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3998 }39994000 async nest(signer: TSigner, toTokenObj: IToken) {4001 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);4002 }40034004 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {4005 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);4006 }40074008 async getBalance(addressObj: ICrossAccountId) {4009 return await this.collection.getTokenBalance(this.tokenId, addressObj);4010 }40114012 async getTotalPieces() {4013 return await this.collection.getTokenTotalPieces(this.tokenId);4014 }40154016 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {4017 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);4018 }40194020 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {4021 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);4022 }40234024 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {4025 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);4026 }40274028 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {4029 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);4030 }40314032 async repartition(signer: TSigner, amount: bigint) {4033 return await this.collection.repartitionToken(signer, this.tokenId, amount);4034 }40354036 async burn(signer: TSigner, amount=1n) {4037 return await this.collection.burnToken(signer, this.tokenId, amount);4038 }40394040 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {4041 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);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 UniqueRFToken(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 UniqueRFToken(this.tokenId, scheduledCollection);4058 }40594060 getSudo<T extends UniqueHelper>() {4061 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());4062 }4063}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 {ApiInterfaceEvents} from '@polkadot/api/types';11import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';12import {IKeyringPair} from '@polkadot/types/types';13import {hexToU8a} from '@polkadot/util/hex';14import {u8aConcat} from '@polkadot/util/u8a';15import {16 IApiListeners,17 IBlock,18 IEvent,19 IChainProperties,20 ICollectionCreationOptions,21 ICollectionLimits,22 ICollectionPermissions,23 ICrossAccountId,24 ICrossAccountIdLower,25 ILogger,26 INestingPermissions,27 IProperty,28 IStakingInfo,29 ISchedulerOptions,30 ISubstrateBalance,31 IToken,32 ITokenPropertyPermission,33 ITransactionResult,34 IUniqueHelperLog,35 TApiAllowedListeners,36 TEthereumAccount,37 TSigner,38 TSubstrateAccount,39 TNetworks,40 IForeignAssetMetadata,41 AcalaAssetMetadata,42 MoonbeamAssetInfo,43 DemocracyStandardAccountVote,44 IEthCrossAccountId,45} from './types';46import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';47import type {Vec} from '@polkadot/types-codec';48import {FrameSystemEventRecord} from '@polkadot/types/lookup';4950export class CrossAccountId implements ICrossAccountId {51 Substrate?: TSubstrateAccount;52 Ethereum?: TEthereumAccount;5354 constructor(account: ICrossAccountId) {55 if (account.Substrate) this.Substrate = account.Substrate;56 if (account.Ethereum) this.Ethereum = account.Ethereum;57 }5859 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {60 switch (domain) {61 case 'Substrate': return new CrossAccountId({Substrate: account.address});62 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();63 }64 }6566 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {67 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});68 }6970 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {71 return encodeAddress(decodeAddress(address), ss58Format);72 }7374 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {75 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});76 }7778 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {79 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);80 return this;81 }8283 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {84 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));85 }8687 toEthereum(): CrossAccountId {88 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});89 return this;90 }9192 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {93 return evmToAddress(address, ss58Format);94 }9596 toSubstrate(ss58Format?: number): CrossAccountId {97 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});98 return this;99 }100101 toLowerCase(): CrossAccountId {102 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();103 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();104 return this;105 }106}107108const nesting = {109 toChecksumAddress(address: string): string {110 if (typeof address === 'undefined') return '';111112 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);113114 address = address.toLowerCase().replace(/^0x/i,'');115 const addressHash = keccakAsHex(address).replace(/^0x/i,'');116 const checksumAddress = ['0x'];117118 for (let i = 0; i < address.length; i++) {119 // If ith character is 8 to f then make it uppercase120 if (parseInt(addressHash[i], 16) > 7) {121 checksumAddress.push(address[i].toUpperCase());122 } else {123 checksumAddress.push(address[i]);124 }125 }126 return checksumAddress.join('');127 },128 tokenIdToAddress(collectionId: number, tokenId: number) {129 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);130 },131};132133class UniqueUtil {134 static transactionStatus = {135 NOT_READY: 'NotReady',136 FAIL: 'Fail',137 SUCCESS: 'Success',138 };139140 static chainLogType = {141 EXTRINSIC: 'extrinsic',142 RPC: 'rpc',143 };144145 static getTokenAccount(token: IToken): CrossAccountId {146 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});147 }148149 static getTokenAddress(token: IToken): string {150 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);151 }152153 static getDefaultLogger(): ILogger {154 return {155 log(msg: any, level = 'INFO') {156 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));157 },158 level: {159 ERROR: 'ERROR',160 WARNING: 'WARNING',161 INFO: 'INFO',162 },163 };164 }165166 static vec2str(arr: string[] | number[]) {167 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');168 }169170 static str2vec(string: string) {171 if (typeof string !== 'string') return string;172 return Array.from(string).map(x => x.charCodeAt(0));173 }174175 static fromSeed(seed: string, ss58Format = 42) {176 const keyring = new Keyring({type: 'sr25519', ss58Format});177 return keyring.addFromUri(seed);178 }179180 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {181 if (creationResult.status !== this.transactionStatus.SUCCESS) {182 throw Error('Unable to create collection!');183 }184185 let collectionId = null;186 creationResult.result.events.forEach(({event: {data, method, section}}) => {187 if ((section === 'common') && (method === 'CollectionCreated')) {188 collectionId = parseInt(data[0].toString(), 10);189 }190 });191192 if (collectionId === null) {193 throw Error('No CollectionCreated event was found!');194 }195196 return collectionId;197 }198199 static extractTokensFromCreationResult(creationResult: ITransactionResult): {200 success: boolean,201 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],202 } {203 if (creationResult.status !== this.transactionStatus.SUCCESS) {204 throw Error('Unable to create tokens!');205 }206 let success = false;207 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];208 creationResult.result.events.forEach(({event: {data, method, section}}) => {209 if (method === 'ExtrinsicSuccess') {210 success = true;211 } else if ((section === 'common') && (method === 'ItemCreated')) {212 tokens.push({213 collectionId: parseInt(data[0].toString(), 10),214 tokenId: parseInt(data[1].toString(), 10),215 owner: data[2].toHuman(),216 amount: data[3].toBigInt(),217 });218 }219 });220 return {success, tokens};221 }222223 static extractTokensFromBurnResult(burnResult: ITransactionResult): {224 success: boolean,225 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],226 } {227 if (burnResult.status !== this.transactionStatus.SUCCESS) {228 throw Error('Unable to burn tokens!');229 }230 let success = false;231 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];232 burnResult.result.events.forEach(({event: {data, method, section}}) => {233 if (method === 'ExtrinsicSuccess') {234 success = true;235 } else if ((section === 'common') && (method === 'ItemDestroyed')) {236 tokens.push({237 collectionId: parseInt(data[0].toString(), 10),238 tokenId: parseInt(data[1].toString(), 10),239 owner: data[2].toHuman(),240 amount: data[3].toBigInt(),241 });242 }243 });244 return {success, tokens};245 }246247 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {248 let eventId = null;249 events.forEach(({event: {data, method, section}}) => {250 if ((section === expectedSection) && (method === expectedMethod)) {251 eventId = parseInt(data[0].toString(), 10);252 }253 });254255 if (eventId === null) {256 throw Error(`No ${expectedMethod} event was found!`);257 }258 return eventId === collectionId;259 }260261 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {262 const normalizeAddress = (address: string | ICrossAccountId) => {263 if(typeof address === 'string') return address;264 const obj = {} as any;265 Object.keys(address).forEach(k => {266 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];267 });268 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);269 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();270 return address;271 };272 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;273 events.forEach(({event: {data, method, section}}) => {274 if ((section === 'common') && (method === 'Transfer')) {275 const hData = (data as any).toJSON();276 transfer = {277 collectionId: hData[0],278 tokenId: hData[1],279 from: normalizeAddress(hData[2]),280 to: normalizeAddress(hData[3]),281 amount: BigInt(hData[4]),282 };283 }284 });285 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;286 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);287 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);288 isSuccess = isSuccess && amount === transfer.amount;289 return isSuccess;290 }291292 static bigIntToDecimals(number: bigint, decimals = 18) {293 const numberStr = number.toString();294 const dotPos = numberStr.length - decimals;295296 if (dotPos <= 0) {297 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;298 } else {299 const intPart = numberStr.substring(0, dotPos);300 const fractPart = numberStr.substring(dotPos);301 return intPart + '.' + fractPart;302 }303 }304}305306class UniqueEventHelper {307 private static extractIndex(index: any): [number, number] | string {308 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];309 return index.toJSON();310 }311312 private static extractSub(data: any, subTypes: any): {[key: string]: any} {313 let obj: any = {};314 let index = 0;315316 if (data.entries) {317 for(const [key, value] of data.entries()) {318 obj[key] = this.extractData(value, subTypes[index]);319 index++;320 }321 } else obj = data.toJSON();322323 return obj;324 }325326 private static toHuman(data: any) {327 return data && data.toHuman ? data.toHuman() : `${data}`;328 }329330 private static extractData(data: any, type: any): any {331 if(!type) return this.toHuman(data);332 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();333 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();334 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);335 return this.toHuman(data);336 }337338 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {339 const parsedEvents: IEvent[] = [];340341 events.forEach((record) => {342 const {event, phase} = record;343 const types = event.typeDef;344345 const eventData: IEvent = {346 section: event.section.toString(),347 method: event.method.toString(),348 index: this.extractIndex(event.index),349 data: [],350 phase: phase.toJSON(),351 };352353 event.data.forEach((val: any, index: number) => {354 eventData.data.push(this.extractData(val, types[index]));355 });356357 parsedEvents.push(eventData);358 });359360 return parsedEvents;361 }362}363364export class ChainHelperBase {365 helperBase: any;366367 transactionStatus = UniqueUtil.transactionStatus;368 chainLogType = UniqueUtil.chainLogType;369 util: typeof UniqueUtil;370 eventHelper: typeof UniqueEventHelper;371 logger: ILogger;372 api: ApiPromise | null;373 forcedNetwork: TNetworks | null;374 network: TNetworks | null;375 wsEndpoint: string | null;376 chainLog: IUniqueHelperLog[];377 children: ChainHelperBase[];378 address: AddressGroup;379 chain: ChainGroup;380381 constructor(logger?: ILogger, helperBase?: any) {382 this.helperBase = helperBase;383384 this.util = UniqueUtil;385 this.eventHelper = UniqueEventHelper;386 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();387 this.logger = logger;388 this.api = null;389 this.forcedNetwork = null;390 this.network = null;391 this.wsEndpoint = null;392 this.chainLog = [];393 this.children = [];394 this.address = new AddressGroup(this);395 this.chain = new ChainGroup(this);396 }397398 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {399 Object.setPrototypeOf(helperCls.prototype, this);400 const newHelper = new helperCls(this.logger, options);401402 newHelper.api = this.api;403 newHelper.network = this.network;404 newHelper.forceNetwork = this.forceNetwork;405406 this.children.push(newHelper);407408 return newHelper;409 }410411 getEndpoint(): string {412 if (this.wsEndpoint === null) throw Error('No connection was established');413 return this.wsEndpoint;414 }415416 getApi(): ApiPromise {417 if(this.api === null) throw Error('API not initialized');418 return this.api;419 }420421 async subscribeEvents(expectedEvents: {section: string, names: string[]}[]) {422 const collectedEvents: IEvent[] = [];423 const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {424 const ievents = this.eventHelper.extractEvents(events);425 ievents.forEach((event) => {426 expectedEvents.forEach((e => {427 if (event.section === e.section && e.names.includes(event.method)) {428 collectedEvents.push(event);429 }430 }));431 });432 });433 return {unsubscribe: unsubscribe as any, collectedEvents};434 }435436 clearChainLog(): void {437 this.chainLog = [];438 }439440 forceNetwork(value: TNetworks): void {441 this.forcedNetwork = value;442 }443444 async connect(wsEndpoint: string, listeners?: IApiListeners) {445 if (this.api !== null) throw Error('Already connected');446 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);447 this.wsEndpoint = wsEndpoint;448 this.api = api;449 this.network = network;450 }451452 async disconnect() {453 for (const child of this.children) {454 child.clearApi();455 }456457 if (this.api === null) return;458 await this.api.disconnect();459 this.clearApi();460 }461462 clearApi() {463 this.api = null;464 this.network = null;465 }466467 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {468 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;469 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];470471 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;472473 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;474 return 'opal';475 }476477 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {478 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});479 await api.isReady;480481 const network = await this.detectNetwork(api);482483 await api.disconnect();484485 return network;486 }487488 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{489 api: ApiPromise;490 network: TNetworks;491 }> {492 if(typeof network === 'undefined' || network === null) network = 'opal';493 const supportedRPC = {494 opal: {495 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,496 },497 quartz: {498 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,499 },500 unique: {501 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,502 },503 rococo: {},504 westend: {},505 moonbeam: {},506 moonriver: {},507 acala: {},508 karura: {},509 westmint: {},510 };511 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);512 const rpc = supportedRPC[network];513514 // TODO: investigate how to replace rpc in runtime515 // api._rpcCore.addUserInterfaces(rpc);516517 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});518519 await api.isReadyOrError;520521 if (typeof listeners === 'undefined') listeners = {};522 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {523 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;524 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);525 }526527 return {api, network};528 }529530 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {531 const {events, status} = data;532 if (status.isReady) {533 return this.transactionStatus.NOT_READY;534 }535 if (status.isBroadcast) {536 return this.transactionStatus.NOT_READY;537 }538 if (status.isInBlock || status.isFinalized) {539 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');540 if (errors.length > 0) {541 return this.transactionStatus.FAIL;542 }543 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {544 return this.transactionStatus.SUCCESS;545 }546 }547548 return this.transactionStatus.FAIL;549 }550551 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {552 const sign = (callback: any) => {553 if(options !== null) return transaction.signAndSend(sender, options, callback);554 return transaction.signAndSend(sender, callback);555 };556 // eslint-disable-next-line no-async-promise-executor557 return new Promise(async (resolve, reject) => {558 try {559 const unsub = await sign((result: any) => {560 const status = this.getTransactionStatus(result);561562 if (status === this.transactionStatus.SUCCESS) {563 this.logger.log(`${label} successful`);564 unsub();565 resolve({result, status, blockHash: result.status.asInBlock.toHuman()});566 } else if (status === this.transactionStatus.FAIL) {567 let moduleError = null;568569 if (result.hasOwnProperty('dispatchError')) {570 const dispatchError = result['dispatchError'];571572 if (dispatchError) {573 if (dispatchError.isModule) {574 const modErr = dispatchError.asModule;575 const errorMeta = dispatchError.registry.findMetaError(modErr);576577 moduleError = `${errorMeta.section}.${errorMeta.name}`;578 } else {579 moduleError = dispatchError.toHuman();580 }581 } else {582 this.logger.log(result, this.logger.level.ERROR);583 }584 }585586 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);587 unsub();588 reject({status, moduleError, result});589 }590 });591 } catch (e) {592 this.logger.log(e, this.logger.level.ERROR);593 reject(e);594 }595 });596 }597598 async signTransactionWithoutSending(signer: TSigner, tx: any) {599 const api = this.getApi();600 const signingInfo = await api.derive.tx.signingInfo(signer.address);601602 tx.sign(signer, {603 blockHash: api.genesisHash,604 genesisHash: api.genesisHash,605 runtimeVersion: api.runtimeVersion,606 nonce: signingInfo.nonce,607 });608609 return tx.toHex();610 }611612 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {613 const api = this.getApi();614 const signingInfo = await api.derive.tx.signingInfo(signer.address);615616 // We need to sign the tx because617 // unsigned transactions does not have an inclusion fee618 tx.sign(signer, {619 blockHash: api.genesisHash,620 genesisHash: api.genesisHash,621 runtimeVersion: api.runtimeVersion,622 nonce: signingInfo.nonce,623 });624625 if (len === null) {626 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;627 } else {628 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;629 }630 }631632 constructApiCall(apiCall: string, params: any[]) {633 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);634 let call = this.getApi() as any;635 for(const part of apiCall.slice(4).split('.')) {636 call = call[part];637 if (!call) {638 const advice = part.includes('_') ? ' Looks like it needs to be converted to camel case.' : '';639 throw Error(`Function ${part} of api call ${apiCall} not found.${advice}`);640 }641 }642 return call(...params);643 }644645 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {646 if(this.api === null) throw Error('API not initialized');647 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);648649 const startTime = (new Date()).getTime();650 let result: ITransactionResult;651 let events: IEvent[] = [];652 try {653 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;654 events = this.eventHelper.extractEvents(result.result.events);655 const errorEvent = events.find((event) => event.method == 'ExecutedFailed' || event.method == 'CreatedFailed');656 if (errorEvent)657 throw Error(errorEvent.method + ': ' + extrinsic);658 }659 catch(e) {660 if(!(e as object).hasOwnProperty('status')) throw e;661 result = e as ITransactionResult;662 }663664 const endTime = (new Date()).getTime();665666 const log = {667 executedAt: endTime,668 executionTime: endTime - startTime,669 type: this.chainLogType.EXTRINSIC,670 status: result.status,671 call: extrinsic,672 signer: this.getSignerAddress(sender),673 params,674 } as IUniqueHelperLog;675676 let errorMessage = '';677678 if(result.status !== this.transactionStatus.SUCCESS) {679 if (result.moduleError) {680 errorMessage = typeof result.moduleError === 'string'681 ? result.moduleError682 : `${Object.keys(result.moduleError)[0]}: ${Object.values(result.moduleError)[0]}`;683 log.moduleError = errorMessage;684 }685 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;686 }687 if(events.length > 0) log.events = events;688689 this.chainLog.push(log);690691 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {692 if (result.moduleError) throw Error(`${errorMessage}`);693 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));694 }695 return result;696 }697698 async callRpc(rpc: string, params?: any[]) {699 if(typeof params === 'undefined') params = [];700 if(this.api === null) throw Error('API not initialized');701 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);702703 const startTime = (new Date()).getTime();704 let result;705 let error = null;706 const log = {707 type: this.chainLogType.RPC,708 call: rpc,709 params,710 } as IUniqueHelperLog;711712 try {713 result = await this.constructApiCall(rpc, params);714 }715 catch(e) {716 error = e;717 }718719 const endTime = (new Date()).getTime();720721 log.executedAt = endTime;722 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';723 log.executionTime = endTime - startTime;724725 this.chainLog.push(log);726727 if(error !== null) throw error;728729 return result;730 }731732 getSignerAddress(signer: IKeyringPair | string): string {733 if(typeof signer === 'string') return signer;734 return signer.address;735 }736737 fetchAllPalletNames(): string[] {738 if(this.api === null) throw Error('API not initialized');739 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase()).sort();740 }741742 fetchMissingPalletNames(requiredPallets: string[]): string[] {743 const palletNames = this.fetchAllPalletNames();744 return requiredPallets.filter(p => !palletNames.includes(p));745 }746}747748749class HelperGroup<T extends ChainHelperBase> {750 helper: T;751752 constructor(uniqueHelper: T) {753 this.helper = uniqueHelper;754 }755}756757758class CollectionGroup extends HelperGroup<UniqueHelper> {759 /**760 * Get number of blocks when sponsored transaction is available.761 *762 * @param collectionId ID of collection763 * @param tokenId ID of token764 * @param addressObj address for which the sponsorship is checked765 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});766 * @returns number of blocks or null if sponsorship hasn't been set767 */768 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {769 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();770 }771772 /**773 * Get the number of created collections.774 *775 * @returns number of created collections776 */777 async getTotalCount(): Promise<number> {778 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();779 }780781 /**782 * Get information about the collection with additional data,783 * including the number of tokens it contains, its administrators,784 * the normalized address of the collection's owner, and decoded name and description.785 *786 * @param collectionId ID of collection787 * @example await getData(2)788 * @returns collection information object789 */790 async getData(collectionId: number): Promise<{791 id: number;792 name: string;793 description: string;794 tokensCount: number;795 admins: CrossAccountId[];796 normalizedOwner: TSubstrateAccount;797 raw: any798 } | null> {799 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);800 const humanCollection = collection.toHuman(), collectionData = {801 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],802 raw: humanCollection,803 } as any, jsonCollection = collection.toJSON();804 if (humanCollection === null) return null;805 collectionData.raw.limits = jsonCollection.limits;806 collectionData.raw.permissions = jsonCollection.permissions;807 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);808 for (const key of ['name', 'description']) {809 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);810 }811812 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))813 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)814 : 0;815 collectionData.admins = await this.getAdmins(collectionId);816817 return collectionData;818 }819820 /**821 * Get the addresses of the collection's administrators, optionally normalized.822 *823 * @param collectionId ID of collection824 * @param normalize whether to normalize the addresses to the default ss58 format825 * @example await getAdmins(1)826 * @returns array of administrators827 */828 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {829 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();830831 return normalize832 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())833 : admins;834 }835836 /**837 * Get the addresses added to the collection allow-list, optionally normalized.838 * @param collectionId ID of collection839 * @param normalize whether to normalize the addresses to the default ss58 format840 * @example await getAllowList(1)841 * @returns array of allow-listed addresses842 */843 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {844 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();845 return normalize846 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())847 : allowListed;848 }849850 /**851 * Get the effective limits of the collection instead of null for default values852 *853 * @param collectionId ID of collection854 * @example await getEffectiveLimits(2)855 * @returns object of collection limits856 */857 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {858 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();859 }860861 /**862 * Burns the collection if the signer has sufficient permissions and collection is empty.863 *864 * @param signer keyring of signer865 * @param collectionId ID of collection866 * @example await helper.collection.burn(aliceKeyring, 3);867 * @returns ```true``` if extrinsic success, otherwise ```false```868 */869 async burn(signer: TSigner, collectionId: number): Promise<boolean> {870 const result = await this.helper.executeExtrinsic(871 signer,872 'api.tx.unique.destroyCollection', [collectionId],873 true,874 );875876 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');877 }878879 /**880 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.881 *882 * @param signer keyring of signer883 * @param collectionId ID of collection884 * @param sponsorAddress Sponsor substrate address885 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")886 * @returns ```true``` if extrinsic success, otherwise ```false```887 */888 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {889 const result = await this.helper.executeExtrinsic(890 signer,891 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],892 true,893 );894895 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');896 }897898 /**899 * Confirms consent to sponsor the collection on behalf of the signer.900 *901 * @param signer keyring of signer902 * @param collectionId ID of collection903 * @example confirmSponsorship(aliceKeyring, 10)904 * @returns ```true``` if extrinsic success, otherwise ```false```905 */906 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {907 const result = await this.helper.executeExtrinsic(908 signer,909 'api.tx.unique.confirmSponsorship', [collectionId],910 true,911 );912913 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');914 }915916 /**917 * Removes the sponsor of a collection, regardless if it consented or not.918 *919 * @param signer keyring of signer920 * @param collectionId ID of collection921 * @example removeSponsor(aliceKeyring, 10)922 * @returns ```true``` if extrinsic success, otherwise ```false```923 */924 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {925 const result = await this.helper.executeExtrinsic(926 signer,927 'api.tx.unique.removeCollectionSponsor', [collectionId],928 true,929 );930931 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');932 }933934 /**935 * Sets the limits of the collection. At least one limit must be specified for a correct call.936 *937 * @param signer keyring of signer938 * @param collectionId ID of collection939 * @param limits collection limits object940 * @example941 * await setLimits(942 * aliceKeyring,943 * 10,944 * {945 * sponsorTransferTimeout: 0,946 * ownerCanDestroy: false947 * }948 * )949 * @returns ```true``` if extrinsic success, otherwise ```false```950 */951 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {952 const result = await this.helper.executeExtrinsic(953 signer,954 'api.tx.unique.setCollectionLimits', [collectionId, limits],955 true,956 );957958 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');959 }960961 /**962 * Changes the owner of the collection to the new Substrate address.963 *964 * @param signer keyring of signer965 * @param collectionId ID of collection966 * @param ownerAddress substrate address of new owner967 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")968 * @returns ```true``` if extrinsic success, otherwise ```false```969 */970 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {971 const result = await this.helper.executeExtrinsic(972 signer,973 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],974 true,975 );976977 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');978 }979980 /**981 * Adds a collection administrator.982 *983 * @param signer keyring of signer984 * @param collectionId ID of collection985 * @param adminAddressObj Administrator address (substrate or ethereum)986 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})987 * @returns ```true``` if extrinsic success, otherwise ```false```988 */989 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {990 const result = await this.helper.executeExtrinsic(991 signer,992 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],993 true,994 );995996 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');997 }998999 /**1000 * Removes a collection administrator.1001 *1002 * @param signer keyring of signer1003 * @param collectionId ID of collection1004 * @param adminAddressObj Administrator address (substrate or ethereum)1005 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})1006 * @returns ```true``` if extrinsic success, otherwise ```false```1007 */1008 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1009 const result = await this.helper.executeExtrinsic(1010 signer,1011 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],1012 true,1013 );10141015 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');1016 }10171018 /**1019 * Check if user is in allow list.1020 *1021 * @param collectionId ID of collection1022 * @param user Account to check1023 * @example await getAdmins(1)1024 * @returns is user in allow list1025 */1026 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {1027 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();1028 }10291030 /**1031 * Adds an address to allow list1032 * @param signer keyring of signer1033 * @param collectionId ID of collection1034 * @param addressObj address to add to the allow list1035 * @returns ```true``` if extrinsic success, otherwise ```false```1036 */1037 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1038 const result = await this.helper.executeExtrinsic(1039 signer,1040 'api.tx.unique.addToAllowList', [collectionId, addressObj],1041 true,1042 );10431044 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1045 }10461047 /**1048 * Removes an address from allow list1049 *1050 * @param signer keyring of signer1051 * @param collectionId ID of collection1052 * @param addressObj address to remove from the allow list1053 * @returns ```true``` if extrinsic success, otherwise ```false```1054 */1055 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1056 const result = await this.helper.executeExtrinsic(1057 signer,1058 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1059 true,1060 );10611062 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1063 }10641065 /**1066 * Sets onchain permissions for selected collection.1067 *1068 * @param signer keyring of signer1069 * @param collectionId ID of collection1070 * @param permissions collection permissions object1071 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1072 * @returns ```true``` if extrinsic success, otherwise ```false```1073 */1074 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1075 const result = await this.helper.executeExtrinsic(1076 signer,1077 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1078 true,1079 );10801081 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1082 }10831084 /**1085 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1086 *1087 * @param signer keyring of signer1088 * @param collectionId ID of collection1089 * @param permissions nesting permissions object1090 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1091 * @returns ```true``` if extrinsic success, otherwise ```false```1092 */1093 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1094 return await this.setPermissions(signer, collectionId, {nesting: permissions});1095 }10961097 /**1098 * Disables nesting for selected collection.1099 *1100 * @param signer keyring of signer1101 * @param collectionId ID of collection1102 * @example disableNesting(aliceKeyring, 10);1103 * @returns ```true``` if extrinsic success, otherwise ```false```1104 */1105 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1106 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1107 }11081109 /**1110 * Sets onchain properties to the collection.1111 *1112 * @param signer keyring of signer1113 * @param collectionId ID of collection1114 * @param properties array of property objects1115 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1116 * @returns ```true``` if extrinsic success, otherwise ```false```1117 */1118 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1119 const result = await this.helper.executeExtrinsic(1120 signer,1121 'api.tx.unique.setCollectionProperties', [collectionId, properties],1122 true,1123 );11241125 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1126 }11271128 /**1129 * Get collection properties.1130 *1131 * @param collectionId ID of collection1132 * @param propertyKeys optionally filter the returned properties to only these keys1133 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1134 * @returns array of key-value pairs1135 */1136 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1137 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1138 }11391140 async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1141 const api = this.helper.getApi();1142 const props = (await api.query.common.collectionProperties(collectionId)).toJSON();11431144 return (props! as any).consumedSpace;1145 }11461147 async getCollectionOptions(collectionId: number) {1148 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1149 }11501151 /**1152 * Deletes onchain properties from the collection.1153 *1154 * @param signer keyring of signer1155 * @param collectionId ID of collection1156 * @param propertyKeys array of property keys to delete1157 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1158 * @returns ```true``` if extrinsic success, otherwise ```false```1159 */1160 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1161 const result = await this.helper.executeExtrinsic(1162 signer,1163 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1164 true,1165 );11661167 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1168 }11691170 /**1171 * Changes the owner of the token.1172 *1173 * @param signer keyring of signer1174 * @param collectionId ID of collection1175 * @param tokenId ID of token1176 * @param addressObj address of a new owner1177 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1178 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1179 * @returns true if the token success, otherwise false1180 */1181 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1182 const result = await this.helper.executeExtrinsic(1183 signer,1184 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1185 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1186 );11871188 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1189 }11901191 /**1192 *1193 * Change ownership of a token(s) on behalf of the owner.1194 *1195 * @param signer keyring of signer1196 * @param collectionId ID of collection1197 * @param tokenId ID of token1198 * @param fromAddressObj address on behalf of which the token will be sent1199 * @param toAddressObj new token owner1200 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1201 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1202 * @returns true if the token success, otherwise false1203 */1204 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1205 const result = await this.helper.executeExtrinsic(1206 signer,1207 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1208 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1209 );1210 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1211 }12121213 /**1214 *1215 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1216 *1217 * @param signer keyring of signer1218 * @param collectionId ID of collection1219 * @param tokenId ID of token1220 * @param amount amount of tokens to be burned. For NFT must be set to 1n1221 * @example burnToken(aliceKeyring, 10, 5);1222 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1223 */1224 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1225 const burnResult = await this.helper.executeExtrinsic(1226 signer,1227 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1228 true, // `Unable to burn token for ${label}`,1229 );1230 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1231 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1232 return burnedTokens.success;1233 }12341235 /**1236 * Destroys a concrete instance of NFT on behalf of the owner1237 *1238 * @param signer keyring of signer1239 * @param collectionId ID of collection1240 * @param tokenId ID of token1241 * @param fromAddressObj address on behalf of which the token will be burnt1242 * @param amount amount of tokens to be burned. For NFT must be set to 1n1243 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1244 * @returns ```true``` if extrinsic success, otherwise ```false```1245 */1246 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1247 const burnResult = await this.helper.executeExtrinsic(1248 signer,1249 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1250 true, // `Unable to burn token from for ${label}`,1251 );1252 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1253 return burnedTokens.success && burnedTokens.tokens.length > 0;1254 }12551256 /**1257 * Set, change, or remove approved address to transfer the ownership of the NFT.1258 *1259 * @param signer keyring of signer1260 * @param collectionId ID of collection1261 * @param tokenId ID of token1262 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1263 * @param amount amount of token to be approved. For NFT must be set to 1n1264 * @returns ```true``` if extrinsic success, otherwise ```false```1265 */1266 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1267 const approveResult = await this.helper.executeExtrinsic(1268 signer,1269 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1270 true, // `Unable to approve token for ${label}`,1271 );12721273 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1274 }12751276 /**1277 * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1278 *1279 * @param signer keyring of signer1280 * @param collectionId ID of collection1281 * @param tokenId ID of token1282 * @param fromAddressObj Signer's Ethereum address containing her tokens1283 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1284 * @param amount amount of token to be approved. For NFT must be set to 1n1285 * @returns ```true``` if extrinsic success, otherwise ```false```1286 */1287 async approveTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1288 const approveResult = await this.helper.executeExtrinsic(1289 signer,1290 'api.tx.unique.approveFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1291 true, // `Unable to approve token for ${label}`,1292 );12931294 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1295 }12961297 /**1298 * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1299 *1300 * @param signer keyring of signer1301 * @param collectionId ID of collection1302 * @param tokenId ID of token1303 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1304 * @param amount amount of token to be approved. For NFT must be set to 1n1305 * @returns ```true``` if extrinsic success, otherwise ```false```1306 */1307 async approveTokenFromEth(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1308 const ethMirror = CrossAccountId.fromKeyring(signer).toEthereum();1309 return await this.approveTokenFrom(signer, collectionId, tokenId, ethMirror, toAddressObj, amount);1310 }13111312 /**1313 * Get the amount of token pieces approved to transfer or burn. Normally 0.1314 *1315 * @param collectionId ID of collection1316 * @param tokenId ID of token1317 * @param toAccountObj address which is approved to use token pieces1318 * @param fromAccountObj address which may have allowed the use of its owned tokens1319 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1320 * @returns number of approved to transfer pieces1321 */1322 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1323 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1324 }13251326 /**1327 * Get the last created token ID in a collection1328 *1329 * @param collectionId ID of collection1330 * @example getLastTokenId(10);1331 * @returns id of the last created token1332 */1333 async getLastTokenId(collectionId: number): Promise<number> {1334 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1335 }13361337 /**1338 * Check if token exists1339 *1340 * @param collectionId ID of collection1341 * @param tokenId ID of token1342 * @example doesTokenExist(10, 20);1343 * @returns true if the token exists, otherwise false1344 */1345 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1346 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1347 }1348}13491350class NFTnRFT extends CollectionGroup {1351 /**1352 * Get tokens owned by account1353 *1354 * @param collectionId ID of collection1355 * @param addressObj tokens owner1356 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1357 * @returns array of token ids owned by account1358 */1359 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1360 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1361 }13621363 /**1364 * Get token data1365 *1366 * @param collectionId ID of collection1367 * @param tokenId ID of token1368 * @param propertyKeys optionally filter the token properties to only these keys1369 * @param blockHashAt optionally query the data at some block with this hash1370 * @example getToken(10, 5);1371 * @returns human readable token data1372 */1373 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1374 properties: IProperty[];1375 owner: CrossAccountId;1376 normalizedOwner: CrossAccountId;1377 }| null> {1378 let tokenData;1379 if(typeof blockHashAt === 'undefined') {1380 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1381 }1382 else {1383 if(propertyKeys.length == 0) {1384 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1385 if(!collection) return null;1386 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1387 }1388 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1389 }1390 tokenData = tokenData.toHuman();1391 if (tokenData === null || tokenData.owner === null) return null;1392 const owner = {} as any;1393 for (const key of Object.keys(tokenData.owner)) {1394 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1395 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1396 : tokenData.owner[key];1397 }1398 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1399 return tokenData;1400 }14011402 /**1403 * Get token's owner1404 * @param collectionId ID of collection1405 * @param tokenId ID of token1406 * @param blockHashAt optionally query the data at the block with this hash1407 * @example getTokenOwner(10, 5);1408 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1409 */1410 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1411 let owner;1412 if (typeof blockHashAt === 'undefined') {1413 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1414 } else {1415 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1416 }1417 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1418 }14191420 /**1421 * Recursively find the address that owns the token1422 * @param collectionId ID of collection1423 * @param tokenId ID of token1424 * @param blockHashAt1425 * @example getTokenTopmostOwner(10, 5);1426 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1427 */1428 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1429 let owner;1430 if (typeof blockHashAt === 'undefined') {1431 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1432 } else {1433 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1434 }14351436 if (owner === null) return null;14371438 return owner.toHuman();1439 }14401441 /**1442 * Nest one token into another1443 * @param signer keyring of signer1444 * @param tokenObj token to be nested1445 * @param rootTokenObj token to be parent1446 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1447 * @returns ```true``` if extrinsic success, otherwise ```false```1448 */1449 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1450 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1451 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1452 if(!result) {1453 throw Error('Unable to nest token!');1454 }1455 return result;1456 }14571458 /**1459 * Remove token from nested state1460 * @param signer keyring of signer1461 * @param tokenObj token to unnest1462 * @param rootTokenObj parent of a token1463 * @param toAddressObj address of a new token owner1464 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1465 * @returns ```true``` if extrinsic success, otherwise ```false```1466 */1467 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1468 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1469 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1470 if(!result) {1471 throw Error('Unable to unnest token!');1472 }1473 return result;1474 }14751476 /**1477 * Set permissions to change token properties1478 *1479 * @param signer keyring of signer1480 * @param collectionId ID of collection1481 * @param permissions permissions to change a property by the collection admin or token owner1482 * @example setTokenPropertyPermissions(1483 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1484 * )1485 * @returns true if extrinsic success otherwise false1486 */1487 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1488 const result = await this.helper.executeExtrinsic(1489 signer,1490 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1491 true,1492 );14931494 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1495 }14961497 /**1498 * Get token property permissions.1499 *1500 * @param collectionId ID of collection1501 * @param propertyKeys optionally filter the returned property permissions to only these keys1502 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1503 * @returns array of key-permission pairs1504 */1505 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1506 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1507 }15081509 /**1510 * Set token properties1511 *1512 * @param signer keyring of signer1513 * @param collectionId ID of collection1514 * @param tokenId ID of token1515 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1516 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1517 * @returns ```true``` if extrinsic success, otherwise ```false```1518 */1519 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1520 const result = await this.helper.executeExtrinsic(1521 signer,1522 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1523 true,1524 );15251526 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1527 }15281529 /**1530 * Get properties, metadata assigned to a token.1531 *1532 * @param collectionId ID of collection1533 * @param tokenId ID of token1534 * @param propertyKeys optionally filter the returned properties to only these keys1535 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1536 * @returns array of key-value pairs1537 */1538 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1539 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1540 }15411542 /**1543 * Delete the provided properties of a token1544 * @param signer keyring of signer1545 * @param collectionId ID of collection1546 * @param tokenId ID of token1547 * @param propertyKeys property keys to be deleted1548 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1549 * @returns ```true``` if extrinsic success, otherwise ```false```1550 */1551 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1552 const result = await this.helper.executeExtrinsic(1553 signer,1554 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1555 true,1556 );15571558 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1559 }15601561 /**1562 * Mint new collection1563 *1564 * @param signer keyring of signer1565 * @param collectionOptions basic collection options and properties1566 * @param mode NFT or RFT type of a collection1567 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1568 * @returns object of the created collection1569 */1570 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1571 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1572 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1573 for (const key of ['name', 'description', 'tokenPrefix']) {1574 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);1575 }1576 const creationResult = await this.helper.executeExtrinsic(1577 signer,1578 'api.tx.unique.createCollectionEx', [collectionOptions],1579 true, // errorLabel,1580 );1581 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1582 }15831584 getCollectionObject(_collectionId: number): any {1585 return null;1586 }15871588 getTokenObject(_collectionId: number, _tokenId: number): any {1589 return null;1590 }15911592 /**1593 * Tells whether the given `owner` approves the `operator`.1594 * @param collectionId ID of collection1595 * @param owner owner address1596 * @param operator operator addrees1597 * @returns true if operator is enabled1598 */1599 async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1600 return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1601 }16021603 /** Sets or unsets the approval of a given operator.1604 * The `operator` is allowed to transfer all tokens of the `caller` on their behalf.1605 * @param operator Operator1606 * @param approved Should operator status be granted or revoked?1607 * @returns ```true``` if extrinsic success, otherwise ```false```1608 */1609 async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1610 const result = await this.helper.executeExtrinsic(1611 signer,1612 'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1613 true,1614 );1615 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1616 }1617}161816191620class NFTGroup extends NFTnRFT {1621 /**1622 * Get collection object1623 * @param collectionId ID of collection1624 * @example getCollectionObject(2);1625 * @returns instance of UniqueNFTCollection1626 */1627 getCollectionObject(collectionId: number): UniqueNFTCollection {1628 return new UniqueNFTCollection(collectionId, this.helper);1629 }16301631 /**1632 * Get token object1633 * @param collectionId ID of collection1634 * @param tokenId ID of token1635 * @example getTokenObject(10, 5);1636 * @returns instance of UniqueNFTToken1637 */1638 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1639 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1640 }16411642 /**1643 * Is token approved to transfer1644 * @param collectionId ID of collection1645 * @param tokenId ID of token1646 * @param toAccountObj address to be approved1647 * @returns ```true``` if extrinsic success, otherwise ```false```1648 */1649 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1650 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1651 }16521653 /**1654 * Changes the owner of the token.1655 *1656 * @param signer keyring of signer1657 * @param collectionId ID of collection1658 * @param tokenId ID of token1659 * @param addressObj address of a new owner1660 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1661 * @returns ```true``` if extrinsic success, otherwise ```false```1662 */1663 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1664 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1665 }16661667 /**1668 *1669 * Change ownership of a NFT on behalf of the owner.1670 *1671 * @param signer keyring of signer1672 * @param collectionId ID of collection1673 * @param tokenId ID of token1674 * @param fromAddressObj address on behalf of which the token will be sent1675 * @param toAddressObj new token owner1676 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1677 * @returns ```true``` if extrinsic success, otherwise ```false```1678 */1679 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1680 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1681 }16821683 /**1684 * Get tokens nested in the provided token1685 * @param collectionId ID of collection1686 * @param tokenId ID of token1687 * @param blockHashAt optionally query the data at the block with this hash1688 * @example getTokenChildren(10, 5);1689 * @returns tokens whose depth of nesting is <= 51690 */1691 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1692 let children;1693 if(typeof blockHashAt === 'undefined') {1694 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1695 } else {1696 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1697 }16981699 return children.toJSON().map((x: any) => {1700 return {collectionId: x.collection, tokenId: x.token};1701 });1702 }17031704 /**1705 * Mint new collection1706 * @param signer keyring of signer1707 * @param collectionOptions Collection options1708 * @example1709 * mintCollection(aliceKeyring, {1710 * name: 'New',1711 * description: 'New collection',1712 * tokenPrefix: 'NEW',1713 * })1714 * @returns object of the created collection1715 */1716 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1717 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1718 }17191720 /**1721 * Mint new token1722 * @param signer keyring of signer1723 * @param data token data1724 * @returns created token object1725 */1726 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1727 const creationResult = await this.helper.executeExtrinsic(1728 signer,1729 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1730 nft: {1731 properties: data.properties,1732 },1733 }],1734 true,1735 );1736 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1737 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1738 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1739 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1740 }17411742 /**1743 * Mint multiple NFT tokens1744 * @param signer keyring of signer1745 * @param collectionId ID of collection1746 * @param tokens array of tokens with owner and properties1747 * @example1748 * mintMultipleTokens(aliceKeyring, 10, [{1749 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1750 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1751 * },{1752 * owner: {Ethereum: "0x9F0583DbB855d..."},1753 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1754 * }]);1755 * @returns ```true``` if extrinsic success, otherwise ```false```1756 */1757 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1758 const creationResult = await this.helper.executeExtrinsic(1759 signer,1760 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1761 true,1762 );1763 const collection = this.getCollectionObject(collectionId);1764 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1765 }17661767 /**1768 * Mint multiple NFT tokens with one owner1769 * @param signer keyring of signer1770 * @param collectionId ID of collection1771 * @param owner tokens owner1772 * @param tokens array of tokens with owner and properties1773 * @example1774 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1775 * properties: [{1776 * key: "gender",1777 * value: "female",1778 * },{1779 * key: "age",1780 * value: "33",1781 * }],1782 * }]);1783 * @returns array of newly created tokens1784 */1785 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1786 const rawTokens = [];1787 for (const token of tokens) {1788 const raw = {NFT: {properties: token.properties}};1789 rawTokens.push(raw);1790 }1791 const creationResult = await this.helper.executeExtrinsic(1792 signer,1793 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1794 true,1795 );1796 const collection = this.getCollectionObject(collectionId);1797 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1798 }17991800 /**1801 * Set, change, or remove approved address to transfer the ownership of the NFT.1802 *1803 * @param signer keyring of signer1804 * @param collectionId ID of collection1805 * @param tokenId ID of token1806 * @param toAddressObj address to approve1807 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1808 * @returns ```true``` if extrinsic success, otherwise ```false```1809 */1810 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1811 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1812 }1813}181418151816class RFTGroup extends NFTnRFT {1817 /**1818 * Get collection object1819 * @param collectionId ID of collection1820 * @example getCollectionObject(2);1821 * @returns instance of UniqueRFTCollection1822 */1823 getCollectionObject(collectionId: number): UniqueRFTCollection {1824 return new UniqueRFTCollection(collectionId, this.helper);1825 }18261827 /**1828 * Get token object1829 * @param collectionId ID of collection1830 * @param tokenId ID of token1831 * @example getTokenObject(10, 5);1832 * @returns instance of UniqueNFTToken1833 */1834 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1835 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1836 }18371838 /**1839 * Get top 10 token owners with the largest number of pieces1840 * @param collectionId ID of collection1841 * @param tokenId ID of token1842 * @example getTokenTop10Owners(10, 5);1843 * @returns array of top 10 owners1844 */1845 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1846 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1847 }18481849 /**1850 * Get number of pieces owned by address1851 * @param collectionId ID of collection1852 * @param tokenId ID of token1853 * @param addressObj address token owner1854 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1855 * @returns number of pieces ownerd by address1856 */1857 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1858 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1859 }18601861 /**1862 * Transfer pieces of token to another address1863 * @param signer keyring of signer1864 * @param collectionId ID of collection1865 * @param tokenId ID of token1866 * @param addressObj address of a new owner1867 * @param amount number of pieces to be transfered1868 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1869 * @returns ```true``` if extrinsic success, otherwise ```false```1870 */1871 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1872 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1873 }18741875 /**1876 * Change ownership of some pieces of RFT on behalf of the owner.1877 * @param signer keyring of signer1878 * @param collectionId ID of collection1879 * @param tokenId ID of token1880 * @param fromAddressObj address on behalf of which the token will be sent1881 * @param toAddressObj new token owner1882 * @param amount number of pieces to be transfered1883 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1884 * @returns ```true``` if extrinsic success, otherwise ```false```1885 */1886 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1887 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1888 }18891890 /**1891 * Mint new collection1892 * @param signer keyring of signer1893 * @param collectionOptions Collection options1894 * @example1895 * mintCollection(aliceKeyring, {1896 * name: 'New',1897 * description: 'New collection',1898 * tokenPrefix: 'NEW',1899 * })1900 * @returns object of the created collection1901 */1902 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1903 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1904 }19051906 /**1907 * Mint new token1908 * @param signer keyring of signer1909 * @param data token data1910 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1911 * @returns created token object1912 */1913 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1914 const creationResult = await this.helper.executeExtrinsic(1915 signer,1916 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1917 refungible: {1918 pieces: data.pieces,1919 properties: data.properties,1920 },1921 }],1922 true,1923 );1924 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1925 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1926 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1927 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1928 }19291930 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1931 throw Error('Not implemented');1932 const creationResult = await this.helper.executeExtrinsic(1933 signer,1934 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1935 true, // `Unable to mint RFT tokens for ${label}`,1936 );1937 const collection = this.getCollectionObject(collectionId);1938 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1939 }19401941 /**1942 * Mint multiple RFT tokens with one owner1943 * @param signer keyring of signer1944 * @param collectionId ID of collection1945 * @param owner tokens owner1946 * @param tokens array of tokens with properties and pieces1947 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1948 * @returns array of newly created RFT tokens1949 */1950 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1951 const rawTokens = [];1952 for (const token of tokens) {1953 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1954 rawTokens.push(raw);1955 }1956 const creationResult = await this.helper.executeExtrinsic(1957 signer,1958 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1959 true,1960 );1961 const collection = this.getCollectionObject(collectionId);1962 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1963 }19641965 /**1966 * Destroys a concrete instance of RFT.1967 * @param signer keyring of signer1968 * @param collectionId ID of collection1969 * @param tokenId ID of token1970 * @param amount number of pieces to be burnt1971 * @example burnToken(aliceKeyring, 10, 5);1972 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1973 */1974 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1975 return await super.burnToken(signer, collectionId, tokenId, amount);1976 }19771978 /**1979 * Destroys a concrete instance of RFT on behalf of the owner.1980 * @param signer keyring of signer1981 * @param collectionId ID of collection1982 * @param tokenId ID of token1983 * @param fromAddressObj address on behalf of which the token will be burnt1984 * @param amount number of pieces to be burnt1985 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1986 * @returns ```true``` if extrinsic success, otherwise ```false```1987 */1988 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1989 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1990 }19911992 /**1993 * Set, change, or remove approved address to transfer the ownership of the RFT.1994 *1995 * @param signer keyring of signer1996 * @param collectionId ID of collection1997 * @param tokenId ID of token1998 * @param toAddressObj address to approve1999 * @param amount number of pieces to be approved2000 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);2001 * @returns true if the token success, otherwise false2002 */2003 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2004 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);2005 }20062007 /**2008 * Get total number of pieces2009 * @param collectionId ID of collection2010 * @param tokenId ID of token2011 * @example getTokenTotalPieces(10, 5);2012 * @returns number of pieces2013 */2014 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {2015 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();2016 }20172018 /**2019 * Change number of token pieces. Signer must be the owner of all token pieces.2020 * @param signer keyring of signer2021 * @param collectionId ID of collection2022 * @param tokenId ID of token2023 * @param amount new number of pieces2024 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);2025 * @returns true if the repartion was success, otherwise false2026 */2027 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {2028 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);2029 const repartitionResult = await this.helper.executeExtrinsic(2030 signer,2031 'api.tx.unique.repartition', [collectionId, tokenId, amount],2032 true,2033 );2034 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');2035 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');2036 }2037}203820392040class FTGroup extends CollectionGroup {2041 /**2042 * Get collection object2043 * @param collectionId ID of collection2044 * @example getCollectionObject(2);2045 * @returns instance of UniqueFTCollection2046 */2047 getCollectionObject(collectionId: number): UniqueFTCollection {2048 return new UniqueFTCollection(collectionId, this.helper);2049 }20502051 /**2052 * Mint new fungible collection2053 * @param signer keyring of signer2054 * @param collectionOptions Collection options2055 * @param decimalPoints number of token decimals2056 * @example2057 * mintCollection(aliceKeyring, {2058 * name: 'New',2059 * description: 'New collection',2060 * tokenPrefix: 'NEW',2061 * }, 18)2062 * @returns newly created fungible collection2063 */2064 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {2065 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object2066 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');2067 collectionOptions.mode = {fungible: decimalPoints};2068 for (const key of ['name', 'description', 'tokenPrefix']) {2069 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);2070 }2071 const creationResult = await this.helper.executeExtrinsic(2072 signer,2073 'api.tx.unique.createCollectionEx', [collectionOptions],2074 true,2075 );2076 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2077 }20782079 /**2080 * Mint tokens2081 * @param signer keyring of signer2082 * @param collectionId ID of collection2083 * @param owner address owner of new tokens2084 * @param amount amount of tokens to be meanted2085 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);2086 * @returns ```true``` if extrinsic success, otherwise ```false```2087 */2088 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2089 const creationResult = await this.helper.executeExtrinsic(2090 signer,2091 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2092 fungible: {2093 value: amount,2094 },2095 }],2096 true, // `Unable to mint fungible tokens for ${label}`,2097 );2098 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2099 }21002101 /**2102 * Mint multiple Fungible tokens with one owner2103 * @param signer keyring of signer2104 * @param collectionId ID of collection2105 * @param owner tokens owner2106 * @param tokens array of tokens with properties and pieces2107 * @returns ```true``` if extrinsic success, otherwise ```false```2108 */2109 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {2110 const rawTokens = [];2111 for (const token of tokens) {2112 const raw = {Fungible: {Value: token.value}};2113 rawTokens.push(raw);2114 }2115 const creationResult = await this.helper.executeExtrinsic(2116 signer,2117 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2118 true,2119 );2120 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2121 }21222123 /**2124 * Get the top 10 owners with the largest balance for the Fungible collection2125 * @param collectionId ID of collection2126 * @example getTop10Owners(10);2127 * @returns array of ```ICrossAccountId```2128 */2129 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2130 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2131 }21322133 /**2134 * Get account balance2135 * @param collectionId ID of collection2136 * @param addressObj address of owner2137 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2138 * @returns amount of fungible tokens owned by address2139 */2140 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2141 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2142 }21432144 /**2145 * Transfer tokens to address2146 * @param signer keyring of signer2147 * @param collectionId ID of collection2148 * @param toAddressObj address recipient2149 * @param amount amount of tokens to be sent2150 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2151 * @returns ```true``` if extrinsic success, otherwise ```false```2152 */2153 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2154 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2155 }21562157 /**2158 * Transfer some tokens on behalf of the owner.2159 * @param signer keyring of signer2160 * @param collectionId ID of collection2161 * @param fromAddressObj address on behalf of which tokens will be sent2162 * @param toAddressObj address where token to be sent2163 * @param amount number of tokens to be sent2164 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2165 * @returns ```true``` if extrinsic success, otherwise ```false```2166 */2167 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2168 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2169 }21702171 /**2172 * Destroy some amount of tokens2173 * @param signer keyring of signer2174 * @param collectionId ID of collection2175 * @param amount amount of tokens to be destroyed2176 * @example burnTokens(aliceKeyring, 10, 1000n);2177 * @returns ```true``` if extrinsic success, otherwise ```false```2178 */2179 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2180 return await super.burnToken(signer, collectionId, 0, amount);2181 }21822183 /**2184 * Burn some tokens on behalf of the owner.2185 * @param signer keyring of signer2186 * @param collectionId ID of collection2187 * @param fromAddressObj address on behalf of which tokens will be burnt2188 * @param amount amount of tokens to be burnt2189 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2190 * @returns ```true``` if extrinsic success, otherwise ```false```2191 */2192 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2193 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2194 }21952196 /**2197 * Get total collection supply2198 * @param collectionId2199 * @returns2200 */2201 async getTotalPieces(collectionId: number): Promise<bigint> {2202 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2203 }22042205 /**2206 * Set, change, or remove approved address to transfer tokens.2207 *2208 * @param signer keyring of signer2209 * @param collectionId ID of collection2210 * @param toAddressObj address to be approved2211 * @param amount amount of tokens to be approved2212 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2213 * @returns ```true``` if extrinsic success, otherwise ```false```2214 */2215 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2216 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2217 }22182219 /**2220 * Get amount of fungible tokens approved to transfer2221 * @param collectionId ID of collection2222 * @param fromAddressObj owner of tokens2223 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2224 * @returns number of tokens approved for the transfer2225 */2226 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2227 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2228 }2229}223022312232class ChainGroup extends HelperGroup<ChainHelperBase> {2233 /**2234 * Get system properties of a chain2235 * @example getChainProperties();2236 * @returns ss58Format, token decimals, and token symbol2237 */2238 getChainProperties(): IChainProperties {2239 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2240 return {2241 ss58Format: properties.ss58Format.toJSON(),2242 tokenDecimals: properties.tokenDecimals.toJSON(),2243 tokenSymbol: properties.tokenSymbol.toJSON(),2244 };2245 }22462247 /**2248 * Get chain header2249 * @example getLatestBlockNumber();2250 * @returns the number of the last block2251 */2252 async getLatestBlockNumber(): Promise<number> {2253 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2254 }22552256 /**2257 * Get block hash by block number2258 * @param blockNumber number of block2259 * @example getBlockHashByNumber(12345);2260 * @returns hash of a block2261 */2262 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2263 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2264 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2265 return blockHash;2266 }22672268 // TODO add docs2269 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2270 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2271 if (!blockHash) return null;2272 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2273 }22742275 /**2276 * Get latest relay block2277 * @returns {number} relay block2278 */2279 async getRelayBlockNumber(): Promise<bigint> {2280 const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2281 return BigInt(blockNumber);2282 }22832284 /**2285 * Get account nonce2286 * @param address substrate address2287 * @example getNonce("5GrwvaEF5zXb26Fz...");2288 * @returns number, account's nonce2289 */2290 async getNonce(address: TSubstrateAccount): Promise<number> {2291 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2292 }2293}22942295class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2296 /**2297 * Get substrate address balance2298 * @param address substrate address2299 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2300 * @returns amount of tokens on address2301 */2302 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2303 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2304 }23052306 /**2307 * Transfer tokens to substrate address2308 * @param signer keyring of signer2309 * @param address substrate address of a recipient2310 * @param amount amount of tokens to be transfered2311 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2312 * @returns ```true``` if extrinsic success, otherwise ```false```2313 */2314 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2315 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}`*/);23162317 let transfer = {from: null, to: null, amount: 0n} as any;2318 result.result.events.forEach(({event: {data, method, section}}) => {2319 if ((section === 'balances') && (method === 'Transfer')) {2320 transfer = {2321 from: this.helper.address.normalizeSubstrate(data[0]),2322 to: this.helper.address.normalizeSubstrate(data[1]),2323 amount: BigInt(data[2]),2324 };2325 }2326 });2327 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2328 && this.helper.address.normalizeSubstrate(address) === transfer.to2329 && BigInt(amount) === transfer.amount;2330 return isSuccess;2331 }23322333 /**2334 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2335 * @param address substrate address2336 * @returns2337 */2338 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2339 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2340 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2341 }23422343 async getLocked(address: TSubstrateAccount): Promise<[{id: string, amount: bigint, reason: string}]> {2344 const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2345 return locks.map((lock: any) => {return {id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons};});2346 }2347}23482349class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2350 /**2351 * Get ethereum address balance2352 * @param address ethereum address2353 * @example getEthereum("0x9F0583DbB855d...")2354 * @returns amount of tokens on address2355 */2356 async getEthereum(address: TEthereumAccount): Promise<bigint> {2357 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2358 }23592360 /**2361 * Transfer tokens to address2362 * @param signer keyring of signer2363 * @param address Ethereum address of a recipient2364 * @param amount amount of tokens to be transfered2365 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2366 * @returns ```true``` if extrinsic success, otherwise ```false```2367 */2368 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2369 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);23702371 let transfer = {from: null, to: null, amount: 0n} as any;2372 result.result.events.forEach(({event: {data, method, section}}) => {2373 if ((section === 'balances') && (method === 'Transfer')) {2374 transfer = {2375 from: data[0].toString(),2376 to: data[1].toString(),2377 amount: BigInt(data[2]),2378 };2379 }2380 });2381 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2382 && address === transfer.to2383 && BigInt(amount) === transfer.amount;2384 return isSuccess;2385 }2386}23872388class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2389 subBalanceGroup: SubstrateBalanceGroup<T>;2390 ethBalanceGroup: EthereumBalanceGroup<T>;23912392 constructor(helper: T) {2393 super(helper);2394 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2395 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2396 }23972398 getCollectionCreationPrice(): bigint {2399 return 2n * this.getOneTokenNominal();2400 }2401 /**2402 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2403 * @example getOneTokenNominal()2404 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2405 */2406 getOneTokenNominal(): bigint {2407 const chainProperties = this.helper.chain.getChainProperties();2408 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2409 }24102411 /**2412 * Get substrate address balance2413 * @param address substrate address2414 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2415 * @returns amount of tokens on address2416 */2417 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2418 return this.subBalanceGroup.getSubstrate(address);2419 }24202421 /**2422 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2423 * @param address substrate address2424 * @returns2425 */2426 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2427 return this.subBalanceGroup.getSubstrateFull(address);2428 }24292430 /**2431 * Get locked balances2432 * @param address substrate address2433 * @returns locked balances with reason via api.query.balances.locks2434 */2435 getLocked(address: TSubstrateAccount) {2436 return this.subBalanceGroup.getLocked(address);2437 }24382439 /**2440 * Get ethereum address balance2441 * @param address ethereum address2442 * @example getEthereum("0x9F0583DbB855d...")2443 * @returns amount of tokens on address2444 */2445 getEthereum(address: TEthereumAccount): Promise<bigint> {2446 return this.ethBalanceGroup.getEthereum(address);2447 }24482449 async setBalanceSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint, reservedAmount = 0n) {2450 await this.helper.executeExtrinsic(signer, 'api.tx.balances.setBalance', [address, amount, reservedAmount], true);2451 }24522453 /**2454 * Transfer tokens to substrate address2455 * @param signer keyring of signer2456 * @param address substrate address of a recipient2457 * @param amount amount of tokens to be transfered2458 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2459 * @returns ```true``` if extrinsic success, otherwise ```false```2460 */2461 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2462 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2463 }24642465 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2466 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);24672468 let transfer = {from: null, to: null, amount: 0n} as any;2469 result.result.events.forEach(({event: {data, method, section}}) => {2470 if ((section === 'balances') && (method === 'Transfer')) {2471 transfer = {2472 from: this.helper.address.normalizeSubstrate(data[0]),2473 to: this.helper.address.normalizeSubstrate(data[1]),2474 amount: BigInt(data[2]),2475 };2476 }2477 });2478 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2479 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2480 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2481 return isSuccess;2482 }24832484 /**2485 * Transfer tokens with the unlock period2486 * @param signer signers Keyring2487 * @param address Substrate address of recipient2488 * @param schedule Schedule params2489 * @example vestedTransfer(signer, recepient.address, 20000, 100, 10, 50 * nominal); // total amount of vested tokens will be 100 * 50 = 50002490 */2491 async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: {start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}): Promise<void> {2492 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2493 const event = result.result.events2494 .find(e => e.event.section === 'vesting' &&2495 e.event.method === 'VestingScheduleAdded' &&2496 e.event.data[0].toHuman() === signer.address);2497 if (!event) throw Error('Cannot find transfer in events');2498 }24992500 /**2501 * Get schedule for recepient of vested transfer2502 * @param address Substrate address of recipient2503 * @returns2504 */2505 async getVestingSchedules(address: TSubstrateAccount): Promise<{start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}[]> {2506 const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2507 return schedule.map((schedule: any) => {2508 return {2509 start: BigInt(schedule.start),2510 period: BigInt(schedule.period),2511 periodCount: BigInt(schedule.periodCount),2512 perPeriod: BigInt(schedule.perPeriod),2513 };2514 });2515 }25162517 /**2518 * Claim vested tokens2519 * @param signer signers Keyring2520 */2521 async claim(signer: TSigner) {2522 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2523 const event = result.result.events2524 .find(e => e.event.section === 'vesting' &&2525 e.event.method === 'Claimed' &&2526 e.event.data[0].toHuman() === signer.address);2527 if (!event) throw Error('Cannot find claim in events');2528 }2529}25302531class AddressGroup extends HelperGroup<ChainHelperBase> {2532 /**2533 * Normalizes the address to the specified ss58 format, by default ```42```.2534 * @param address substrate address2535 * @param ss58Format format for address conversion, by default ```42```2536 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2537 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2538 */2539 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2540 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2541 }25422543 /**2544 * Get address in the connected chain format2545 * @param address substrate address2546 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2547 * @returns address in chain format2548 */2549 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2550 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2551 }25522553 /**2554 * Get substrate mirror of an ethereum address2555 * @param ethAddress ethereum address2556 * @param toChainFormat false for normalized account2557 * @example ethToSubstrate('0x9F0583DbB855d...')2558 * @returns substrate mirror of a provided ethereum address2559 */2560 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2561 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2562 }25632564 /**2565 * Get ethereum mirror of a substrate address2566 * @param subAddress substrate account2567 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2568 * @returns ethereum mirror of a provided substrate address2569 */2570 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2571 return CrossAccountId.translateSubToEth(subAddress);2572 }25732574 /**2575 * Encode key to substrate address2576 * @param key key for encoding address2577 * @param ss58Format prefix for encoding to the address of the corresponding network2578 * @returns encoded substrate address2579 */2580 encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2581 const u8a :Uint8Array = typeof key === 'string'2582 ? hexToU8a(key)2583 : typeof key === 'bigint'2584 ? hexToU8a(key.toString(16))2585 : key;25862587 if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2588 throw new Error(`ss58Format is not valid, received ${typeofss58Format} "${ss58Format}"`);2589 }25902591 const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2592 if (!allowedDecodedLengths.includes(u8a.length)) {2593 throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2594 }25952596 const u8aPrefix = ss58Format < 642597 ? new Uint8Array([ss58Format])2598 : new Uint8Array([2599 ((ss58Format & 0xfc) >> 2) | 0x40,2600 (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2601 ]);26022603 const input = u8aConcat(u8aPrefix, u8a);26042605 return base58Encode(u8aConcat(2606 input,2607 blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2608 ));2609 }26102611 /**2612 * Restore substrate address from bigint representation2613 * @param number decimal representation of substrate address2614 * @returns substrate address2615 */2616 restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2617 if (this.helper.api === null) {2618 throw 'Not connected';2619 }2620 const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2621 if (res === undefined || res === null) {2622 throw 'Restore address error';2623 }2624 return res.toString();2625 }26262627 /**2628 * Convert etherium cross account id to substrate cross account id2629 * @param ethCrossAccount etherium cross account2630 * @returns substrate cross account id2631 */2632 convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2633 if (ethCrossAccount.sub === '0') {2634 return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2635 }26362637 const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2638 return {Substrate: ss58};2639 }26402641 paraSiblingSovereignAccount(paraid: number) {2642 // We are getting a *sibling* parachain sovereign account,2643 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2644 const siblingPrefix = '0x7369626c';26452646 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2647 const suffix = '000000000000000000000000000000000000000000000000';26482649 return siblingPrefix + encodedParaId + suffix;2650 }2651}26522653class StakingGroup extends HelperGroup<UniqueHelper> {2654 /**2655 * Stake tokens for App Promotion2656 * @param signer keyring of signer2657 * @param amountToStake amount of tokens to stake2658 * @param label extra label for log2659 * @returns2660 */2661 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2662 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2663 const _stakeResult = await this.helper.executeExtrinsic(2664 signer, 'api.tx.appPromotion.stake',2665 [amountToStake], true,2666 );2667 // TODO extract info from stakeResult2668 return true;2669 }26702671 /**2672 * Unstake all staked tokens2673 * @param signer keyring of signer2674 * @param amountToUnstake amount of tokens to unstake2675 * @param label extra label for log2676 * @returns block hash where unstake happened2677 */2678 async unstakeAll(signer: TSigner, label?: string): Promise<string> {2679 if(typeof label === 'undefined') label = `${signer.address}`;2680 const unstakeResult = await this.helper.executeExtrinsic(2681 signer, 'api.tx.appPromotion.unstakeAll',2682 [], true,2683 );2684 return unstakeResult.blockHash;2685 }26862687 /**2688 * Unstake the part of a staked tokens2689 * @param signer keyring of signer2690 * @param amount amount of tokens to unstake2691 * @param label extra label for log2692 * @returns block hash where unstake happened2693 */2694 async unstakePartial(signer: TSigner, amount: bigint, label?: string): Promise<string> {2695 if(typeof label === 'undefined') label = `${signer.address}`;2696 const unstakeResult = await this.helper.executeExtrinsic(2697 signer, 'api.tx.appPromotion.unstakePartial',2698 [amount], true,2699 );2700 return unstakeResult.blockHash;2701 }27022703 /**2704 * Get total number of active stakes2705 * @param address substrate address2706 * @returns {number}2707 */2708 async getStakesNumber(address: ICrossAccountId): Promise<number> {2709 if (address.Ethereum) throw Error('only substrate address');2710 return (await this.helper.callRpc('api.query.appPromotion.stakesPerAccount', [address.Substrate])).toNumber();2711 }27122713 /**2714 * Get total staked amount for address2715 * @param address substrate or ethereum address2716 * @returns total staked amount2717 */2718 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2719 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2720 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2721 }27222723 /**2724 * Get total staked per block2725 * @param address substrate or ethereum address2726 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2727 */2728 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2729 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2730 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2731 return {2732 block: block.toBigInt(),2733 amount: amount.toBigInt(),2734 };2735 });2736 }27372738 /**2739 * Get total pending unstake amount for address2740 * @param address substrate or ethereum address2741 * @returns total pending unstake amount2742 */2743 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2744 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2745 }27462747 /**2748 * Get pending unstake amount per block for address2749 * @param address substrate or ethereum address2750 * @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 block2751 */2752 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2753 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2754 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2755 return {2756 block: block.toBigInt(),2757 amount: amount.toBigInt(),2758 };2759 });2760 return result;2761 }2762}27632764class SchedulerGroup extends HelperGroup<UniqueHelper> {2765 constructor(helper: UniqueHelper) {2766 super(helper);2767 }27682769 cancelScheduled(signer: TSigner, scheduledId: string) {2770 return this.helper.executeExtrinsic(2771 signer,2772 'api.tx.scheduler.cancelNamed',2773 [scheduledId],2774 true,2775 );2776 }27772778 changePriority(signer: TSigner, scheduledId: string, priority: number) {2779 return this.helper.executeExtrinsic(2780 signer,2781 'api.tx.scheduler.changeNamedPriority',2782 [scheduledId, priority],2783 true,2784 );2785 }27862787 scheduleAt<T extends UniqueHelper>(2788 executionBlockNumber: number,2789 options: ISchedulerOptions = {},2790 ) {2791 return this.schedule<T>('schedule', executionBlockNumber, options);2792 }27932794 scheduleAfter<T extends UniqueHelper>(2795 blocksBeforeExecution: number,2796 options: ISchedulerOptions = {},2797 ) {2798 return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2799 }28002801 schedule<T extends UniqueHelper>(2802 scheduleFn: 'schedule' | 'scheduleAfter',2803 blocksNum: number,2804 options: ISchedulerOptions = {},2805 ) {2806 // eslint-disable-next-line @typescript-eslint/naming-convention2807 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2808 return this.helper.clone(ScheduledHelperType, {2809 scheduleFn,2810 blocksNum,2811 options,2812 }) as T;2813 }2814}28152816class CollatorSelectionGroup extends HelperGroup<UniqueHelper> {2817 //todo:collator documentation2818 addInvulnerable(signer: TSigner, address: string) {2819 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.addInvulnerable', [address]);2820 }28212822 removeInvulnerable(signer: TSigner, address: string) {2823 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.removeInvulnerable', [address]);2824 }28252826 async getInvulnerables(): Promise<string[]> {2827 return (await this.helper.callRpc('api.query.collatorSelection.invulnerables')).map((x: any) => x.toHuman());2828 }28292830 /** and also total max invulnerables */2831 maxCollators(): number {2832 return (this.helper.getApi().consts.configuration.defaultCollatorSelectionMaxCollators.toJSON() as number);2833 }28342835 async getDesiredCollators(): Promise<number> {2836 return (await this.helper.callRpc('api.query.configuration.collatorSelectionDesiredCollatorsOverride')).toNumber();2837 }28382839 setLicenseBond(signer: TSigner, amount: bigint) {2840 return this.helper.executeExtrinsic(signer, 'api.tx.configuration.setCollatorSelectionLicenseBond', [amount]);2841 }28422843 async getLicenseBond(): Promise<bigint> {2844 return (await this.helper.callRpc('api.query.configuration.collatorSelectionLicenseBondOverride')).toBigInt();2845 }28462847 obtainLicense(signer: TSigner) {2848 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.getLicense', []);2849 }28502851 releaseLicense(signer: TSigner) {2852 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.releaseLicense', []);2853 }28542855 forceReleaseLicense(signer: TSigner, released: string) {2856 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.forceReleaseLicense', [released]);2857 }28582859 async hasLicense(address: string): Promise<bigint> {2860 return (await this.helper.callRpc('api.query.collatorSelection.licenseDepositOf', [address])).toBigInt();2861 }28622863 onboard(signer: TSigner) {2864 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.onboard', []);2865 }28662867 offboard(signer: TSigner) {2868 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.offboard', []);2869 }28702871 async getCandidates(): Promise<string[]> {2872 return (await this.helper.callRpc('api.query.collatorSelection.candidates')).map((x: any) => x.toHuman());2873 }2874}28752876class PreimageGroup extends HelperGroup<UniqueHelper> {2877 async getPreimageInfo(h256: string) {2878 return (await this.helper.callRpc('api.query.preimage.statusFor', [h256])).toJSON();2879 }28802881 /**2882 * Create a preimage with a hex or a byte array.2883 * @param signer keyring of the signer.2884 * @param bytes preimage encoded in hex or a byte array, e.g. an extrinsic call.2885 * @example await notePreimage(preimageMaker,2886 * helper.constructApiCall('api.tx.identity.forceInsertIdentities', [identitiesToAdd]).method.toHex()2887 * );2888 * @returns promise of extrinsic execution.2889 */2890 notePreimage(signer: TSigner, bytes: string | Uint8Array) {2891 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.notePreimage', [bytes]);2892 }28932894 /**2895 * Delete an existing preimage and return the deposit.2896 * @param signer keyring of the signer - either the owner or the preimage manager (sudo).2897 * @param h256 hash of the preimage.2898 * @returns promise of extrinsic execution.2899 */2900 unnotePreimage(signer: TSigner, h256: string) {2901 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unnotePreimage', [h256]);2902 }29032904 /**2905 * Request a preimage be uploaded to the chain without paying any fees or deposits.2906 * @param signer keyring of the signer - either the owner or the preimage manager (sudo).2907 * @param h256 hash of the preimage.2908 * @returns promise of extrinsic execution.2909 */2910 requestPreimage(signer: TSigner, h256: string) {2911 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.requestPreimage', [h256]);2912 }29132914 /**2915 * Clear a previously made request for a preimage.2916 * @param signer keyring of the signer - either the owner or the preimage manager (sudo).2917 * @param h256 hash of the preimage.2918 * @returns promise of extrinsic execution.2919 */2920 unrequestPreimage(signer: TSigner, h256: string) {2921 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unrequestPreimage', [h256]);2922 }2923}29242925class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2926 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2927 await this.helper.executeExtrinsic(2928 signer,2929 'api.tx.foreignAssets.registerForeignAsset',2930 [ownerAddress, location, metadata],2931 true,2932 );2933 }29342935 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2936 await this.helper.executeExtrinsic(2937 signer,2938 'api.tx.foreignAssets.updateForeignAsset',2939 [foreignAssetId, location, metadata],2940 true,2941 );2942 }2943}29442945class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2946 palletName: string;29472948 constructor(helper: T, palletName: string) {2949 super(helper);29502951 this.palletName = palletName;2952 }29532954 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {2955 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);2956 }29572958 async setSafeXcmVersion(signer: TSigner, version: number) {2959 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.forceDefaultXcmVersion`, [version], true);2960 }29612962 async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {2963 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);2964 }29652966 async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint, xcmVersion = 3) {2967 const destinationContent = {2968 parents: 0,2969 interior: {2970 X1: {2971 Parachain: destinationParaId,2972 },2973 },2974 };29752976 const beneficiaryContent = {2977 parents: 0,2978 interior: {2979 X1: {2980 AccountId32: {2981 network: 'Any',2982 id: targetAccount,2983 },2984 },2985 },2986 };29872988 const assetsContent = [2989 {2990 id: {2991 Concrete: {2992 parents: 0,2993 interior: 'Here',2994 },2995 },2996 fun: {2997 Fungible: amount,2998 },2999 },3000 ];30013002 let destination;3003 let beneficiary;3004 let assets;30053006 if (xcmVersion == 2) {3007 destination = {V1: destinationContent};3008 beneficiary = {V1: beneficiaryContent};3009 assets = {V1: assetsContent};30103011 } else if (xcmVersion == 3) {3012 destination = {V2: destinationContent};3013 beneficiary = {V2: beneficiaryContent};3014 assets = {V2: assetsContent};30153016 } else {3017 throw Error('Unknown XCM version: ' + xcmVersion);3018 }30193020 const feeAssetItem = 0;30213022 await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);3023 }30243025 async send(signer: IKeyringPair, destination: any, message: any) {3026 await this.helper.executeExtrinsic(3027 signer,3028 `api.tx.${this.palletName}.send`,3029 [3030 destination,3031 message,3032 ],3033 true,3034 );3035 }3036}30373038class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {3039 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {3040 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);3041 }30423043 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {3044 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);3045 }30463047 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {3048 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);3049 }3050}30513052class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {3053 async accounts(address: string, currencyId: any) {3054 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;3055 return BigInt(free);3056 }3057}30583059class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {3060 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {3061 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);3062 }30633064 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {3065 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);3066 }30673068 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {3069 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);3070 }30713072 async account(assetId: string | number, address: string) {3073 const accountAsset = (3074 await this.helper.callRpc('api.query.assets.account', [assetId, address])3075 ).toJSON()! as any;30763077 if (accountAsset !== null) {3078 return BigInt(accountAsset['balance']);3079 } else {3080 return null;3081 }3082 }3083}30843085class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {3086 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {3087 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);3088 }3089}30903091class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {3092 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {3093 const apiPrefix = 'api.tx.assetManager.';30943095 const registerTx = this.helper.constructApiCall(3096 apiPrefix + 'registerForeignAsset',3097 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],3098 );30993100 const setUnitsTx = this.helper.constructApiCall(3101 apiPrefix + 'setAssetUnitsPerSecond',3102 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],3103 );31043105 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);3106 const encodedProposal = batchCall?.method.toHex() || '';3107 return encodedProposal;3108 }31093110 async assetTypeId(location: any) {3111 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);3112 }3113}31143115class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {3116 notePreimagePallet: string;31173118 constructor(helper: MoonbeamHelper, options: {[key: string]: any} = {}) {3119 super(helper);3120 this.notePreimagePallet = options.notePreimagePallet;3121 }31223123 async notePreimage(signer: TSigner, encodedProposal: string) {3124 await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);3125 }31263127 externalProposeMajority(proposal: any) {3128 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);3129 }31303131 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {3132 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);3133 }31343135 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {3136 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);3137 }3138}31393140class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {3141 collective: string;31423143 constructor(helper: MoonbeamHelper, collective: string) {3144 super(helper);31453146 this.collective = collective;3147 }31483149 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {3150 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);3151 }31523153 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {3154 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);3155 }31563157 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {3158 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);3159 }31603161 async proposalCount() {3162 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));3163 }3164}31653166export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;3167export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;31683169export class UniqueHelper extends ChainHelperBase {3170 balance: BalanceGroup<UniqueHelper>;3171 collection: CollectionGroup;3172 nft: NFTGroup;3173 rft: RFTGroup;3174 ft: FTGroup;3175 staking: StakingGroup;3176 scheduler: SchedulerGroup;3177 collatorSelection: CollatorSelectionGroup;3178 preimage: PreimageGroup;3179 foreignAssets: ForeignAssetsGroup;3180 xcm: XcmGroup<UniqueHelper>;3181 xTokens: XTokensGroup<UniqueHelper>;3182 tokens: TokensGroup<UniqueHelper>;31833184 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3185 super(logger, options.helperBase ?? UniqueHelper);31863187 this.balance = new BalanceGroup(this);3188 this.collection = new CollectionGroup(this);3189 this.nft = new NFTGroup(this);3190 this.rft = new RFTGroup(this);3191 this.ft = new FTGroup(this);3192 this.staking = new StakingGroup(this);3193 this.scheduler = new SchedulerGroup(this);3194 this.collatorSelection = new CollatorSelectionGroup(this);3195 this.preimage = new PreimageGroup(this);3196 this.foreignAssets = new ForeignAssetsGroup(this);3197 this.xcm = new XcmGroup(this, 'polkadotXcm');3198 this.xTokens = new XTokensGroup(this);3199 this.tokens = new TokensGroup(this);3200 }32013202 getSudo<T extends UniqueHelper>() {3203 // eslint-disable-next-line @typescript-eslint/naming-convention3204 const SudoHelperType = SudoHelper(this.helperBase);3205 return this.clone(SudoHelperType) as T;3206 }3207}32083209export class XcmChainHelper extends ChainHelperBase {3210 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {3211 const wsProvider = new WsProvider(wsEndpoint);3212 this.api = new ApiPromise({3213 provider: wsProvider,3214 });3215 await this.api.isReadyOrError;3216 this.network = await UniqueHelper.detectNetwork(this.api);3217 }3218}32193220export class RelayHelper extends XcmChainHelper {3221 balance: SubstrateBalanceGroup<RelayHelper>;3222 xcm: XcmGroup<RelayHelper>;32233224 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3225 super(logger, options.helperBase ?? RelayHelper);32263227 this.balance = new SubstrateBalanceGroup(this);3228 this.xcm = new XcmGroup(this, 'xcmPallet');3229 }3230}32313232export class WestmintHelper extends XcmChainHelper {3233 balance: SubstrateBalanceGroup<WestmintHelper>;3234 xcm: XcmGroup<WestmintHelper>;3235 assets: AssetsGroup<WestmintHelper>;3236 xTokens: XTokensGroup<WestmintHelper>;32373238 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3239 super(logger, options.helperBase ?? WestmintHelper);32403241 this.balance = new SubstrateBalanceGroup(this);3242 this.xcm = new XcmGroup(this, 'polkadotXcm');3243 this.assets = new AssetsGroup(this);3244 this.xTokens = new XTokensGroup(this);3245 }3246}32473248export class MoonbeamHelper extends XcmChainHelper {3249 balance: EthereumBalanceGroup<MoonbeamHelper>;3250 assetManager: MoonbeamAssetManagerGroup;3251 assets: AssetsGroup<MoonbeamHelper>;3252 xTokens: XTokensGroup<MoonbeamHelper>;3253 democracy: MoonbeamDemocracyGroup;3254 collective: {3255 council: MoonbeamCollectiveGroup,3256 techCommittee: MoonbeamCollectiveGroup,3257 };32583259 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3260 super(logger, options.helperBase ?? MoonbeamHelper);32613262 this.balance = new EthereumBalanceGroup(this);3263 this.assetManager = new MoonbeamAssetManagerGroup(this);3264 this.assets = new AssetsGroup(this);3265 this.xTokens = new XTokensGroup(this);3266 this.democracy = new MoonbeamDemocracyGroup(this, options);3267 this.collective = {3268 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),3269 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),3270 };3271 }3272}32733274export class AstarHelper extends XcmChainHelper {3275 balance: SubstrateBalanceGroup<AstarHelper>;3276 assets: AssetsGroup<AstarHelper>;3277 xcm: XcmGroup<AstarHelper>;32783279 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3280 super(logger, options.helperBase ?? AstarHelper);32813282 this.balance = new SubstrateBalanceGroup(this);3283 this.assets = new AssetsGroup(this);3284 this.xcm = new XcmGroup(this, 'polkadotXcm');3285 }32863287 getSudo<T extends UniqueHelper>() {3288 // eslint-disable-next-line @typescript-eslint/naming-convention3289 const SudoHelperType = SudoHelper(this.helperBase);3290 return this.clone(SudoHelperType) as T;3291 }3292}32933294export class AcalaHelper extends XcmChainHelper {3295 balance: SubstrateBalanceGroup<AcalaHelper>;3296 assetRegistry: AcalaAssetRegistryGroup;3297 xTokens: XTokensGroup<AcalaHelper>;3298 tokens: TokensGroup<AcalaHelper>;3299 xcm: XcmGroup<AcalaHelper>;33003301 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3302 super(logger, options.helperBase ?? AcalaHelper);33033304 this.balance = new SubstrateBalanceGroup(this);3305 this.assetRegistry = new AcalaAssetRegistryGroup(this);3306 this.xTokens = new XTokensGroup(this);3307 this.tokens = new TokensGroup(this);3308 this.xcm = new XcmGroup(this, 'polkadotXcm');3309 }33103311 getSudo<T extends AcalaHelper>() {3312 // eslint-disable-next-line @typescript-eslint/naming-convention3313 const SudoHelperType = SudoHelper(this.helperBase);3314 return this.clone(SudoHelperType) as T;3315 }3316}33173318// eslint-disable-next-line @typescript-eslint/naming-convention3319function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3320 return class extends Base {3321 scheduleFn: 'schedule' | 'scheduleAfter';3322 blocksNum: number;3323 options: ISchedulerOptions;33243325 constructor(...args: any[]) {3326 const logger = args[0] as ILogger;3327 const options = args[1] as {3328 scheduleFn: 'schedule' | 'scheduleAfter',3329 blocksNum: number,3330 options: ISchedulerOptions3331 };33323333 super(logger);33343335 this.scheduleFn = options.scheduleFn;3336 this.blocksNum = options.blocksNum;3337 this.options = options.options;3338 }33393340 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3341 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);33423343 const mandatorySchedArgs = [3344 this.blocksNum,3345 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3346 this.options.priority ?? null,3347 scheduledTx,3348 ];33493350 let schedArgs;3351 let scheduleFn;33523353 if (this.options.scheduledId) {3354 schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];33553356 if (this.scheduleFn == 'schedule') {3357 scheduleFn = 'scheduleNamed';3358 } else if (this.scheduleFn == 'scheduleAfter') {3359 scheduleFn = 'scheduleNamedAfter';3360 }3361 } else {3362 schedArgs = mandatorySchedArgs;3363 scheduleFn = this.scheduleFn;3364 }33653366 const extrinsic = 'api.tx.scheduler.' + scheduleFn;33673368 return super.executeExtrinsic(3369 sender,3370 extrinsic,3371 schedArgs,3372 expectSuccess,3373 );3374 }3375 };3376}33773378// eslint-disable-next-line @typescript-eslint/naming-convention3379function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3380 return class extends Base {3381 constructor(...args: any[]) {3382 super(...args);3383 }33843385 async executeExtrinsic(3386 sender: IKeyringPair,3387 extrinsic: string,3388 params: any[],3389 expectSuccess?: boolean,3390 options: Partial<SignerOptions>|null = null,3391 ): Promise<ITransactionResult> {3392 const call = this.constructApiCall(extrinsic, params);3393 const result = await super.executeExtrinsic(3394 sender,3395 'api.tx.sudo.sudo',3396 [call],3397 expectSuccess,3398 options,3399 );34003401 if (result.status === 'Fail') return result;34023403 const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;3404 if (data.isErr) {3405 if (data.asErr.isModule) {3406 const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;3407 const metaError = super.getApi()?.registry.findMetaError(error);3408 throw new Error(`${metaError.section}.${metaError.name}`);3409 } else {3410 throw new Error(data.asErr.toHuman());3411 }3412 }3413 return result;3414 }3415 };3416}34173418export class UniqueBaseCollection {3419 helper: UniqueHelper;3420 collectionId: number;34213422 constructor(collectionId: number, uniqueHelper: UniqueHelper) {3423 this.collectionId = collectionId;3424 this.helper = uniqueHelper;3425 }34263427 async getData() {3428 return await this.helper.collection.getData(this.collectionId);3429 }34303431 async getLastTokenId() {3432 return await this.helper.collection.getLastTokenId(this.collectionId);3433 }34343435 async doesTokenExist(tokenId: number) {3436 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3437 }34383439 async getAdmins() {3440 return await this.helper.collection.getAdmins(this.collectionId);3441 }34423443 async getAllowList() {3444 return await this.helper.collection.getAllowList(this.collectionId);3445 }34463447 async getEffectiveLimits() {3448 return await this.helper.collection.getEffectiveLimits(this.collectionId);3449 }34503451 async getProperties(propertyKeys?: string[] | null) {3452 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3453 }34543455 async getPropertiesConsumedSpace() {3456 return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3457 }34583459 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3460 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3461 }34623463 async getOptions() {3464 return await this.helper.collection.getCollectionOptions(this.collectionId);3465 }34663467 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3468 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3469 }34703471 async confirmSponsorship(signer: TSigner) {3472 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3473 }34743475 async removeSponsor(signer: TSigner) {3476 return await this.helper.collection.removeSponsor(signer, this.collectionId);3477 }34783479 async setLimits(signer: TSigner, limits: ICollectionLimits) {3480 return await this.helper.collection.setLimits(signer, this.collectionId, limits);3481 }34823483 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3484 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3485 }34863487 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3488 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3489 }34903491 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3492 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3493 }34943495 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3496 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3497 }34983499 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3500 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3501 }35023503 async setProperties(signer: TSigner, properties: IProperty[]) {3504 return await this.helper.collection.setProperties(signer, this.collectionId, properties);3505 }35063507 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3508 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3509 }35103511 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3512 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3513 }35143515 async enableNesting(signer: TSigner, permissions: INestingPermissions) {3516 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3517 }35183519 async disableNesting(signer: TSigner) {3520 return await this.helper.collection.disableNesting(signer, this.collectionId);3521 }35223523 async burn(signer: TSigner) {3524 return await this.helper.collection.burn(signer, this.collectionId);3525 }35263527 scheduleAt<T extends UniqueHelper>(3528 executionBlockNumber: number,3529 options: ISchedulerOptions = {},3530 ) {3531 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3532 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3533 }35343535 scheduleAfter<T extends UniqueHelper>(3536 blocksBeforeExecution: number,3537 options: ISchedulerOptions = {},3538 ) {3539 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3540 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3541 }35423543 getSudo<T extends UniqueHelper>() {3544 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3545 }3546}354735483549export class UniqueNFTCollection extends UniqueBaseCollection {3550 getTokenObject(tokenId: number) {3551 return new UniqueNFToken(tokenId, this);3552 }35533554 async getTokensByAddress(addressObj: ICrossAccountId) {3555 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3556 }35573558 async getToken(tokenId: number, blockHashAt?: string) {3559 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3560 }35613562 async getTokenOwner(tokenId: number, blockHashAt?: string) {3563 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3564 }35653566 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3567 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3568 }35693570 async getTokenChildren(tokenId: number, blockHashAt?: string) {3571 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3572 }35733574 async getPropertyPermissions(propertyKeys: string[] | null = null) {3575 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3576 }35773578 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3579 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3580 }35813582 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3583 const api = this.helper.getApi();3584 const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();35853586 return (props! as any).consumedSpace;3587 }35883589 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3590 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3591 }35923593 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3594 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3595 }35963597 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3598 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3599 }36003601 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3602 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3603 }36043605 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3606 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3607 }36083609 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3610 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3611 }36123613 async burnToken(signer: TSigner, tokenId: number) {3614 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3615 }36163617 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3618 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3619 }36203621 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3622 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3623 }36243625 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3626 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3627 }36283629 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3630 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3631 }36323633 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3634 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3635 }36363637 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3638 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3639 }36403641 scheduleAt<T extends UniqueHelper>(3642 executionBlockNumber: number,3643 options: ISchedulerOptions = {},3644 ) {3645 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3646 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3647 }36483649 scheduleAfter<T extends UniqueHelper>(3650 blocksBeforeExecution: number,3651 options: ISchedulerOptions = {},3652 ) {3653 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3654 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3655 }36563657 getSudo<T extends UniqueHelper>() {3658 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3659 }3660}366136623663export class UniqueRFTCollection extends UniqueBaseCollection {3664 getTokenObject(tokenId: number) {3665 return new UniqueRFToken(tokenId, this);3666 }36673668 async getToken(tokenId: number, blockHashAt?: string) {3669 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3670 }36713672 async getTokenOwner(tokenId: number, blockHashAt?: string) {3673 return await this.helper.rft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3674 }36753676 async getTokensByAddress(addressObj: ICrossAccountId) {3677 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3678 }36793680 async getTop10TokenOwners(tokenId: number) {3681 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3682 }36833684 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3685 return await this.helper.rft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3686 }36873688 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3689 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3690 }36913692 async getTokenTotalPieces(tokenId: number) {3693 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3694 }36953696 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3697 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3698 }36993700 async getPropertyPermissions(propertyKeys: string[] | null = null) {3701 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3702 }37033704 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3705 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3706 }37073708 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3709 const api = this.helper.getApi();3710 const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();37113712 return (props! as any).consumedSpace;3713 }37143715 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3716 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3717 }37183719 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3720 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3721 }37223723 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3724 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3725 }37263727 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3728 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3729 }37303731 async mintToken(signer: TSigner, pieces = 1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3732 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3733 }37343735 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3736 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3737 }37383739 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3740 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3741 }37423743 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3744 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3745 }37463747 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3748 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3749 }37503751 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3752 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3753 }37543755 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3756 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3757 }37583759 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3760 return await this.helper.rft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3761 }37623763 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3764 return await this.helper.rft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3765 }37663767 scheduleAt<T extends UniqueHelper>(3768 executionBlockNumber: number,3769 options: ISchedulerOptions = {},3770 ) {3771 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3772 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3773 }37743775 scheduleAfter<T extends UniqueHelper>(3776 blocksBeforeExecution: number,3777 options: ISchedulerOptions = {},3778 ) {3779 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3780 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3781 }37823783 getSudo<T extends UniqueHelper>() {3784 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3785 }3786}378737883789export class UniqueFTCollection extends UniqueBaseCollection {3790 async getBalance(addressObj: ICrossAccountId) {3791 return await this.helper.ft.getBalance(this.collectionId, addressObj);3792 }37933794 async getTotalPieces() {3795 return await this.helper.ft.getTotalPieces(this.collectionId);3796 }37973798 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3799 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3800 }38013802 async getTop10Owners() {3803 return await this.helper.ft.getTop10Owners(this.collectionId);3804 }38053806 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3807 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3808 }38093810 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3811 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3812 }38133814 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3815 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3816 }38173818 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3819 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3820 }38213822 async burnTokens(signer: TSigner, amount=1n) {3823 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3824 }38253826 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3827 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3828 }38293830 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3831 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3832 }38333834 scheduleAt<T extends UniqueHelper>(3835 executionBlockNumber: number,3836 options: ISchedulerOptions = {},3837 ) {3838 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3839 return new UniqueFTCollection(this.collectionId, scheduledHelper);3840 }38413842 scheduleAfter<T extends UniqueHelper>(3843 blocksBeforeExecution: number,3844 options: ISchedulerOptions = {},3845 ) {3846 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3847 return new UniqueFTCollection(this.collectionId, scheduledHelper);3848 }38493850 getSudo<T extends UniqueHelper>() {3851 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3852 }3853}385438553856export class UniqueBaseToken {3857 collection: UniqueNFTCollection | UniqueRFTCollection;3858 collectionId: number;3859 tokenId: number;38603861 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3862 this.collection = collection;3863 this.collectionId = collection.collectionId;3864 this.tokenId = tokenId;3865 }38663867 async getNextSponsored(addressObj: ICrossAccountId) {3868 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3869 }38703871 async getProperties(propertyKeys?: string[] | null) {3872 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3873 }38743875 async getTokenPropertiesConsumedSpace() {3876 return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3877 }38783879 async setProperties(signer: TSigner, properties: IProperty[]) {3880 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3881 }38823883 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3884 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3885 }38863887 async doesExist() {3888 return await this.collection.doesTokenExist(this.tokenId);3889 }38903891 nestingAccount() {3892 return this.collection.helper.util.getTokenAccount(this);3893 }38943895 scheduleAt<T extends UniqueHelper>(3896 executionBlockNumber: number,3897 options: ISchedulerOptions = {},3898 ) {3899 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3900 return new UniqueBaseToken(this.tokenId, scheduledCollection);3901 }39023903 scheduleAfter<T extends UniqueHelper>(3904 blocksBeforeExecution: number,3905 options: ISchedulerOptions = {},3906 ) {3907 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3908 return new UniqueBaseToken(this.tokenId, scheduledCollection);3909 }39103911 getSudo<T extends UniqueHelper>() {3912 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3913 }3914}391539163917export class UniqueNFToken extends UniqueBaseToken {3918 collection: UniqueNFTCollection;39193920 constructor(tokenId: number, collection: UniqueNFTCollection) {3921 super(tokenId, collection);3922 this.collection = collection;3923 }39243925 async getData(blockHashAt?: string) {3926 return await this.collection.getToken(this.tokenId, blockHashAt);3927 }39283929 async getOwner(blockHashAt?: string) {3930 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3931 }39323933 async getTopmostOwner(blockHashAt?: string) {3934 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3935 }39363937 async getChildren(blockHashAt?: string) {3938 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3939 }39403941 async nest(signer: TSigner, toTokenObj: IToken) {3942 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3943 }39443945 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3946 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3947 }39483949 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3950 return await this.collection.transferToken(signer, this.tokenId, addressObj);3951 }39523953 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3954 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3955 }39563957 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3958 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3959 }39603961 async isApproved(toAddressObj: ICrossAccountId) {3962 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3963 }39643965 async burn(signer: TSigner) {3966 return await this.collection.burnToken(signer, this.tokenId);3967 }39683969 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3970 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3971 }39723973 scheduleAt<T extends UniqueHelper>(3974 executionBlockNumber: number,3975 options: ISchedulerOptions = {},3976 ) {3977 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3978 return new UniqueNFToken(this.tokenId, scheduledCollection);3979 }39803981 scheduleAfter<T extends UniqueHelper>(3982 blocksBeforeExecution: number,3983 options: ISchedulerOptions = {},3984 ) {3985 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3986 return new UniqueNFToken(this.tokenId, scheduledCollection);3987 }39883989 getSudo<T extends UniqueHelper>() {3990 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3991 }3992}39933994export class UniqueRFToken extends UniqueBaseToken {3995 collection: UniqueRFTCollection;39963997 constructor(tokenId: number, collection: UniqueRFTCollection) {3998 super(tokenId, collection);3999 this.collection = collection;4000 }40014002 async getData(blockHashAt?: string) {4003 return await this.collection.getToken(this.tokenId, blockHashAt);4004 }40054006 async getOwner(blockHashAt?: string) {4007 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);4008 }40094010 async getTop10Owners() {4011 return await this.collection.getTop10TokenOwners(this.tokenId);4012 }40134014 async getTopmostOwner(blockHashAt?: string) {4015 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);4016 }40174018 async nest(signer: TSigner, toTokenObj: IToken) {4019 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);4020 }40214022 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {4023 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);4024 }40254026 async getBalance(addressObj: ICrossAccountId) {4027 return await this.collection.getTokenBalance(this.tokenId, addressObj);4028 }40294030 async getTotalPieces() {4031 return await this.collection.getTokenTotalPieces(this.tokenId);4032 }40334034 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {4035 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);4036 }40374038 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {4039 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);4040 }40414042 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {4043 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);4044 }40454046 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {4047 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);4048 }40494050 async repartition(signer: TSigner, amount: bigint) {4051 return await this.collection.repartitionToken(signer, this.tokenId, amount);4052 }40534054 async burn(signer: TSigner, amount=1n) {4055 return await this.collection.burnToken(signer, this.tokenId, amount);4056 }40574058 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {4059 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);4060 }40614062 scheduleAt<T extends UniqueHelper>(4063 executionBlockNumber: number,4064 options: ISchedulerOptions = {},4065 ) {4066 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);4067 return new UniqueRFToken(this.tokenId, scheduledCollection);4068 }40694070 scheduleAfter<T extends UniqueHelper>(4071 blocksBeforeExecution: number,4072 options: ISchedulerOptions = {},4073 ) {4074 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);4075 return new UniqueRFToken(this.tokenId, scheduledCollection);4076 }40774078 getSudo<T extends UniqueHelper>() {4079 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());4080 }4081}tests/src/xcm/xcmQuartz.test.tsdiffbeforeafterboth--- a/tests/src/xcm/xcmQuartz.test.ts
+++ b/tests/src/xcm/xcmQuartz.test.ts
@@ -19,6 +19,7 @@
import config from '../config';
import {XcmV2TraitsError} from '../interfaces';
import {itSub, expect, describeXCM, usingPlaygrounds, usingKaruraPlaygrounds, usingRelayPlaygrounds, usingMoonriverPlaygrounds, usingStateminePlaygrounds, usingShidenPlaygrounds} from '../util';
+import {DevUniqueHelper} from '../util/playgrounds/unique.dev';
const QUARTZ_CHAIN = 2095;
const STATEMINE_CHAIN = 1000;
@@ -641,63 +642,277 @@
console.log('[Karura -> Quartz] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(qtzFees));
expect(qtzFees == 0n).to.be.true;
});
+
+ itSub('Karura can send only up to its balance', async ({helper}) => {
+ // set Karura's sovereign account's balance
+ const karuraBalance = 10000n * (10n ** QTZ_DECIMALS);
+ const karuraSovereignAccount = helper.address.paraSiblingSovereignAccount(KARURA_CHAIN);
+ await helper.getSudo().balance.setBalanceSubstrate(alice, karuraSovereignAccount, karuraBalance);
+
+ const moreThanKaruraHas = karuraBalance * 2n;
+
+ let targetAccountBalance = 0n;
+ const [targetAccount] = await helper.arrange.createAccounts([targetAccountBalance], alice);
+
+ const quartzMultilocation = {
+ V1: {
+ parents: 1,
+ interior: {
+ X1: {Parachain: QUARTZ_CHAIN},
+ },
+ },
+ };
+
+ const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(
+ targetAccount.addressRaw,
+ {
+ Concrete: {
+ parents: 0,
+ interior: 'Here',
+ },
+ },
+ moreThanKaruraHas,
+ );
+
+ // Try to trick Quartz
+ await usingKaruraPlaygrounds(karuraUrl, async (helper) => {
+ await helper.getSudo().xcm.send(alice, quartzMultilocation, maliciousXcmProgram);
+ });
+
+ const maxWaitBlocks = 3;
+
+ const xcmpQueueFailEvent = await helper.wait.eventOutcome<XcmV2TraitsError>(
+ maxWaitBlocks,
+ 'xcmpQueue',
+ 'Fail',
+ );
+
+ expect(
+ xcmpQueueFailEvent != null,
+ '\'xcmpQueue.FailEvent\' event is expected',
+ ).to.be.true;
+
+ expect(
+ xcmpQueueFailEvent!.isFailedToTransactAsset,
+ 'The XCM error should be \'FailedToTransactAsset\'',
+ ).to.be.true;
+
+ targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);
+ expect(targetAccountBalance).to.be.equal(0n);
+
+ // But Karura still can send the correct amount
+ const validTransferAmount = karuraBalance / 2n;
+ const validXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(
+ targetAccount.addressRaw,
+ {
+ Concrete: {
+ parents: 0,
+ interior: 'Here',
+ },
+ },
+ validTransferAmount,
+ );
+
+ await usingKaruraPlaygrounds(karuraUrl, async (helper) => {
+ await helper.getSudo().xcm.send(alice, quartzMultilocation, validXcmProgram);
+ });
+
+ await helper.wait.newBlocks(maxWaitBlocks);
+
+ targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);
+ expect(targetAccountBalance).to.be.equal(validTransferAmount);
+ });
+
+ itSub('Should not accept reserve transfer of QTZ from Karura', async ({helper}) => {
+ const testAmount = 10_000n * (10n ** QTZ_DECIMALS);
+ const [targetAccount] = await helper.arrange.createAccounts([0n], alice);
+
+ const quartzMultilocation = {
+ V1: {
+ parents: 1,
+ interior: {
+ X1: {
+ Parachain: QUARTZ_CHAIN,
+ },
+ },
+ },
+ };
+
+ const maliciousXcmProgram = helper.arrange.makeXcmProgramReserveAssetDeposited(
+ targetAccount.addressRaw,
+ {
+ Concrete: {
+ parents: 1,
+ interior: {
+ X1: {
+ Parachain: QUARTZ_CHAIN,
+ },
+ },
+ },
+ },
+ testAmount,
+ );
+
+ await usingKaruraPlaygrounds(karuraUrl, async (helper) => {
+ await helper.getSudo().xcm.send(alice, quartzMultilocation, maliciousXcmProgram);
+ });
+
+ const maxWaitBlocks = 3;
+
+ const xcmpQueueFailEvent = await helper.wait.eventOutcome<XcmV2TraitsError>(
+ maxWaitBlocks,
+ 'xcmpQueue',
+ 'Fail',
+ );
+
+ expect(
+ xcmpQueueFailEvent != null,
+ '\'xcmpQueue.FailEvent\' event is expected',
+ ).to.be.true;
+
+ expect(
+ xcmpQueueFailEvent!.isUntrustedReserveLocation,
+ 'The XCM error should be \'isUntrustedReserveLocation\'',
+ ).to.be.true;
+
+ const accountBalance = await helper.balance.getSubstrate(targetAccount.address);
+ expect(accountBalance).to.be.equal(0n);
+ });
});
-// These tests are relevant only when the foreign asset pallet is disabled
+// These tests are relevant only when
+// the the corresponding foreign assets are not registered
describeXCM('[XCM] Integration test: Quartz rejects non-native tokens', () => {
let alice: IKeyringPair;
+ let alith: IKeyringPair;
+
+ const testAmount = 100_000_000_000n;
+ let quartzParachainJunction;
+ let quartzAccountJunction;
+ let quartzParachainMultilocation: any;
+ let quartzAccountMultilocation: any;
+ let quartzCombinedMultilocation: any;
+
before(async () => {
await usingPlaygrounds(async (helper, privateKey) => {
alice = await privateKey('//Alice');
- // Set the default version to wrap the first message to other chains.
- await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);
- });
- });
+ quartzParachainJunction = {Parachain: QUARTZ_CHAIN};
+ quartzAccountJunction = {
+ AccountId32: {
+ network: 'Any',
+ id: alice.addressRaw,
+ },
+ };
- itSub('Quartz rejects KAR tokens from Karura', async ({helper}) => {
- await usingKaruraPlaygrounds(karuraUrl, async (helper) => {
- const destination = {
+ quartzParachainMultilocation = {
V1: {
parents: 1,
interior: {
- X2: [
- {Parachain: QUARTZ_CHAIN},
- {
- AccountId32: {
- network: 'Any',
- id: alice.addressRaw,
- },
- },
- ],
+ X1: quartzParachainJunction,
+ },
+ },
+ };
+
+ quartzAccountMultilocation = {
+ V1: {
+ parents: 0,
+ interior: {
+ X1: quartzAccountJunction,
},
},
};
- const id = {
- Token: 'KAR',
+ quartzCombinedMultilocation = {
+ V1: {
+ parents: 1,
+ interior: {
+ X2: [quartzParachainJunction, quartzAccountJunction],
+ },
+ },
};
- await helper.xTokens.transfer(alice, id, 100_000_000_000n, destination, 'Unlimited');
+ // Set the default version to wrap the first message to other chains.
+ await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);
+ });
+
+ // eslint-disable-next-line require-await
+ await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {
+ alith = helper.account.alithAccount();
});
+ });
+ const expectFailedToTransact = async (network: string, helper: DevUniqueHelper) => {
const maxWaitBlocks = 3;
- const xcmpQueueFailEvent = await helper.wait.event(maxWaitBlocks, 'xcmpQueue', 'Fail');
+ const xcmpQueueFailEvent = await helper.wait.eventOutcome<XcmV2TraitsError>(
+ maxWaitBlocks,
+ 'xcmpQueue',
+ 'Fail',
+ );
expect(
xcmpQueueFailEvent != null,
- '[Karura] xcmpQueue.FailEvent event is expected',
+ `[reject ${network} tokens] 'xcmpQueue.FailEvent' event is expected`,
).to.be.true;
- const event = xcmpQueueFailEvent!.event;
- const outcome = event.data[1] as XcmV2TraitsError;
-
expect(
- outcome.isFailedToTransactAsset,
- '[Karura] The XCM error should be `FailedToTransactAsset`',
+ xcmpQueueFailEvent!.isFailedToTransactAsset,
+ `[reject ${network} tokens] The XCM error should be 'FailedToTransactAsset'`,
).to.be.true;
+ };
+
+ itSub('Quartz rejects KAR tokens from Karura', async ({helper}) => {
+ await usingKaruraPlaygrounds(karuraUrl, async (helper) => {
+ const id = {
+ Token: 'KAR',
+ };
+ const destination = quartzCombinedMultilocation;
+ await helper.xTokens.transfer(alice, id, testAmount, destination, 'Unlimited');
+ });
+
+ await expectFailedToTransact('KAR', helper);
+ });
+
+ itSub('Quartz rejects MOVR tokens from Moonriver', async ({helper}) => {
+ await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {
+ const id = 'SelfReserve';
+ const destination = quartzCombinedMultilocation;
+ await helper.xTokens.transfer(alith, id, testAmount, destination, 'Unlimited');
+ });
+
+ await expectFailedToTransact('MOVR', helper);
+ });
+
+ itSub('Quartz rejects SDN tokens from Shiden', async ({helper}) => {
+ await usingShidenPlaygrounds(shidenUrl, async (helper) => {
+ const destinationParachain = quartzParachainMultilocation;
+ const beneficiary = quartzAccountMultilocation;
+ const assets = {
+ V1: [{
+ id: {
+ Concrete: {
+ parents: 0,
+ interior: 'Here',
+ },
+ },
+ fun: {
+ Fungible: testAmount,
+ },
+ }],
+ };
+ const feeAssetItem = 0;
+
+ await helper.executeExtrinsic(alice, 'api.tx.polkadotXcm.reserveWithdrawAssets', [
+ destinationParachain,
+ beneficiary,
+ assets,
+ feeAssetItem,
+ ]);
+ });
+
+ await expectFailedToTransact('SDN', helper);
});
});
@@ -981,6 +1196,16 @@
console.log('[Moonriver -> Quartz] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(qtzFees));
expect(qtzFees == 0n).to.be.true;
});
+
+ // eslint-disable-next-line require-await
+ itSub.skip('Moonriver can send only up to its balance', async ({helper}) => {
+ throw Error('Not yet implemented');
+ });
+
+ // eslint-disable-next-line require-await
+ itSub.skip('Should not accept reserve transfer of QTZ from Moonriver', async ({helper}) => {
+ throw Error('Not yet implemented');
+ });
});
describeXCM('[XCM] Integration test: Exchanging tokens with Shiden', () => {
@@ -1193,4 +1418,140 @@
console.log(`QTZ Balance on Quartz after XCM is: ${balanceQTZ}`);
expect(balanceQTZ).to.eq(balanceAfterQuartzToShidenXCM + qtzFromShidenTransfered);
});
+
+ itSub('Shiden can send only up to its balance', async ({helper}) => {
+ // set Shiden's sovereign account's balance
+ const shidenBalance = 10000n * (10n ** QTZ_DECIMALS);
+ const shidenSovereignAccount = helper.address.paraSiblingSovereignAccount(SHIDEN_CHAIN);
+ await helper.getSudo().balance.setBalanceSubstrate(alice, shidenSovereignAccount, shidenBalance);
+
+ const moreThanShidenHas = shidenBalance * 2n;
+
+ let targetAccountBalance = 0n;
+ const [targetAccount] = await helper.arrange.createAccounts([targetAccountBalance], alice);
+
+ const quartzMultilocation = {
+ V1: {
+ parents: 1,
+ interior: {
+ X1: {Parachain: QUARTZ_CHAIN},
+ },
+ },
+ };
+
+ const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(
+ targetAccount.addressRaw,
+ {
+ Concrete: {
+ parents: 0,
+ interior: 'Here',
+ },
+ },
+ moreThanShidenHas,
+ );
+
+ // Try to trick Quartz
+ await usingShidenPlaygrounds(shidenUrl, async (helper) => {
+ await helper.getSudo().xcm.send(alice, quartzMultilocation, maliciousXcmProgram);
+ });
+
+ const maxWaitBlocks = 3;
+
+ const xcmpQueueFailEvent = await helper.wait.eventOutcome<XcmV2TraitsError>(
+ maxWaitBlocks,
+ 'xcmpQueue',
+ 'Fail',
+ );
+
+ expect(
+ xcmpQueueFailEvent != null,
+ '\'xcmpQueue.FailEvent\' event is expected',
+ ).to.be.true;
+
+ expect(
+ xcmpQueueFailEvent!.isFailedToTransactAsset,
+ 'The XCM error should be \'FailedToTransactAsset\'',
+ ).to.be.true;
+
+ targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);
+ expect(targetAccountBalance).to.be.equal(0n);
+
+ // But Shiden still can send the correct amount
+ const validTransferAmount = shidenBalance / 2n;
+ const validXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(
+ targetAccount.addressRaw,
+ {
+ Concrete: {
+ parents: 0,
+ interior: 'Here',
+ },
+ },
+ validTransferAmount,
+ );
+
+ await usingShidenPlaygrounds(shidenUrl, async (helper) => {
+ await helper.getSudo().xcm.send(alice, quartzMultilocation, validXcmProgram);
+ });
+
+ await helper.wait.newBlocks(maxWaitBlocks);
+
+ targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);
+ expect(targetAccountBalance).to.be.equal(validTransferAmount);
+ });
+
+ itSub('Should not accept reserve transfer of QTZ from Shiden', async ({helper}) => {
+ const testAmount = 10_000n * (10n ** QTZ_DECIMALS);
+ const [targetAccount] = await helper.arrange.createAccounts([0n], alice);
+
+ const quartzMultilocation = {
+ V1: {
+ parents: 1,
+ interior: {
+ X1: {
+ Parachain: QUARTZ_CHAIN,
+ },
+ },
+ },
+ };
+
+ const maliciousXcmProgram = helper.arrange.makeXcmProgramReserveAssetDeposited(
+ targetAccount.addressRaw,
+ {
+ Concrete: {
+ parents: 1,
+ interior: {
+ X1: {
+ Parachain: QUARTZ_CHAIN,
+ },
+ },
+ },
+ },
+ testAmount,
+ );
+
+ await usingShidenPlaygrounds(shidenUrl, async (helper) => {
+ await helper.getSudo().xcm.send(alice, quartzMultilocation, maliciousXcmProgram);
+ });
+
+ const maxWaitBlocks = 3;
+
+ const xcmpQueueFailEvent = await helper.wait.eventOutcome<XcmV2TraitsError>(
+ maxWaitBlocks,
+ 'xcmpQueue',
+ 'Fail',
+ );
+
+ expect(
+ xcmpQueueFailEvent != null,
+ '\'xcmpQueue.FailEvent\' event is expected',
+ ).to.be.true;
+
+ expect(
+ xcmpQueueFailEvent!.isUntrustedReserveLocation,
+ 'The XCM error should be \'isUntrustedReserveLocation\'',
+ ).to.be.true;
+
+ const accountBalance = await helper.balance.getSubstrate(targetAccount.address);
+ expect(accountBalance).to.be.equal(0n);
+ });
});
tests/src/xcm/xcmUnique.test.tsdiffbeforeafterboth--- a/tests/src/xcm/xcmUnique.test.ts
+++ b/tests/src/xcm/xcmUnique.test.ts
@@ -19,6 +19,7 @@
import config from '../config';
import {XcmV2TraitsError} from '../interfaces';
import {itSub, expect, describeXCM, usingPlaygrounds, usingAcalaPlaygrounds, usingRelayPlaygrounds, usingMoonbeamPlaygrounds, usingStatemintPlaygrounds, usingAstarPlaygrounds} from '../util';
+import {DevUniqueHelper} from '../util/playgrounds/unique.dev';
const UNIQUE_CHAIN = 2037;
const STATEMINT_CHAIN = 1000;
@@ -643,63 +644,277 @@
console.log('[Acala -> Unique] transaction fees on Unique: %s UNQ', helper.util.bigIntToDecimals(unqFees));
expect(unqFees == 0n).to.be.true;
});
+
+ itSub('Acala can send only up to its balance', async ({helper}) => {
+ // set Acala's sovereign account's balance
+ const acalaBalance = 10000n * (10n ** UNQ_DECIMALS);
+ const acalaSovereignAccount = helper.address.paraSiblingSovereignAccount(ACALA_CHAIN);
+ await helper.getSudo().balance.setBalanceSubstrate(alice, acalaSovereignAccount, acalaBalance);
+
+ const moreThanAcalaHas = acalaBalance * 2n;
+
+ let targetAccountBalance = 0n;
+ const [targetAccount] = await helper.arrange.createAccounts([targetAccountBalance], alice);
+
+ const uniqueMultilocation = {
+ V1: {
+ parents: 1,
+ interior: {
+ X1: {Parachain: UNIQUE_CHAIN},
+ },
+ },
+ };
+
+ const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(
+ targetAccount.addressRaw,
+ {
+ Concrete: {
+ parents: 0,
+ interior: 'Here',
+ },
+ },
+ moreThanAcalaHas,
+ );
+
+ // Try to trick Unique
+ await usingAcalaPlaygrounds(acalaUrl, async (helper) => {
+ await helper.getSudo().xcm.send(alice, uniqueMultilocation, maliciousXcmProgram);
+ });
+
+ const maxWaitBlocks = 3;
+
+ const xcmpQueueFailEvent = await helper.wait.eventOutcome<XcmV2TraitsError>(
+ maxWaitBlocks,
+ 'xcmpQueue',
+ 'Fail',
+ );
+
+ expect(
+ xcmpQueueFailEvent != null,
+ '\'xcmpQueue.FailEvent\' event is expected',
+ ).to.be.true;
+
+ expect(
+ xcmpQueueFailEvent!.isFailedToTransactAsset,
+ 'The XCM error should be \'FailedToTransactAsset\'',
+ ).to.be.true;
+
+ targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);
+ expect(targetAccountBalance).to.be.equal(0n);
+
+ // But Acala still can send the correct amount
+ const validTransferAmount = acalaBalance / 2n;
+ const validXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(
+ targetAccount.addressRaw,
+ {
+ Concrete: {
+ parents: 0,
+ interior: 'Here',
+ },
+ },
+ validTransferAmount,
+ );
+
+ await usingAcalaPlaygrounds(acalaUrl, async (helper) => {
+ await helper.getSudo().xcm.send(alice, uniqueMultilocation, validXcmProgram);
+ });
+
+ await helper.wait.newBlocks(maxWaitBlocks);
+
+ targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);
+ expect(targetAccountBalance).to.be.equal(validTransferAmount);
+ });
+
+ itSub('Should not accept reserve transfer of UNQ from Acala', async ({helper}) => {
+ const testAmount = 10_000n * (10n ** UNQ_DECIMALS);
+ const [targetAccount] = await helper.arrange.createAccounts([0n], alice);
+
+ const uniqueMultilocation = {
+ V1: {
+ parents: 1,
+ interior: {
+ X1: {
+ Parachain: UNIQUE_CHAIN,
+ },
+ },
+ },
+ };
+
+ const maliciousXcmProgram = helper.arrange.makeXcmProgramReserveAssetDeposited(
+ targetAccount.addressRaw,
+ {
+ Concrete: {
+ parents: 1,
+ interior: {
+ X1: {
+ Parachain: UNIQUE_CHAIN,
+ },
+ },
+ },
+ },
+ testAmount,
+ );
+
+ await usingAcalaPlaygrounds(acalaUrl, async (helper) => {
+ await helper.getSudo().xcm.send(alice, uniqueMultilocation, maliciousXcmProgram);
+ });
+
+ const maxWaitBlocks = 3;
+
+ const xcmpQueueFailEvent = await helper.wait.eventOutcome<XcmV2TraitsError>(
+ maxWaitBlocks,
+ 'xcmpQueue',
+ 'Fail',
+ );
+
+ expect(
+ xcmpQueueFailEvent != null,
+ '\'xcmpQueue.FailEvent\' event is expected',
+ ).to.be.true;
+
+ expect(
+ xcmpQueueFailEvent!.isUntrustedReserveLocation,
+ 'The XCM error should be \'isUntrustedReserveLocation\'',
+ ).to.be.true;
+
+ const accountBalance = await helper.balance.getSubstrate(targetAccount.address);
+ expect(accountBalance).to.be.equal(0n);
+ });
});
-// These tests are relevant only when the foreign asset pallet is disabled
+// These tests are relevant only when
+// the the corresponding foreign assets are not registered
describeXCM('[XCM] Integration test: Unique rejects non-native tokens', () => {
let alice: IKeyringPair;
+ let alith: IKeyringPair;
+
+ const testAmount = 100_000_000_000n;
+ let uniqueParachainJunction;
+ let uniqueAccountJunction;
+
+ let uniqueParachainMultilocation: any;
+ let uniqueAccountMultilocation: any;
+ let uniqueCombinedMultilocation: any;
before(async () => {
await usingPlaygrounds(async (helper, privateKey) => {
alice = await privateKey('//Alice');
- // Set the default version to wrap the first message to other chains.
- await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);
- });
- });
+ uniqueParachainJunction = {Parachain: UNIQUE_CHAIN};
+ uniqueAccountJunction = {
+ AccountId32: {
+ network: 'Any',
+ id: alice.addressRaw,
+ },
+ };
- itSub('Unique rejects ACA tokens from Acala', async ({helper}) => {
- await usingAcalaPlaygrounds(acalaUrl, async (helper) => {
- const destination = {
+ uniqueParachainMultilocation = {
V1: {
parents: 1,
interior: {
- X2: [
- {Parachain: UNIQUE_CHAIN},
- {
- AccountId32: {
- network: 'Any',
- id: alice.addressRaw,
- },
- },
- ],
+ X1: uniqueParachainJunction,
+ },
+ },
+ };
+
+ uniqueAccountMultilocation = {
+ V1: {
+ parents: 0,
+ interior: {
+ X1: uniqueAccountJunction,
},
},
};
- const id = {
- Token: 'ACA',
+ uniqueCombinedMultilocation = {
+ V1: {
+ parents: 1,
+ interior: {
+ X2: [uniqueParachainJunction, uniqueAccountJunction],
+ },
+ },
};
- await helper.xTokens.transfer(alice, id, 100_000_000_000n, destination, 'Unlimited');
+ // Set the default version to wrap the first message to other chains.
+ await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);
});
+ // eslint-disable-next-line require-await
+ await usingMoonbeamPlaygrounds(moonbeamUrl, async (helper) => {
+ alith = helper.account.alithAccount();
+ });
+ });
+
+ const expectFailedToTransact = async (network: string, helper: DevUniqueHelper) => {
const maxWaitBlocks = 3;
- const xcmpQueueFailEvent = await helper.wait.event(maxWaitBlocks, 'xcmpQueue', 'Fail');
+ const xcmpQueueFailEvent = await helper.wait.eventOutcome<XcmV2TraitsError>(
+ maxWaitBlocks,
+ 'xcmpQueue',
+ 'Fail',
+ );
expect(
xcmpQueueFailEvent != null,
- '[Acala] xcmpQueue.FailEvent event is expected',
+ `[reject ${network} tokens] 'xcmpQueue.FailEvent' event is expected`,
).to.be.true;
-
- const event = xcmpQueueFailEvent!.event;
- const outcome = event.data[1] as XcmV2TraitsError;
expect(
- outcome.isFailedToTransactAsset,
- '[Acala] The XCM error should be `FailedToTransactAsset`',
+ xcmpQueueFailEvent!.isFailedToTransactAsset,
+ `[reject ${network} tokens] The XCM error should be 'FailedToTransactAsset'`,
).to.be.true;
+ };
+
+ itSub('Unique rejects ACA tokens from Acala', async ({helper}) => {
+ await usingAcalaPlaygrounds(acalaUrl, async (helper) => {
+ const id = {
+ Token: 'ACA',
+ };
+ const destination = uniqueCombinedMultilocation;
+ await helper.xTokens.transfer(alice, id, testAmount, destination, 'Unlimited');
+ });
+
+ await expectFailedToTransact('ACA', helper);
+ });
+
+ itSub('Unique rejects GLMR tokens from Moonbeam', async ({helper}) => {
+ await usingMoonbeamPlaygrounds(moonbeamUrl, async (helper) => {
+ const id = 'SelfReserve';
+ const destination = uniqueCombinedMultilocation;
+ await helper.xTokens.transfer(alith, id, testAmount, destination, 'Unlimited');
+ });
+
+ await expectFailedToTransact('GLMR', helper);
+ });
+
+ itSub('Unique rejects ASTR tokens from Astar', async ({helper}) => {
+ await usingAstarPlaygrounds(astarUrl, async (helper) => {
+ const destinationParachain = uniqueParachainMultilocation;
+ const beneficiary = uniqueAccountMultilocation;
+ const assets = {
+ V1: [{
+ id: {
+ Concrete: {
+ parents: 0,
+ interior: 'Here',
+ },
+ },
+ fun: {
+ Fungible: testAmount,
+ },
+ }],
+ };
+ const feeAssetItem = 0;
+
+ await helper.executeExtrinsic(alice, 'api.tx.polkadotXcm.reserveWithdrawAssets', [
+ destinationParachain,
+ beneficiary,
+ assets,
+ feeAssetItem,
+ ]);
+ });
+
+ await expectFailedToTransact('ASTR', helper);
});
});
@@ -984,6 +1199,16 @@
console.log('[Moonbeam -> Unique] transaction fees on Unique: %s UNQ', helper.util.bigIntToDecimals(unqFees));
expect(unqFees == 0n).to.be.true;
});
+
+ // eslint-disable-next-line require-await
+ itSub.skip('Moonbeam can send only up to its balance', async ({helper}) => {
+ throw Error('Not yet implemented');
+ });
+
+ // eslint-disable-next-line require-await
+ itSub.skip('Should not accept reserve transfer of UNQ from Moonbeam', async ({helper}) => {
+ throw Error('Not yet implemented');
+ });
});
describeXCM('[XCM] Integration test: Exchanging tokens with Astar', () => {
@@ -1196,59 +1421,140 @@
expect(balanceUNQ).to.eq(balanceAfterUniqueToAstarXCM + unqFromAstarTransfered);
});
- itSub.skip('Should not accept limitedReserveTransfer of UNQ from ASTAR', async ({helper}) => {
+ itSub('Astar can send only up to its balance', async ({helper}) => {
+ // set Astar's sovereign account's balance
+ const astarBalance = 10000n * (10n ** UNQ_DECIMALS);
+ const astarSovereignAccount = helper.address.paraSiblingSovereignAccount(ASTAR_CHAIN);
+ await helper.getSudo().balance.setBalanceSubstrate(alice, astarSovereignAccount, astarBalance);
+
+ const moreThanShidenHas = astarBalance * 2n;
+
+ let targetAccountBalance = 0n;
+ const [targetAccount] = await helper.arrange.createAccounts([targetAccountBalance], alice);
+
+ const uniqueMultilocation = {
+ V1: {
+ parents: 1,
+ interior: {
+ X1: {Parachain: UNIQUE_CHAIN},
+ },
+ },
+ };
+
+ const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(
+ targetAccount.addressRaw,
+ {
+ Concrete: {
+ parents: 0,
+ interior: 'Here',
+ },
+ },
+ moreThanShidenHas,
+ );
+
+ // Try to trick Unique
+ await usingAstarPlaygrounds(astarUrl, async (helper) => {
+ await helper.getSudo().xcm.send(alice, uniqueMultilocation, maliciousXcmProgram);
+ });
+
+ const maxWaitBlocks = 3;
+
+ const xcmpQueueFailEvent = await helper.wait.eventOutcome<XcmV2TraitsError>(
+ maxWaitBlocks,
+ 'xcmpQueue',
+ 'Fail',
+ );
+
+ expect(
+ xcmpQueueFailEvent != null,
+ '\'xcmpQueue.FailEvent\' event is expected',
+ ).to.be.true;
+
+ expect(
+ xcmpQueueFailEvent!.isFailedToTransactAsset,
+ 'The XCM error should be \'FailedToTransactAsset\'',
+ ).to.be.true;
+
+ targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);
+ expect(targetAccountBalance).to.be.equal(0n);
+
+ // But Astar still can send the correct amount
+ const validTransferAmount = astarBalance / 2n;
+ const validXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(
+ targetAccount.addressRaw,
+ {
+ Concrete: {
+ parents: 0,
+ interior: 'Here',
+ },
+ },
+ validTransferAmount,
+ );
+
await usingAstarPlaygrounds(astarUrl, async (helper) => {
- const destination = {
- V1: {
- parents: 1,
- interior: {
- X1: {
- Parachain: UNIQUE_CHAIN,
- },
+ await helper.getSudo().xcm.send(alice, uniqueMultilocation, validXcmProgram);
+ });
+
+ await helper.wait.newBlocks(maxWaitBlocks);
+
+ targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);
+ expect(targetAccountBalance).to.be.equal(validTransferAmount);
+ });
+
+ itSub('Should not accept reserve transfer of UNQ from Astar', async ({helper}) => {
+ const testAmount = 10_000n * (10n ** UNQ_DECIMALS);
+ const [targetAccount] = await helper.arrange.createAccounts([0n], alice);
+
+ const uniqueMultilocation = {
+ V1: {
+ parents: 1,
+ interior: {
+ X1: {
+ Parachain: UNIQUE_CHAIN,
},
},
- };
+ },
+ };
- const beneficiary = {
- V1: {
- parents: 0,
+ const maliciousXcmProgram = helper.arrange.makeXcmProgramReserveAssetDeposited(
+ targetAccount.addressRaw,
+ {
+ Concrete: {
+ parents: 1,
interior: {
X1: {
- AccountId32: {
- network: 'Any',
- id: randomAccount.addressRaw,
- },
+ Parachain: UNIQUE_CHAIN,
},
},
},
- };
+ },
+ testAmount,
+ );
- const assets = {
- V1: [
- {
- id: {
- Concrete: {
- parents: 1,
- interior: {
- X1: {
- Parachain: UNIQUE_CHAIN,
- },
- },
- },
- },
- fun: {
- Fungible: unqFromAstarTransfered,
- },
- },
- ],
- };
+ await usingAstarPlaygrounds(astarUrl, async (helper) => {
+ await helper.getSudo().xcm.send(alice, uniqueMultilocation, maliciousXcmProgram);
+ });
+
+ const maxWaitBlocks = 3;
- // Initial balance is 1 ASTAR
- expect(await helper.balance.getSubstrate(randomAccount.address)).to.eq(astarInitialBalance);
+ const xcmpQueueFailEvent = await helper.wait.eventOutcome<XcmV2TraitsError>(
+ maxWaitBlocks,
+ 'xcmpQueue',
+ 'Fail',
+ );
- const feeAssetItem = 0;
- // TODO: expect rejected:
- await helper.xcm.limitedReserveTransferAssets(randomAccount, destination, beneficiary, assets, feeAssetItem, 'Unlimited');
- });
+ expect(
+ xcmpQueueFailEvent != null,
+ '\'xcmpQueue.FailEvent\' event is expected',
+ ).to.be.true;
+
+ expect(
+ xcmpQueueFailEvent!.isUntrustedReserveLocation,
+ 'The XCM error should be \'isUntrustedReserveLocation\'',
+ ).to.be.true;
+
+ const accountBalance = await helper.balance.getSubstrate(targetAccount.address);
+ expect(accountBalance).to.be.equal(0n);
});
+
});