difftreelog
fix after rebase
in: master
1 file changed
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISchedulerOptions, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, IForeignAssetMetadata, TNetworks, MoonbeamAssetInfo, DemocracyStandardAccountVote, AcalaAssetMetadata} from './types';13import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';1415export class CrossAccountId implements ICrossAccountId {16 Substrate?: TSubstrateAccount;17 Ethereum?: TEthereumAccount;1819 constructor(account: ICrossAccountId) {20 if (account.Substrate) this.Substrate = account.Substrate;21 if (account.Ethereum) this.Ethereum = account.Ethereum;22 }2324 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {25 switch (domain) {26 case 'Substrate': return new CrossAccountId({Substrate: account.address});27 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();28 }29 }3031 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {32 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});33 }3435 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {36 return encodeAddress(decodeAddress(address), ss58Format);37 }3839 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {40 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});41 }42 43 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {44 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);45 return this;46 }4748 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {49 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));50 }5152 toEthereum(): CrossAccountId {53 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});54 return this;55 }5657 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {58 return evmToAddress(address, ss58Format);59 }6061 toSubstrate(ss58Format?: number): CrossAccountId {62 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});63 return this;64 }65 66 toLowerCase(): CrossAccountId {67 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();68 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();69 return this;70 }71}7273const nesting = {74 toChecksumAddress(address: string): string {75 if (typeof address === 'undefined') return '';7677 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);7879 address = address.toLowerCase().replace(/^0x/i,'');80 const addressHash = keccakAsHex(address).replace(/^0x/i,'');81 const checksumAddress = ['0x'];8283 for (let i = 0; i < address.length; i++) {84 // If ith character is 8 to f then make it uppercase85 if (parseInt(addressHash[i], 16) > 7) {86 checksumAddress.push(address[i].toUpperCase());87 } else {88 checksumAddress.push(address[i]);89 }90 }91 return checksumAddress.join('');92 },93 tokenIdToAddress(collectionId: number, tokenId: number) {94 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);95 },96};9798class UniqueUtil {99 static transactionStatus = {100 NOT_READY: 'NotReady',101 FAIL: 'Fail',102 SUCCESS: 'Success',103 };104105 static chainLogType = {106 EXTRINSIC: 'extrinsic',107 RPC: 'rpc',108 };109110 static getTokenAccount(token: IToken): CrossAccountId {111 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});112 }113114 static getTokenAddress(token: IToken): string {115 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);116 }117118 static getDefaultLogger(): ILogger {119 return {120 log(msg: any, level = 'INFO') {121 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));122 },123 level: {124 ERROR: 'ERROR',125 WARNING: 'WARNING',126 INFO: 'INFO',127 },128 };129 }130131 static vec2str(arr: string[] | number[]) {132 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');133 }134135 static str2vec(string: string) {136 if (typeof string !== 'string') return string;137 return Array.from(string).map(x => x.charCodeAt(0));138 }139140 static fromSeed(seed: string, ss58Format = 42) {141 const keyring = new Keyring({type: 'sr25519', ss58Format});142 return keyring.addFromUri(seed);143 }144145 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {146 if (creationResult.status !== this.transactionStatus.SUCCESS) {147 throw Error('Unable to create collection!');148 }149150 let collectionId = null;151 creationResult.result.events.forEach(({event: {data, method, section}}) => {152 if ((section === 'common') && (method === 'CollectionCreated')) {153 collectionId = parseInt(data[0].toString(), 10);154 }155 });156157 if (collectionId === null) {158 throw Error('No CollectionCreated event was found!');159 }160161 return collectionId;162 }163164 static extractTokensFromCreationResult(creationResult: ITransactionResult): {165 success: boolean, 166 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],167 } {168 if (creationResult.status !== this.transactionStatus.SUCCESS) {169 throw Error('Unable to create tokens!');170 }171 let success = false;172 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];173 creationResult.result.events.forEach(({event: {data, method, section}}) => {174 if (method === 'ExtrinsicSuccess') {175 success = true;176 } else if ((section === 'common') && (method === 'ItemCreated')) {177 tokens.push({178 collectionId: parseInt(data[0].toString(), 10),179 tokenId: parseInt(data[1].toString(), 10),180 owner: data[2].toHuman(),181 amount: data[3].toBigInt(),182 });183 }184 });185 return {success, tokens};186 }187188 static extractTokensFromBurnResult(burnResult: ITransactionResult): {189 success: boolean, 190 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],191 } {192 if (burnResult.status !== this.transactionStatus.SUCCESS) {193 throw Error('Unable to burn tokens!');194 }195 let success = false;196 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];197 burnResult.result.events.forEach(({event: {data, method, section}}) => {198 if (method === 'ExtrinsicSuccess') {199 success = true;200 } else if ((section === 'common') && (method === 'ItemDestroyed')) {201 tokens.push({202 collectionId: parseInt(data[0].toString(), 10),203 tokenId: parseInt(data[1].toString(), 10),204 owner: data[2].toHuman(),205 amount: data[3].toBigInt(),206 });207 }208 });209 return {success, tokens};210 }211212 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {213 let eventId = null;214 events.forEach(({event: {data, method, section}}) => {215 if ((section === expectedSection) && (method === expectedMethod)) {216 eventId = parseInt(data[0].toString(), 10);217 }218 });219220 if (eventId === null) {221 throw Error(`No ${expectedMethod} event was found!`);222 }223 return eventId === collectionId;224 }225226 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {227 const normalizeAddress = (address: string | ICrossAccountId) => {228 if(typeof address === 'string') return address;229 const obj = {} as any;230 Object.keys(address).forEach(k => {231 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];232 });233 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);234 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();235 return address;236 };237 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;238 events.forEach(({event: {data, method, section}}) => {239 if ((section === 'common') && (method === 'Transfer')) {240 const hData = (data as any).toJSON();241 transfer = {242 collectionId: hData[0],243 tokenId: hData[1],244 from: normalizeAddress(hData[2]),245 to: normalizeAddress(hData[3]),246 amount: BigInt(hData[4]),247 };248 }249 });250 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;251 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);252 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);253 isSuccess = isSuccess && amount === transfer.amount;254 return isSuccess;255 }256257 static bigIntToDecimals(number: bigint, decimals = 18) {258 const numberStr = number.toString();259 const dotPos = numberStr.length - decimals;260 261 if (dotPos <= 0) {262 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;263 } else {264 const intPart = numberStr.substring(0, dotPos);265 const fractPart = numberStr.substring(dotPos);266 return intPart + '.' + fractPart;267 }268 }269}270271class UniqueEventHelper {272 private static extractIndex(index: any): [number, number] | string {273 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];274 return index.toJSON();275 }276277 private static extractSub(data: any, subTypes: any): {[key: string]: any} {278 let obj: any = {};279 let index = 0;280281 if (data.entries) {282 for(const [key, value] of data.entries()) {283 obj[key] = this.extractData(value, subTypes[index]);284 index++;285 }286 } else obj = data.toJSON();287288 return obj;289 }290 291 private static extractData(data: any, type: any): any {292 if(!type) return data.toHuman();293 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();294 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();295 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);296 return data.toHuman();297 }298299 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {300 const parsedEvents: IEvent[] = [];301302 events.forEach((record) => {303 const {event, phase} = record;304 const types = event.typeDef;305306 const eventData: IEvent = {307 section: event.section.toString(),308 method: event.method.toString(),309 index: this.extractIndex(event.index),310 data: [],311 phase: phase.toJSON(),312 };313314 event.data.forEach((val: any, index: number) => {315 eventData.data.push(this.extractData(val, types[index]));316 });317318 parsedEvents.push(eventData);319 });320321 return parsedEvents;322 }323}324325export class ChainHelperBase {326 helperBase: any;327328 transactionStatus = UniqueUtil.transactionStatus;329 chainLogType = UniqueUtil.chainLogType;330 util: typeof UniqueUtil;331 eventHelper: typeof UniqueEventHelper;332 logger: ILogger;333 api: ApiPromise | null;334 forcedNetwork: TNetworks | null;335 network: TNetworks | null;336 chainLog: IUniqueHelperLog[];337 children: ChainHelperBase[];338 address: AddressGroup;339 chain: ChainGroup;340341 constructor(logger?: ILogger, helperBase?: any) {342 this.helperBase = helperBase;343344 this.util = UniqueUtil;345 this.eventHelper = UniqueEventHelper;346 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();347 this.logger = logger;348 this.api = null;349 this.forcedNetwork = null;350 this.network = null;351 this.chainLog = [];352 this.children = [];353 this.address = new AddressGroup(this);354 this.chain = new ChainGroup(this);355 }356357 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {358 Object.setPrototypeOf(helperCls.prototype, this);359 const newHelper = new helperCls(this.logger, options);360361 newHelper.api = this.api;362 newHelper.network = this.network;363 newHelper.forceNetwork = this.forceNetwork;364365 this.children.push(newHelper);366367 return newHelper;368 }369370 getApi(): ApiPromise {371 if(this.api === null) throw Error('API not initialized');372 return this.api;373 }374375 clearChainLog(): void {376 this.chainLog = [];377 }378379 forceNetwork(value: TNetworks): void {380 this.forcedNetwork = value;381 }382383 async connect(wsEndpoint: string, listeners?: IApiListeners) {384 if (this.api !== null) throw Error('Already connected');385 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);386 this.api = api;387 this.network = network;388 }389390 async disconnect() {391 for (const child of this.children) {392 child.clearApi();393 }394395 if (this.api === null) return;396 await this.api.disconnect();397 this.clearApi();398 }399400 clearApi() {401 this.api = null;402 this.network = null;403 }404405 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {406 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;407 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];408409 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;410411 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;412 return 'opal';413 }414415 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {416 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});417 await api.isReady;418419 const network = await this.detectNetwork(api);420421 await api.disconnect();422423 return network;424 }425426 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{427 api: ApiPromise;428 network: TNetworks;429 }> {430 if(typeof network === 'undefined' || network === null) network = 'opal';431 const supportedRPC = {432 opal: {433 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,434 },435 quartz: {436 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,437 },438 unique: {439 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,440 },441 rococo: {},442 westend: {},443 moonbeam: {},444 moonriver: {},445 acala: {},446 karura: {},447 westmint: {},448 };449 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);450 const rpc = supportedRPC[network];451452 // TODO: investigate how to replace rpc in runtime453 // api._rpcCore.addUserInterfaces(rpc);454455 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});456457 await api.isReadyOrError;458459 if (typeof listeners === 'undefined') listeners = {};460 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {461 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;462 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);463 }464465 return {api, network};466 }467468 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {469 const {events, status} = data;470 if (status.isReady) {471 return this.transactionStatus.NOT_READY;472 }473 if (status.isBroadcast) {474 return this.transactionStatus.NOT_READY;475 }476 if (status.isInBlock || status.isFinalized) {477 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');478 if (errors.length > 0) {479 return this.transactionStatus.FAIL;480 }481 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {482 return this.transactionStatus.SUCCESS;483 }484 }485486 return this.transactionStatus.FAIL;487 }488489 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {490 const sign = (callback: any) => {491 if(options !== null) return transaction.signAndSend(sender, options, callback);492 return transaction.signAndSend(sender, callback);493 };494 // eslint-disable-next-line no-async-promise-executor495 return new Promise(async (resolve, reject) => {496 try {497 const unsub = await sign((result: any) => {498 const status = this.getTransactionStatus(result);499500 if (status === this.transactionStatus.SUCCESS) {501 this.logger.log(`${label} successful`);502 unsub();503 resolve({result, status});504 } else if (status === this.transactionStatus.FAIL) {505 let moduleError = null;506507 if (result.hasOwnProperty('dispatchError')) {508 const dispatchError = result['dispatchError'];509510 if (dispatchError) {511 if (dispatchError.isModule) {512 const modErr = dispatchError.asModule;513 const errorMeta = dispatchError.registry.findMetaError(modErr);514515 moduleError = `${errorMeta.section}.${errorMeta.name}`;516 } else {517 moduleError = dispatchError.toHuman();518 }519 } else {520 this.logger.log(result, this.logger.level.ERROR);521 }522 }523524 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);525 unsub();526 reject({status, moduleError, result});527 }528 });529 } catch (e) {530 this.logger.log(e, this.logger.level.ERROR);531 reject(e);532 }533 });534 }535536 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {537 const api = this.getApi();538 const signingInfo = await api.derive.tx.signingInfo(signer.address);539540 // We need to sign the tx because541 // unsigned transactions does not have an inclusion fee542 tx.sign(signer, {543 blockHash: api.genesisHash,544 genesisHash: api.genesisHash,545 runtimeVersion: api.runtimeVersion,546 nonce: signingInfo.nonce,547 });548549 if (len === null) {550 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;551 } else {552 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;553 }554 }555556 constructApiCall(apiCall: string, params: any[]) {557 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);558 let call = this.getApi() as any;559 for(const part of apiCall.slice(4).split('.')) {560 call = call[part];561 }562 return call(...params);563 }564565 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {566 if(this.api === null) throw Error('API not initialized');567 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);568569 const startTime = (new Date()).getTime();570 let result: ITransactionResult;571 let events: IEvent[] = [];572 try {573 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;574 events = this.eventHelper.extractEvents(result.result.events);575 }576 catch(e) {577 if(!(e as object).hasOwnProperty('status')) throw e;578 result = e as ITransactionResult;579 }580581 const endTime = (new Date()).getTime();582583 const log = {584 executedAt: endTime,585 executionTime: endTime - startTime,586 type: this.chainLogType.EXTRINSIC,587 status: result.status,588 call: extrinsic,589 signer: this.getSignerAddress(sender),590 params,591 } as IUniqueHelperLog;592593 if(result.status !== this.transactionStatus.SUCCESS) {594 if (result.moduleError) log.moduleError = result.moduleError;595 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;596 }597 if(events.length > 0) log.events = events;598599 this.chainLog.push(log);600601 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {602 if (result.moduleError) throw Error(`${result.moduleError}`);603 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));604 }605 return result;606 }607608 async callRpc(rpc: string, params?: any[]) {609 if(typeof params === 'undefined') params = [];610 if(this.api === null) throw Error('API not initialized');611 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);612613 const startTime = (new Date()).getTime();614 let result;615 let error = null;616 const log = {617 type: this.chainLogType.RPC,618 call: rpc,619 params,620 } as IUniqueHelperLog;621622 try {623 result = await this.constructApiCall(rpc, params);624 }625 catch(e) {626 error = e;627 }628629 const endTime = (new Date()).getTime();630631 log.executedAt = endTime;632 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';633 log.executionTime = endTime - startTime;634635 this.chainLog.push(log);636637 if(error !== null) throw error;638639 return result;640 }641642 getSignerAddress(signer: IKeyringPair | string): string {643 if(typeof signer === 'string') return signer;644 return signer.address;645 }646647 fetchAllPalletNames(): string[] {648 if(this.api === null) throw Error('API not initialized');649 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());650 }651652 fetchMissingPalletNames(requiredPallets: string[]): string[] {653 const palletNames = this.fetchAllPalletNames();654 return requiredPallets.filter(p => !palletNames.includes(p));655 }656}657658659class HelperGroup<T extends ChainHelperBase> {660 helper: T;661662 constructor(uniqueHelper: T) {663 this.helper = uniqueHelper;664 }665}666667668class CollectionGroup extends HelperGroup<UniqueHelper> {669 /**670 * Get number of blocks when sponsored transaction is available.671 *672 * @param collectionId ID of collection673 * @param tokenId ID of token674 * @param addressObj address for which the sponsorship is checked675 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});676 * @returns number of blocks or null if sponsorship hasn't been set677 */678 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {679 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();680 }681682 /**683 * Get the number of created collections.684 *685 * @returns number of created collections686 */687 async getTotalCount(): Promise<number> {688 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();689 }690691 /**692 * Get information about the collection with additional data,693 * including the number of tokens it contains, its administrators,694 * the normalized address of the collection's owner, and decoded name and description.695 *696 * @param collectionId ID of collection697 * @example await getData(2)698 * @returns collection information object699 */700 async getData(collectionId: number): Promise<{701 id: number;702 name: string;703 description: string;704 tokensCount: number;705 admins: CrossAccountId[];706 normalizedOwner: TSubstrateAccount;707 raw: any708 } | null> {709 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);710 const humanCollection = collection.toHuman(), collectionData = {711 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],712 raw: humanCollection,713 } as any, jsonCollection = collection.toJSON();714 if (humanCollection === null) return null;715 collectionData.raw.limits = jsonCollection.limits;716 collectionData.raw.permissions = jsonCollection.permissions;717 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);718 for (const key of ['name', 'description']) {719 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);720 }721722 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))723 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)724 : 0;725 collectionData.admins = await this.getAdmins(collectionId);726727 return collectionData;728 }729730 /**731 * Get the addresses of the collection's administrators, optionally normalized.732 *733 * @param collectionId ID of collection734 * @param normalize whether to normalize the addresses to the default ss58 format735 * @example await getAdmins(1)736 * @returns array of administrators737 */738 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {739 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();740741 return normalize742 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())743 : admins;744 }745746 /**747 * Get the addresses added to the collection allow-list, optionally normalized.748 * @param collectionId ID of collection749 * @param normalize whether to normalize the addresses to the default ss58 format750 * @example await getAllowList(1)751 * @returns array of allow-listed addresses752 */753 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {754 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();755 return normalize756 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())757 : allowListed;758 }759760 /**761 * Get the effective limits of the collection instead of null for default values762 *763 * @param collectionId ID of collection764 * @example await getEffectiveLimits(2)765 * @returns object of collection limits766 */767 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {768 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();769 }770771 /**772 * Burns the collection if the signer has sufficient permissions and collection is empty.773 *774 * @param signer keyring of signer775 * @param collectionId ID of collection776 * @example await helper.collection.burn(aliceKeyring, 3);777 * @returns ```true``` if extrinsic success, otherwise ```false```778 */779 async burn(signer: TSigner, collectionId: number): Promise<boolean> {780 const result = await this.helper.executeExtrinsic(781 signer,782 'api.tx.unique.destroyCollection', [collectionId],783 true,784 );785786 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');787 }788789 /**790 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.791 *792 * @param signer keyring of signer793 * @param collectionId ID of collection794 * @param sponsorAddress Sponsor substrate address795 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")796 * @returns ```true``` if extrinsic success, otherwise ```false```797 */798 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {799 const result = await this.helper.executeExtrinsic(800 signer,801 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],802 true,803 );804805 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');806 }807808 /**809 * Confirms consent to sponsor the collection on behalf of the signer.810 *811 * @param signer keyring of signer812 * @param collectionId ID of collection813 * @example confirmSponsorship(aliceKeyring, 10)814 * @returns ```true``` if extrinsic success, otherwise ```false```815 */816 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {817 const result = await this.helper.executeExtrinsic(818 signer,819 'api.tx.unique.confirmSponsorship', [collectionId],820 true,821 );822823 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');824 }825826 /**827 * Removes the sponsor of a collection, regardless if it consented or not.828 *829 * @param signer keyring of signer830 * @param collectionId ID of collection831 * @example removeSponsor(aliceKeyring, 10)832 * @returns ```true``` if extrinsic success, otherwise ```false```833 */834 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {835 const result = await this.helper.executeExtrinsic(836 signer,837 'api.tx.unique.removeCollectionSponsor', [collectionId],838 true,839 );840841 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');842 }843844 /**845 * Sets the limits of the collection. At least one limit must be specified for a correct call.846 *847 * @param signer keyring of signer848 * @param collectionId ID of collection849 * @param limits collection limits object850 * @example851 * await setLimits(852 * aliceKeyring,853 * 10,854 * {855 * sponsorTransferTimeout: 0,856 * ownerCanDestroy: false857 * }858 * )859 * @returns ```true``` if extrinsic success, otherwise ```false```860 */861 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {862 const result = await this.helper.executeExtrinsic(863 signer,864 'api.tx.unique.setCollectionLimits', [collectionId, limits],865 true,866 );867868 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');869 }870871 /**872 * Changes the owner of the collection to the new Substrate address.873 *874 * @param signer keyring of signer875 * @param collectionId ID of collection876 * @param ownerAddress substrate address of new owner877 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")878 * @returns ```true``` if extrinsic success, otherwise ```false```879 */880 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {881 const result = await this.helper.executeExtrinsic(882 signer,883 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],884 true,885 );886887 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');888 }889890 /**891 * Adds a collection administrator.892 *893 * @param signer keyring of signer894 * @param collectionId ID of collection895 * @param adminAddressObj Administrator address (substrate or ethereum)896 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})897 * @returns ```true``` if extrinsic success, otherwise ```false```898 */899 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {900 const result = await this.helper.executeExtrinsic(901 signer,902 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],903 true,904 );905906 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');907 }908909 /**910 * Removes a collection administrator.911 *912 * @param signer keyring of signer913 * @param collectionId ID of collection914 * @param adminAddressObj Administrator address (substrate or ethereum)915 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})916 * @returns ```true``` if extrinsic success, otherwise ```false```917 */918 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {919 const result = await this.helper.executeExtrinsic(920 signer,921 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],922 true,923 );924925 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');926 }927928 /**929 * Check if user is in allow list.930 * 931 * @param collectionId ID of collection932 * @param user Account to check933 * @example await getAdmins(1)934 * @returns is user in allow list935 */936 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {937 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();938 }939940 /**941 * Adds an address to allow list942 * @param signer keyring of signer943 * @param collectionId ID of collection944 * @param addressObj address to add to the allow list945 * @returns ```true``` if extrinsic success, otherwise ```false```946 */947 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {948 const result = await this.helper.executeExtrinsic(949 signer,950 'api.tx.unique.addToAllowList', [collectionId, addressObj],951 true,952 );953954 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');955 }956957 /**958 * Removes an address from allow list959 *960 * @param signer keyring of signer961 * @param collectionId ID of collection962 * @param addressObj address to remove from the allow list963 * @returns ```true``` if extrinsic success, otherwise ```false```964 */965 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {966 const result = await this.helper.executeExtrinsic(967 signer,968 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],969 true,970 );971972 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');973 }974975 /**976 * Sets onchain permissions for selected collection.977 *978 * @param signer keyring of signer979 * @param collectionId ID of collection980 * @param permissions collection permissions object981 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});982 * @returns ```true``` if extrinsic success, otherwise ```false```983 */984 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {985 const result = await this.helper.executeExtrinsic(986 signer,987 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],988 true,989 );990991 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');992 }993994 /**995 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.996 *997 * @param signer keyring of signer998 * @param collectionId ID of collection999 * @param permissions nesting permissions object1000 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1001 * @returns ```true``` if extrinsic success, otherwise ```false```1002 */1003 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1004 return await this.setPermissions(signer, collectionId, {nesting: permissions});1005 }10061007 /**1008 * Disables nesting for selected collection.1009 *1010 * @param signer keyring of signer1011 * @param collectionId ID of collection1012 * @example disableNesting(aliceKeyring, 10);1013 * @returns ```true``` if extrinsic success, otherwise ```false```1014 */1015 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1016 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1017 }10181019 /**1020 * Sets onchain properties to the collection.1021 *1022 * @param signer keyring of signer1023 * @param collectionId ID of collection1024 * @param properties array of property objects1025 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1026 * @returns ```true``` if extrinsic success, otherwise ```false```1027 */1028 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1029 const result = await this.helper.executeExtrinsic(1030 signer,1031 'api.tx.unique.setCollectionProperties', [collectionId, properties],1032 true,1033 );10341035 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1036 }10371038 /**1039 * Get collection properties.1040 * 1041 * @param collectionId ID of collection1042 * @param propertyKeys optionally filter the returned properties to only these keys1043 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1044 * @returns array of key-value pairs1045 */1046 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1047 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1048 }10491050 async getCollectionOptions(collectionId: number) {1051 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1052 }10531054 /**1055 * Deletes onchain properties from the collection.1056 *1057 * @param signer keyring of signer1058 * @param collectionId ID of collection1059 * @param propertyKeys array of property keys to delete1060 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1061 * @returns ```true``` if extrinsic success, otherwise ```false```1062 */1063 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1064 const result = await this.helper.executeExtrinsic(1065 signer,1066 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1067 true,1068 );10691070 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1071 }10721073 /**1074 * Changes the owner of the token.1075 *1076 * @param signer keyring of signer1077 * @param collectionId ID of collection1078 * @param tokenId ID of token1079 * @param addressObj address of a new owner1080 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1081 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1082 * @returns true if the token success, otherwise false1083 */1084 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1085 const result = await this.helper.executeExtrinsic(1086 signer,1087 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1088 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1089 );10901091 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1092 }10931094 /**1095 *1096 * Change ownership of a token(s) on behalf of the owner.1097 *1098 * @param signer keyring of signer1099 * @param collectionId ID of collection1100 * @param tokenId ID of token1101 * @param fromAddressObj address on behalf of which the token will be sent1102 * @param toAddressObj new token owner1103 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1104 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1105 * @returns true if the token success, otherwise false1106 */1107 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1108 const result = await this.helper.executeExtrinsic(1109 signer,1110 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1111 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1112 );1113 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1114 }11151116 /**1117 *1118 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1119 *1120 * @param signer keyring of signer1121 * @param collectionId ID of collection1122 * @param tokenId ID of token1123 * @param amount amount of tokens to be burned. For NFT must be set to 1n1124 * @example burnToken(aliceKeyring, 10, 5);1125 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1126 */1127 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1128 const burnResult = await this.helper.executeExtrinsic(1129 signer,1130 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1131 true, // `Unable to burn token for ${label}`,1132 );1133 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1134 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1135 return burnedTokens.success;1136 }11371138 /**1139 * Destroys a concrete instance of NFT on behalf of the owner1140 *1141 * @param signer keyring of signer1142 * @param collectionId ID of collection1143 * @param tokenId ID of token1144 * @param fromAddressObj address on behalf of which the token will be burnt1145 * @param amount amount of tokens to be burned. For NFT must be set to 1n1146 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1147 * @returns ```true``` if extrinsic success, otherwise ```false```1148 */1149 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1150 const burnResult = await this.helper.executeExtrinsic(1151 signer,1152 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1153 true, // `Unable to burn token from for ${label}`,1154 );1155 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1156 return burnedTokens.success && burnedTokens.tokens.length > 0;1157 }11581159 /**1160 * Set, change, or remove approved address to transfer the ownership of the NFT.1161 *1162 * @param signer keyring of signer1163 * @param collectionId ID of collection1164 * @param tokenId ID of token1165 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1166 * @param amount amount of token to be approved. For NFT must be set to 1n1167 * @returns ```true``` if extrinsic success, otherwise ```false```1168 */1169 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1170 const approveResult = await this.helper.executeExtrinsic(1171 signer,1172 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1173 true, // `Unable to approve token for ${label}`,1174 );11751176 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1177 }11781179 /**1180 * Get the amount of token pieces approved to transfer or burn. Normally 0.1181 *1182 * @param collectionId ID of collection1183 * @param tokenId ID of token1184 * @param toAccountObj address which is approved to use token pieces1185 * @param fromAccountObj address which may have allowed the use of its owned tokens1186 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1187 * @returns number of approved to transfer pieces1188 */1189 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1190 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1191 }11921193 /**1194 * Get the last created token ID in a collection1195 *1196 * @param collectionId ID of collection1197 * @example getLastTokenId(10);1198 * @returns id of the last created token1199 */1200 async getLastTokenId(collectionId: number): Promise<number> {1201 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1202 }12031204 /**1205 * Check if token exists1206 *1207 * @param collectionId ID of collection1208 * @param tokenId ID of token1209 * @example doesTokenExist(10, 20);1210 * @returns true if the token exists, otherwise false1211 */1212 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1213 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1214 }1215}12161217class NFTnRFT extends CollectionGroup {1218 /**1219 * Get tokens owned by account1220 *1221 * @param collectionId ID of collection1222 * @param addressObj tokens owner1223 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1224 * @returns array of token ids owned by account1225 */1226 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1227 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1228 }12291230 /**1231 * Get token data1232 *1233 * @param collectionId ID of collection1234 * @param tokenId ID of token1235 * @param propertyKeys optionally filter the token properties to only these keys1236 * @param blockHashAt optionally query the data at some block with this hash1237 * @example getToken(10, 5);1238 * @returns human readable token data1239 */1240 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1241 properties: IProperty[];1242 owner: CrossAccountId;1243 normalizedOwner: CrossAccountId;1244 }| null> {1245 let tokenData;1246 if(typeof blockHashAt === 'undefined') {1247 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1248 }1249 else {1250 if(propertyKeys.length == 0) {1251 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1252 if(!collection) return null;1253 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1254 }1255 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1256 }1257 tokenData = tokenData.toHuman();1258 if (tokenData === null || tokenData.owner === null) return null;1259 const owner = {} as any;1260 for (const key of Object.keys(tokenData.owner)) {1261 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1262 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1263 : tokenData.owner[key];1264 }1265 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1266 return tokenData;1267 }12681269 /**1270 * Set permissions to change token properties1271 *1272 * @param signer keyring of signer1273 * @param collectionId ID of collection1274 * @param permissions permissions to change a property by the collection admin or token owner1275 * @example setTokenPropertyPermissions(1276 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1277 * )1278 * @returns true if extrinsic success otherwise false1279 */1280 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1281 const result = await this.helper.executeExtrinsic(1282 signer,1283 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1284 true,1285 );12861287 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1288 }12891290 /**1291 * Get token property permissions.1292 * 1293 * @param collectionId ID of collection1294 * @param propertyKeys optionally filter the returned property permissions to only these keys1295 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1296 * @returns array of key-permission pairs1297 */1298 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1299 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1300 }13011302 /**1303 * Set token properties1304 *1305 * @param signer keyring of signer1306 * @param collectionId ID of collection1307 * @param tokenId ID of token1308 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1309 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1310 * @returns ```true``` if extrinsic success, otherwise ```false```1311 */1312 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1313 const result = await this.helper.executeExtrinsic(1314 signer,1315 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1316 true,1317 );13181319 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1320 }13211322 /**1323 * Get properties, metadata assigned to a token.1324 * 1325 * @param collectionId ID of collection1326 * @param tokenId ID of token1327 * @param propertyKeys optionally filter the returned properties to only these keys1328 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1329 * @returns array of key-value pairs1330 */1331 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1332 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1333 }13341335 /**1336 * Delete the provided properties of a token1337 * @param signer keyring of signer1338 * @param collectionId ID of collection1339 * @param tokenId ID of token1340 * @param propertyKeys property keys to be deleted1341 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1342 * @returns ```true``` if extrinsic success, otherwise ```false```1343 */1344 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1345 const result = await this.helper.executeExtrinsic(1346 signer,1347 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1348 true,1349 );13501351 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1352 }13531354 /**1355 * Mint new collection1356 *1357 * @param signer keyring of signer1358 * @param collectionOptions basic collection options and properties1359 * @param mode NFT or RFT type of a collection1360 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1361 * @returns object of the created collection1362 */1363 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1364 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1365 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1366 for (const key of ['name', 'description', 'tokenPrefix']) {1367 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);1368 }1369 const creationResult = await this.helper.executeExtrinsic(1370 signer,1371 'api.tx.unique.createCollectionEx', [collectionOptions],1372 true, // errorLabel,1373 );1374 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1375 }13761377 getCollectionObject(_collectionId: number): any {1378 return null;1379 }13801381 getTokenObject(_collectionId: number, _tokenId: number): any {1382 return null;1383 }1384}138513861387class NFTGroup extends NFTnRFT {1388 /**1389 * Get collection object1390 * @param collectionId ID of collection1391 * @example getCollectionObject(2);1392 * @returns instance of UniqueNFTCollection1393 */1394 getCollectionObject(collectionId: number): UniqueNFTCollection {1395 return new UniqueNFTCollection(collectionId, this.helper);1396 }13971398 /**1399 * Get token object1400 * @param collectionId ID of collection1401 * @param tokenId ID of token1402 * @example getTokenObject(10, 5);1403 * @returns instance of UniqueNFTToken1404 */1405 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1406 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1407 }14081409 /**1410 * Get token's owner1411 * @param collectionId ID of collection1412 * @param tokenId ID of token1413 * @param blockHashAt optionally query the data at the block with this hash1414 * @example getTokenOwner(10, 5);1415 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1416 */1417 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1418 let owner;1419 if (typeof blockHashAt === 'undefined') {1420 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1421 } else {1422 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1423 }1424 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1425 }14261427 /**1428 * Is token approved to transfer1429 * @param collectionId ID of collection1430 * @param tokenId ID of token1431 * @param toAccountObj address to be approved1432 * @returns ```true``` if extrinsic success, otherwise ```false```1433 */1434 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1435 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1436 }14371438 /**1439 * Changes the owner of the token.1440 *1441 * @param signer keyring of signer1442 * @param collectionId ID of collection1443 * @param tokenId ID of token1444 * @param addressObj address of a new owner1445 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1446 * @returns ```true``` if extrinsic success, otherwise ```false```1447 */1448 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1449 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1450 }14511452 /**1453 *1454 * Change ownership of a NFT on behalf of the owner.1455 *1456 * @param signer keyring of signer1457 * @param collectionId ID of collection1458 * @param tokenId ID of token1459 * @param fromAddressObj address on behalf of which the token will be sent1460 * @param toAddressObj new token owner1461 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1462 * @returns ```true``` if extrinsic success, otherwise ```false```1463 */1464 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1465 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1466 }14671468 /**1469 * Recursively find the address that owns the token1470 * @param collectionId ID of collection1471 * @param tokenId ID of token1472 * @param blockHashAt1473 * @example getTokenTopmostOwner(10, 5);1474 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1475 */1476 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1477 let owner;1478 if (typeof blockHashAt === 'undefined') {1479 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1480 } else {1481 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1482 }14831484 if (owner === null) return null;14851486 return owner.toHuman();1487 }14881489 /**1490 * Get tokens nested in the provided token1491 * @param collectionId ID of collection1492 * @param tokenId ID of token1493 * @param blockHashAt optionally query the data at the block with this hash1494 * @example getTokenChildren(10, 5);1495 * @returns tokens whose depth of nesting is <= 51496 */1497 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1498 let children;1499 if(typeof blockHashAt === 'undefined') {1500 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1501 } else {1502 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1503 }15041505 return children.toJSON().map((x: any) => {1506 return {collectionId: x.collection, tokenId: x.token};1507 });1508 }15091510 /**1511 * Nest one token into another1512 * @param signer keyring of signer1513 * @param tokenObj token to be nested1514 * @param rootTokenObj token to be parent1515 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1516 * @returns ```true``` if extrinsic success, otherwise ```false```1517 */1518 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1519 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1520 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1521 if(!result) {1522 throw Error('Unable to nest token!');1523 }1524 return result;1525 }15261527 /**1528 * Remove token from nested state1529 * @param signer keyring of signer1530 * @param tokenObj token to unnest1531 * @param rootTokenObj parent of a token1532 * @param toAddressObj address of a new token owner1533 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1534 * @returns ```true``` if extrinsic success, otherwise ```false```1535 */1536 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1537 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1538 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1539 if(!result) {1540 throw Error('Unable to unnest token!');1541 }1542 return result;1543 }15441545 /**1546 * Mint new collection1547 * @param signer keyring of signer1548 * @param collectionOptions Collection options1549 * @example1550 * mintCollection(aliceKeyring, {1551 * name: 'New',1552 * description: 'New collection',1553 * tokenPrefix: 'NEW',1554 * })1555 * @returns object of the created collection1556 */1557 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1558 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1559 }15601561 /**1562 * Mint new token1563 * @param signer keyring of signer1564 * @param data token data1565 * @returns created token object1566 */1567 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1568 const creationResult = await this.helper.executeExtrinsic(1569 signer,1570 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1571 nft: {1572 properties: data.properties,1573 },1574 }],1575 true,1576 );1577 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1578 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1579 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1580 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1581 }15821583 /**1584 * Mint multiple NFT tokens1585 * @param signer keyring of signer1586 * @param collectionId ID of collection1587 * @param tokens array of tokens with owner and properties1588 * @example1589 * mintMultipleTokens(aliceKeyring, 10, [{1590 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1591 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1592 * },{1593 * owner: {Ethereum: "0x9F0583DbB855d..."},1594 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1595 * }]);1596 * @returns ```true``` if extrinsic success, otherwise ```false```1597 */1598 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1599 const creationResult = await this.helper.executeExtrinsic(1600 signer,1601 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1602 true,1603 );1604 const collection = this.getCollectionObject(collectionId);1605 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1606 }16071608 /**1609 * Mint multiple NFT tokens with one owner1610 * @param signer keyring of signer1611 * @param collectionId ID of collection1612 * @param owner tokens owner1613 * @param tokens array of tokens with owner and properties1614 * @example1615 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1616 * properties: [{1617 * key: "gender",1618 * value: "female",1619 * },{1620 * key: "age",1621 * value: "33",1622 * }],1623 * }]);1624 * @returns array of newly created tokens1625 */1626 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1627 const rawTokens = [];1628 for (const token of tokens) {1629 const raw = {NFT: {properties: token.properties}};1630 rawTokens.push(raw);1631 }1632 const creationResult = await this.helper.executeExtrinsic(1633 signer,1634 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1635 true,1636 );1637 const collection = this.getCollectionObject(collectionId);1638 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1639 }16401641 /**1642 * Set, change, or remove approved address to transfer the ownership of the NFT.1643 *1644 * @param signer keyring of signer1645 * @param collectionId ID of collection1646 * @param tokenId ID of token1647 * @param toAddressObj address to approve1648 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1649 * @returns ```true``` if extrinsic success, otherwise ```false```1650 */1651 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1652 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1653 }1654}165516561657class RFTGroup extends NFTnRFT {1658 /**1659 * Get collection object1660 * @param collectionId ID of collection1661 * @example getCollectionObject(2);1662 * @returns instance of UniqueRFTCollection1663 */1664 getCollectionObject(collectionId: number): UniqueRFTCollection {1665 return new UniqueRFTCollection(collectionId, this.helper);1666 }16671668 /**1669 * Get token object1670 * @param collectionId ID of collection1671 * @param tokenId ID of token1672 * @example getTokenObject(10, 5);1673 * @returns instance of UniqueNFTToken1674 */1675 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1676 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1677 }16781679 /**1680 * Get top 10 token owners with the largest number of pieces1681 * @param collectionId ID of collection1682 * @param tokenId ID of token1683 * @example getTokenTop10Owners(10, 5);1684 * @returns array of top 10 owners1685 */1686 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1687 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1688 }16891690 /**1691 * Get number of pieces owned by address1692 * @param collectionId ID of collection1693 * @param tokenId ID of token1694 * @param addressObj address token owner1695 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1696 * @returns number of pieces ownerd by address1697 */1698 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1699 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1700 }17011702 /**1703 * Transfer pieces of token to another address1704 * @param signer keyring of signer1705 * @param collectionId ID of collection1706 * @param tokenId ID of token1707 * @param addressObj address of a new owner1708 * @param amount number of pieces to be transfered1709 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1710 * @returns ```true``` if extrinsic success, otherwise ```false```1711 */1712 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1713 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1714 }17151716 /**1717 * Change ownership of some pieces of RFT on behalf of the owner.1718 * @param signer keyring of signer1719 * @param collectionId ID of collection1720 * @param tokenId ID of token1721 * @param fromAddressObj address on behalf of which the token will be sent1722 * @param toAddressObj new token owner1723 * @param amount number of pieces to be transfered1724 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1725 * @returns ```true``` if extrinsic success, otherwise ```false```1726 */1727 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1728 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1729 }17301731 /**1732 * Mint new collection1733 * @param signer keyring of signer1734 * @param collectionOptions Collection options1735 * @example1736 * mintCollection(aliceKeyring, {1737 * name: 'New',1738 * description: 'New collection',1739 * tokenPrefix: 'NEW',1740 * })1741 * @returns object of the created collection1742 */1743 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1744 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1745 }17461747 /**1748 * Mint new token1749 * @param signer keyring of signer1750 * @param data token data1751 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1752 * @returns created token object1753 */1754 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1755 const creationResult = await this.helper.executeExtrinsic(1756 signer,1757 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1758 refungible: {1759 pieces: data.pieces,1760 properties: data.properties,1761 },1762 }],1763 true,1764 );1765 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1766 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1767 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1768 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1769 }17701771 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1772 throw Error('Not implemented');1773 const creationResult = await this.helper.executeExtrinsic(1774 signer,1775 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1776 true, // `Unable to mint RFT tokens for ${label}`,1777 );1778 const collection = this.getCollectionObject(collectionId);1779 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1780 }17811782 /**1783 * Mint multiple RFT tokens with one owner1784 * @param signer keyring of signer1785 * @param collectionId ID of collection1786 * @param owner tokens owner1787 * @param tokens array of tokens with properties and pieces1788 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1789 * @returns array of newly created RFT tokens1790 */1791 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1792 const rawTokens = [];1793 for (const token of tokens) {1794 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1795 rawTokens.push(raw);1796 }1797 const creationResult = await this.helper.executeExtrinsic(1798 signer,1799 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1800 true,1801 );1802 const collection = this.getCollectionObject(collectionId);1803 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1804 }18051806 /**1807 * Destroys a concrete instance of RFT.1808 * @param signer keyring of signer1809 * @param collectionId ID of collection1810 * @param tokenId ID of token1811 * @param amount number of pieces to be burnt1812 * @example burnToken(aliceKeyring, 10, 5);1813 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1814 */1815 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1816 return await super.burnToken(signer, collectionId, tokenId, amount);1817 }18181819 /**1820 * Destroys a concrete instance of RFT on behalf of the owner.1821 * @param signer keyring of signer1822 * @param collectionId ID of collection1823 * @param tokenId ID of token1824 * @param fromAddressObj address on behalf of which the token will be burnt1825 * @param amount number of pieces to be burnt1826 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1827 * @returns ```true``` if extrinsic success, otherwise ```false```1828 */1829 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1830 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1831 }18321833 /**1834 * Set, change, or remove approved address to transfer the ownership of the RFT.1835 *1836 * @param signer keyring of signer1837 * @param collectionId ID of collection1838 * @param tokenId ID of token1839 * @param toAddressObj address to approve1840 * @param amount number of pieces to be approved1841 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1842 * @returns true if the token success, otherwise false1843 */1844 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1845 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1846 }18471848 /**1849 * Get total number of pieces1850 * @param collectionId ID of collection1851 * @param tokenId ID of token1852 * @example getTokenTotalPieces(10, 5);1853 * @returns number of pieces1854 */1855 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1856 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1857 }18581859 /**1860 * Change number of token pieces. Signer must be the owner of all token pieces.1861 * @param signer keyring of signer1862 * @param collectionId ID of collection1863 * @param tokenId ID of token1864 * @param amount new number of pieces1865 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1866 * @returns true if the repartion was success, otherwise false1867 */1868 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1869 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1870 const repartitionResult = await this.helper.executeExtrinsic(1871 signer,1872 'api.tx.unique.repartition', [collectionId, tokenId, amount],1873 true,1874 );1875 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1876 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1877 }1878}187918801881class FTGroup extends CollectionGroup {1882 /**1883 * Get collection object1884 * @param collectionId ID of collection1885 * @example getCollectionObject(2);1886 * @returns instance of UniqueFTCollection1887 */1888 getCollectionObject(collectionId: number): UniqueFTCollection {1889 return new UniqueFTCollection(collectionId, this.helper);1890 }18911892 /**1893 * Mint new fungible collection1894 * @param signer keyring of signer1895 * @param collectionOptions Collection options1896 * @param decimalPoints number of token decimals1897 * @example1898 * mintCollection(aliceKeyring, {1899 * name: 'New',1900 * description: 'New collection',1901 * tokenPrefix: 'NEW',1902 * }, 18)1903 * @returns newly created fungible collection1904 */1905 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1906 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1907 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1908 collectionOptions.mode = {fungible: decimalPoints};1909 for (const key of ['name', 'description', 'tokenPrefix']) {1910 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);1911 }1912 const creationResult = await this.helper.executeExtrinsic(1913 signer,1914 'api.tx.unique.createCollectionEx', [collectionOptions],1915 true,1916 );1917 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1918 }19191920 /**1921 * Mint tokens1922 * @param signer keyring of signer1923 * @param collectionId ID of collection1924 * @param owner address owner of new tokens1925 * @param amount amount of tokens to be meanted1926 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1927 * @returns ```true``` if extrinsic success, otherwise ```false```1928 */1929 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1930 const creationResult = await this.helper.executeExtrinsic(1931 signer,1932 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1933 fungible: {1934 value: amount,1935 },1936 }],1937 true, // `Unable to mint fungible tokens for ${label}`,1938 );1939 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1940 }19411942 /**1943 * Mint multiple Fungible tokens with one owner1944 * @param signer keyring of signer1945 * @param collectionId ID of collection1946 * @param owner tokens owner1947 * @param tokens array of tokens with properties and pieces1948 * @returns ```true``` if extrinsic success, otherwise ```false```1949 */1950 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1951 const rawTokens = [];1952 for (const token of tokens) {1953 const raw = {Fungible: {Value: token.value}};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 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1962 }19631964 /**1965 * Get the top 10 owners with the largest balance for the Fungible collection1966 * @param collectionId ID of collection1967 * @example getTop10Owners(10);1968 * @returns array of ```ICrossAccountId```1969 */1970 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1971 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1972 }19731974 /**1975 * Get account balance1976 * @param collectionId ID of collection1977 * @param addressObj address of owner1978 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1979 * @returns amount of fungible tokens owned by address1980 */1981 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1982 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1983 }19841985 /**1986 * Transfer tokens to address1987 * @param signer keyring of signer1988 * @param collectionId ID of collection1989 * @param toAddressObj address recipient1990 * @param amount amount of tokens to be sent1991 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1992 * @returns ```true``` if extrinsic success, otherwise ```false```1993 */1994 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1995 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1996 }19971998 /**1999 * Transfer some tokens on behalf of the owner.2000 * @param signer keyring of signer2001 * @param collectionId ID of collection2002 * @param fromAddressObj address on behalf of which tokens will be sent2003 * @param toAddressObj address where token to be sent2004 * @param amount number of tokens to be sent2005 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2006 * @returns ```true``` if extrinsic success, otherwise ```false```2007 */2008 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2009 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2010 }20112012 /**2013 * Destroy some amount of tokens2014 * @param signer keyring of signer2015 * @param collectionId ID of collection2016 * @param amount amount of tokens to be destroyed2017 * @example burnTokens(aliceKeyring, 10, 1000n);2018 * @returns ```true``` if extrinsic success, otherwise ```false```2019 */2020 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2021 return await super.burnToken(signer, collectionId, 0, amount);2022 }20232024 /**2025 * Burn some tokens on behalf of the owner.2026 * @param signer keyring of signer2027 * @param collectionId ID of collection2028 * @param fromAddressObj address on behalf of which tokens will be burnt2029 * @param amount amount of tokens to be burnt2030 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2031 * @returns ```true``` if extrinsic success, otherwise ```false```2032 */2033 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2034 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2035 }20362037 /**2038 * Get total collection supply2039 * @param collectionId2040 * @returns2041 */2042 async getTotalPieces(collectionId: number): Promise<bigint> {2043 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2044 }20452046 /**2047 * Set, change, or remove approved address to transfer tokens.2048 *2049 * @param signer keyring of signer2050 * @param collectionId ID of collection2051 * @param toAddressObj address to be approved2052 * @param amount amount of tokens to be approved2053 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2054 * @returns ```true``` if extrinsic success, otherwise ```false```2055 */2056 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2057 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2058 }20592060 /**2061 * Get amount of fungible tokens approved to transfer2062 * @param collectionId ID of collection2063 * @param fromAddressObj owner of tokens2064 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2065 * @returns number of tokens approved for the transfer2066 */2067 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2068 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2069 }2070}207120722073class ChainGroup extends HelperGroup<ChainHelperBase> {2074 /**2075 * Get system properties of a chain2076 * @example getChainProperties();2077 * @returns ss58Format, token decimals, and token symbol2078 */2079 getChainProperties(): IChainProperties {2080 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2081 return {2082 ss58Format: properties.ss58Format.toJSON(),2083 tokenDecimals: properties.tokenDecimals.toJSON(),2084 tokenSymbol: properties.tokenSymbol.toJSON(),2085 };2086 }20872088 /**2089 * Get chain header2090 * @example getLatestBlockNumber();2091 * @returns the number of the last block2092 */2093 async getLatestBlockNumber(): Promise<number> {2094 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2095 }20962097 /**2098 * Get block hash by block number2099 * @param blockNumber number of block2100 * @example getBlockHashByNumber(12345);2101 * @returns hash of a block2102 */2103 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2104 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2105 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2106 return blockHash;2107 }21082109 // TODO add docs2110 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2111 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2112 if (!blockHash) return null;2113 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2114 }21152116 /**2117 * Get account nonce2118 * @param address substrate address2119 * @example getNonce("5GrwvaEF5zXb26Fz...");2120 * @returns number, account's nonce2121 */2122 async getNonce(address: TSubstrateAccount): Promise<number> {2123 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2124 }2125}21262127class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2128 /**2129 * Get substrate address balance2130 * @param address substrate address2131 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2132 * @returns amount of tokens on address2133 */2134 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2135 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2136 }21372138 /**2139 * Transfer tokens to substrate address2140 * @param signer keyring of signer2141 * @param address substrate address of a recipient2142 * @param amount amount of tokens to be transfered2143 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2144 * @returns ```true``` if extrinsic success, otherwise ```false```2145 */2146 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2147 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}`*/);21482149 let transfer = {from: null, to: null, amount: 0n} as any;2150 result.result.events.forEach(({event: {data, method, section}}) => {2151 if ((section === 'balances') && (method === 'Transfer')) {2152 transfer = {2153 from: this.helper.address.normalizeSubstrate(data[0]),2154 to: this.helper.address.normalizeSubstrate(data[1]),2155 amount: BigInt(data[2]),2156 };2157 }2158 });2159 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2160 && this.helper.address.normalizeSubstrate(address) === transfer.to 2161 && BigInt(amount) === transfer.amount;2162 return isSuccess;2163 }21642165 /**2166 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2167 * @param address substrate address2168 * @returns2169 */2170 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2171 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2172 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2173 }2174}21752176class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2177 /**2178 * Get ethereum address balance2179 * @param address ethereum address2180 * @example getEthereum("0x9F0583DbB855d...")2181 * @returns amount of tokens on address2182 */2183 async getEthereum(address: TEthereumAccount): Promise<bigint> {2184 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2185 }21862187 /**2188 * Transfer tokens to address2189 * @param signer keyring of signer2190 * @param address Ethereum address of a recipient2191 * @param amount amount of tokens to be transfered2192 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2193 * @returns ```true``` if extrinsic success, otherwise ```false```2194 */2195 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2196 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);21972198 let transfer = {from: null, to: null, amount: 0n} as any;2199 result.result.events.forEach(({event: {data, method, section}}) => {2200 if ((section === 'balances') && (method === 'Transfer')) {2201 transfer = {2202 from: data[0].toString(),2203 to: data[1].toString(),2204 amount: BigInt(data[2]),2205 };2206 }2207 });2208 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from 2209 && address === transfer.to 2210 && BigInt(amount) === transfer.amount;2211 return isSuccess;2212 }2213}22142215class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2216 subBalanceGroup: SubstrateBalanceGroup<T>;2217 ethBalanceGroup: EthereumBalanceGroup<T>;22182219 constructor(helper: T) {2220 super(helper);2221 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2222 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2223 }22242225 getCollectionCreationPrice(): bigint {2226 return 2n * this.getOneTokenNominal();2227 }2228 /**2229 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2230 * @example getOneTokenNominal()2231 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2232 */2233 getOneTokenNominal(): bigint {2234 const chainProperties = this.helper.chain.getChainProperties();2235 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2236 }22372238 /**2239 * Get substrate address balance2240 * @param address substrate address2241 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2242 * @returns amount of tokens on address2243 */2244 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2245 return this.subBalanceGroup.getSubstrate(address);2246 }22472248 /**2249 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2250 * @param address substrate address2251 * @returns2252 */2253 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2254 return this.subBalanceGroup.getSubstrateFull(address);2255 }22562257 /**2258 * Get ethereum address balance2259 * @param address ethereum address2260 * @example getEthereum("0x9F0583DbB855d...")2261 * @returns amount of tokens on address2262 */2263 async getEthereum(address: TEthereumAccount): Promise<bigint> {2264 return this.ethBalanceGroup.getEthereum(address);2265 }22662267 /**2268 * Transfer tokens to substrate address2269 * @param signer keyring of signer2270 * @param address substrate address of a recipient2271 * @param amount amount of tokens to be transfered2272 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2273 * @returns ```true``` if extrinsic success, otherwise ```false```2274 */2275 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2276 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2277 }22782279 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2280 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);22812282 let transfer = {from: null, to: null, amount: 0n} as any;2283 result.result.events.forEach(({event: {data, method, section}}) => {2284 if ((section === 'balances') && (method === 'Transfer')) {2285 transfer = {2286 from: this.helper.address.normalizeSubstrate(data[0]),2287 to: this.helper.address.normalizeSubstrate(data[1]),2288 amount: BigInt(data[2]),2289 };2290 }2291 });2292 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2293 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2294 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2295 return isSuccess;2296 }2297}22982299class AddressGroup extends HelperGroup<ChainHelperBase> {2300 /**2301 * Normalizes the address to the specified ss58 format, by default ```42```.2302 * @param address substrate address2303 * @param ss58Format format for address conversion, by default ```42```2304 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2305 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2306 */2307 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2308 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2309 }23102311 /**2312 * Get address in the connected chain format2313 * @param address substrate address2314 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2315 * @returns address in chain format2316 */2317 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2318 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2319 }23202321 /**2322 * Get substrate mirror of an ethereum address2323 * @param ethAddress ethereum address2324 * @param toChainFormat false for normalized account2325 * @example ethToSubstrate('0x9F0583DbB855d...')2326 * @returns substrate mirror of a provided ethereum address2327 */2328 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2329 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2330 }23312332 /**2333 * Get ethereum mirror of a substrate address2334 * @param subAddress substrate account2335 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2336 * @returns ethereum mirror of a provided substrate address2337 */2338 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2339 return CrossAccountId.translateSubToEth(subAddress);2340 }23412342 paraSiblingSovereignAccount(paraid: number) {2343 // We are getting a *sibling* parachain sovereign account,2344 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2345 const siblingPrefix = '0x7369626c';23462347 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2348 const suffix = '000000000000000000000000000000000000000000000000';23492350 return siblingPrefix + encodedParaId + suffix;2351 }2352}23532354class StakingGroup extends HelperGroup<UniqueHelper> {2355 /**2356 * Stake tokens for App Promotion2357 * @param signer keyring of signer2358 * @param amountToStake amount of tokens to stake2359 * @param label extra label for log2360 * @returns2361 */2362 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2363 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2364 const _stakeResult = await this.helper.executeExtrinsic(2365 signer, 'api.tx.appPromotion.stake',2366 [amountToStake], true,2367 );2368 // TODO extract info from stakeResult2369 return true;2370 }23712372 /**2373 * Unstake tokens for App Promotion2374 * @param signer keyring of signer2375 * @param amountToUnstake amount of tokens to unstake2376 * @param label extra label for log2377 * @returns block number where balances will be unlocked2378 */2379 async unstake(signer: TSigner, label?: string): Promise<number> {2380 if(typeof label === 'undefined') label = `${signer.address}`;2381 const _unstakeResult = await this.helper.executeExtrinsic(2382 signer, 'api.tx.appPromotion.unstake',2383 [], true,2384 );2385 // TODO extract block number fron events2386 return 1;2387 }23882389 /**2390 * Get total staked amount for address2391 * @param address substrate or ethereum address2392 * @returns total staked amount2393 */2394 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2395 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2396 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2397 }23982399 /**2400 * Get total staked per block2401 * @param address substrate or ethereum address2402 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2403 */2404 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2405 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2406 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2407 return { 2408 block: block.toBigInt(),2409 amount: amount.toBigInt(),2410 };2411 });2412 }24132414 /**2415 * Get total pending unstake amount for address2416 * @param address substrate or ethereum address2417 * @returns total pending unstake amount2418 */2419 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2420 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2421 }24222423 /**2424 * Get pending unstake amount per block for address2425 * @param address substrate or ethereum address2426 * @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 block2427 */2428 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2429 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2430 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2431 return {2432 block: block.toBigInt(),2433 amount: amount.toBigInt(),2434 };2435 });2436 return result;2437 }2438}24392440class SchedulerGroup extends HelperGroup<UniqueHelper> {2441 constructor(helper: UniqueHelper) {2442 super(helper);2443 }24442445 async cancelScheduled(signer: TSigner, scheduledId: string) {2446 return this.helper.executeExtrinsic(2447 signer,2448 'api.tx.scheduler.cancelNamed',2449 [scheduledId],2450 true,2451 );2452 }24532454 async changePriority(signer: TSigner, scheduledId: string, priority: number) {2455 return this.helper.executeExtrinsic(2456 signer,2457 'api.tx.scheduler.changeNamedPriority',2458 [scheduledId, priority],2459 true,2460 );2461 }24622463 scheduleAt<T extends UniqueHelper>(2464 scheduledId: string,2465 executionBlockNumber: number,2466 options: ISchedulerOptions = {},2467 ) {2468 return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2469 }24702471 scheduleAfter<T extends UniqueHelper>(2472 scheduledId: string,2473 blocksBeforeExecution: number,2474 options: ISchedulerOptions = {},2475 ) {2476 return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2477 }24782479 schedule<T extends UniqueHelper>(2480 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2481 scheduledId: string,2482 blocksNum: number,2483 options: ISchedulerOptions = {},2484 ) {2485 // eslint-disable-next-line @typescript-eslint/naming-convention2486 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2487 return this.helper.clone(ScheduledHelperType, {2488 scheduleFn,2489 scheduledId,2490 blocksNum,2491 options,2492 }) as T;2493 }2494}24952496class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2497 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2498 await this.helper.executeExtrinsic(2499 signer,2500 'api.tx.foreignAssets.registerForeignAsset',2501 [ownerAddress, location, metadata],2502 true,2503 );2504 }25052506 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2507 await this.helper.executeExtrinsic(2508 signer,2509 'api.tx.foreignAssets.updateForeignAsset',2510 [foreignAssetId, location, metadata],2511 true,2512 );2513 }2514}25152516class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2517 palletName: string;25182519 constructor(helper: T, palletName: string) {2520 super(helper);25212522 this.palletName = palletName;2523 }25242525 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2526 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2527 }2528}25292530class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2531 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2532 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2533 }25342535 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2536 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2537 }25382539 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2540 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2541 }2542}25432544class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2545 async accounts(address: string, currencyId: any) {2546 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2547 return BigInt(free);2548 }2549}25502551class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2552 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2553 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2554 }25552556 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2557 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2558 }25592560 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2561 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2562 }25632564 async account(assetId: string | number, address: string) {2565 const accountAsset = (2566 await this.helper.callRpc('api.query.assets.account', [assetId, address])2567 ).toJSON()! as any;25682569 if (accountAsset !== null) {2570 return BigInt(accountAsset['balance']);2571 } else {2572 return null;2573 }2574 }2575}25762577class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2578 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2579 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2580 }2581}25822583class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2584 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2585 const apiPrefix = 'api.tx.assetManager.';25862587 const registerTx = this.helper.constructApiCall(2588 apiPrefix + 'registerForeignAsset',2589 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2590 );25912592 const setUnitsTx = this.helper.constructApiCall(2593 apiPrefix + 'setAssetUnitsPerSecond',2594 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2595 );25962597 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2598 const encodedProposal = batchCall?.method.toHex() || '';2599 return encodedProposal;2600 }26012602 async assetTypeId(location: any) {2603 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2604 }2605}26062607class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2608 async notePreimage(signer: TSigner, encodedProposal: string) {2609 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2610 }26112612 externalProposeMajority(proposalHash: string) {2613 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2614 }26152616 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2617 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2618 }26192620 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2621 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2622 }2623}26242625class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2626 collective: string;26272628 constructor(helper: MoonbeamHelper, collective: string) {2629 super(helper);26302631 this.collective = collective;2632 }26332634 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2635 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2636 }26372638 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2639 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2640 }26412642 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2643 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2644 }26452646 async proposalCount() {2647 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2648 }2649}26502651export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2652export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;26532654export class UniqueHelper extends ChainHelperBase {2655 balance: BalanceGroup<UniqueHelper>;2656 collection: CollectionGroup;2657 nft: NFTGroup;2658 rft: RFTGroup;2659 ft: FTGroup;2660 staking: StakingGroup;2661 scheduler: SchedulerGroup;2662 foreignAssets: ForeignAssetsGroup;2663 xcm: XcmGroup<UniqueHelper>;2664 xTokens: XTokensGroup<UniqueHelper>;2665 tokens: TokensGroup<UniqueHelper>;26662667 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2668 super(logger, options.helperBase ?? UniqueHelper);26692670 this.balance = new BalanceGroup(this);2671 this.collection = new CollectionGroup(this);2672 this.nft = new NFTGroup(this);2673 this.rft = new RFTGroup(this);2674 this.ft = new FTGroup(this);2675 this.staking = new StakingGroup(this);2676 this.scheduler = new SchedulerGroup(this);2677 this.foreignAssets = new ForeignAssetsGroup(this);2678 this.xcm = new XcmGroup(this, 'polkadotXcm');2679 this.xTokens = new XTokensGroup(this);2680 this.tokens = new TokensGroup(this);2681 }26822683 getSudo<T extends UniqueHelper>() {2684 // eslint-disable-next-line @typescript-eslint/naming-convention2685 const SudoHelperType = SudoHelper(this.helperBase);2686 return this.clone(SudoHelperType) as T;2687 }2688}26892690export class XcmChainHelper extends ChainHelperBase {2691 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2692 const wsProvider = new WsProvider(wsEndpoint);2693 this.api = new ApiPromise({2694 provider: wsProvider,2695 });2696 await this.api.isReadyOrError;2697 this.network = await UniqueHelper.detectNetwork(this.api);2698 }2699}27002701export class RelayHelper extends XcmChainHelper {2702 xcm: XcmGroup<RelayHelper>;27032704 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2705 super(logger, options.helperBase ?? RelayHelper);27062707 this.xcm = new XcmGroup(this, 'xcmPallet');2708 }2709}27102711export class WestmintHelper extends XcmChainHelper {2712 balance: SubstrateBalanceGroup<WestmintHelper>;2713 xcm: XcmGroup<WestmintHelper>;2714 assets: AssetsGroup<WestmintHelper>;2715 xTokens: XTokensGroup<WestmintHelper>;27162717 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2718 super(logger, options.helperBase ?? WestmintHelper);27192720 this.balance = new SubstrateBalanceGroup(this);2721 this.xcm = new XcmGroup(this, 'polkadotXcm');2722 this.assets = new AssetsGroup(this);2723 this.xTokens = new XTokensGroup(this);2724 }2725}27262727export class MoonbeamHelper extends XcmChainHelper {2728 balance: EthereumBalanceGroup<MoonbeamHelper>;2729 assetManager: MoonbeamAssetManagerGroup;2730 assets: AssetsGroup<MoonbeamHelper>;2731 xTokens: XTokensGroup<MoonbeamHelper>;2732 democracy: MoonbeamDemocracyGroup;2733 collective: {2734 council: MoonbeamCollectiveGroup,2735 techCommittee: MoonbeamCollectiveGroup,2736 };27372738 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2739 super(logger, options.helperBase ?? MoonbeamHelper);27402741 this.balance = new EthereumBalanceGroup(this);2742 this.assetManager = new MoonbeamAssetManagerGroup(this);2743 this.assets = new AssetsGroup(this);2744 this.xTokens = new XTokensGroup(this);2745 this.democracy = new MoonbeamDemocracyGroup(this);2746 this.collective = {2747 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2748 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2749 };2750 }2751}27522753export class AcalaHelper extends XcmChainHelper {2754 balance: SubstrateBalanceGroup<AcalaHelper>;2755 assetRegistry: AcalaAssetRegistryGroup;2756 xTokens: XTokensGroup<AcalaHelper>;2757 tokens: TokensGroup<AcalaHelper>;27582759 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2760 super(logger, options.helperBase ?? AcalaHelper);27612762 this.balance = new SubstrateBalanceGroup(this);2763 this.assetRegistry = new AcalaAssetRegistryGroup(this);2764 this.xTokens = new XTokensGroup(this);2765 this.tokens = new TokensGroup(this);2766 }27672768 getSudo<T extends AcalaHelper>() {2769 // eslint-disable-next-line @typescript-eslint/naming-convention2770 const SudoHelperType = SudoHelper(this.helperBase);2771 return this.clone(SudoHelperType) as T;2772 }2773}27742775export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;27762777// eslint-disable-next-line @typescript-eslint/naming-convention2778function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2779 return class extends Base {2780 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2781 scheduledId: string;2782 blocksNum: number;2783 options: ISchedulerOptions;27842785 constructor(...args: any[]) {2786 const logger = args[0] as ILogger;2787 const options = args[1] as {2788 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2789 scheduledId: string,2790 blocksNum: number,2791 options: ISchedulerOptions2792 };27932794 super(logger);27952796 this.scheduleFn = options.scheduleFn;2797 this.scheduledId = options.scheduledId;2798 this.blocksNum = options.blocksNum;2799 this.options = options.options;2800 }28012802 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2803 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2804 const extrinsic = 'api.tx.scheduler.' + this.scheduleFn;28052806 return super.executeExtrinsic(2807 sender,2808 extrinsic,2809 [2810 this.scheduledId,2811 this.blocksNum,2812 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2813 this.options.priority ?? null,2814 {Value: scheduledTx},2815 ],2816 expectSuccess,2817 );2818 }2819 };2820}28212822// eslint-disable-next-line @typescript-eslint/naming-convention2823function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2824 return class extends Base {2825 constructor(...args: any[]) {2826 super(...args);2827 }28282829 executeExtrinsic (2830 sender: IKeyringPair,2831 extrinsic: string,2832 params: any[],2833 expectSuccess?: boolean,2834 ): Promise<ITransactionResult> {2835 const call = this.constructApiCall(extrinsic, params);2836 return super.executeExtrinsic(2837 sender,2838 'api.tx.sudo.sudo',2839 [call],2840 expectSuccess,2841 );2842 }2843 };2844}28452846export class UniqueBaseCollection {2847 helper: UniqueHelper;2848 collectionId: number;28492850 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2851 this.collectionId = collectionId;2852 this.helper = uniqueHelper;2853 }28542855 async getData() {2856 return await this.helper.collection.getData(this.collectionId);2857 }28582859 async getLastTokenId() {2860 return await this.helper.collection.getLastTokenId(this.collectionId);2861 }28622863 async doesTokenExist(tokenId: number) {2864 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2865 }28662867 async getAdmins() {2868 return await this.helper.collection.getAdmins(this.collectionId);2869 }28702871 async getAllowList() {2872 return await this.helper.collection.getAllowList(this.collectionId);2873 }28742875 async getEffectiveLimits() {2876 return await this.helper.collection.getEffectiveLimits(this.collectionId);2877 }28782879 async getProperties(propertyKeys?: string[] | null) {2880 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2881 }28822883 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2884 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2885 }28862887 async getOptions() {2888 return await this.helper.collection.getCollectionOptions(this.collectionId);2889 }28902891 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2892 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2893 }28942895 async confirmSponsorship(signer: TSigner) {2896 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2897 }28982899 async removeSponsor(signer: TSigner) {2900 return await this.helper.collection.removeSponsor(signer, this.collectionId);2901 }29022903 async setLimits(signer: TSigner, limits: ICollectionLimits) {2904 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2905 }29062907 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2908 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2909 }29102911 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2912 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2913 }29142915 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2916 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2917 }29182919 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2920 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2921 }29222923 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2924 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2925 }29262927 async setProperties(signer: TSigner, properties: IProperty[]) {2928 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2929 }29302931 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2932 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2933 }29342935 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2936 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2937 }29382939 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2940 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2941 }29422943 async disableNesting(signer: TSigner) {2944 return await this.helper.collection.disableNesting(signer, this.collectionId);2945 }29462947 async burn(signer: TSigner) {2948 return await this.helper.collection.burn(signer, this.collectionId);2949 }29502951 scheduleAt<T extends UniqueHelper>(2952 scheduledId: string,2953 executionBlockNumber: number,2954 options: ISchedulerOptions = {},2955 ) {2956 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2957 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2958 }29592960 scheduleAfter<T extends UniqueHelper>(2961 scheduledId: string,2962 blocksBeforeExecution: number,2963 options: ISchedulerOptions = {},2964 ) {2965 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2966 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2967 }29682969 getSudo<T extends UniqueHelper>() {2970 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2971 }2972}297329742975export class UniqueNFTCollection extends UniqueBaseCollection {2976 getTokenObject(tokenId: number) {2977 return new UniqueNFToken(tokenId, this);2978 }29792980 async getTokensByAddress(addressObj: ICrossAccountId) {2981 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2982 }29832984 async getToken(tokenId: number, blockHashAt?: string) {2985 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2986 }29872988 async getTokenOwner(tokenId: number, blockHashAt?: string) {2989 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2990 }29912992 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2993 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2994 }29952996 async getTokenChildren(tokenId: number, blockHashAt?: string) {2997 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2998 }29993000 async getPropertyPermissions(propertyKeys: string[] | null = null) {3001 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3002 }30033004 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3005 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3006 }30073008 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3009 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3010 }30113012 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3013 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3014 }30153016 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3017 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3018 }30193020 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3021 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3022 }30233024 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3025 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3026 }30273028 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3029 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3030 }30313032 async burnToken(signer: TSigner, tokenId: number) {3033 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3034 }30353036 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3037 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3038 }30393040 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3041 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3042 }30433044 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3045 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3046 }30473048 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3049 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3050 }30513052 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3053 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3054 }30553056 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3057 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3058 }30593060 scheduleAt<T extends UniqueHelper>(3061 scheduledId: string,3062 executionBlockNumber: number,3063 options: ISchedulerOptions = {},3064 ) {3065 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3066 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3067 }30683069 scheduleAfter<T extends UniqueHelper>(3070 scheduledId: string,3071 blocksBeforeExecution: number,3072 options: ISchedulerOptions = {},3073 ) {3074 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3075 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3076 }30773078 getSudo<T extends UniqueHelper>() {3079 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3080 }3081}308230833084export class UniqueRFTCollection extends UniqueBaseCollection {3085 getTokenObject(tokenId: number) {3086 return new UniqueRFToken(tokenId, this);3087 }30883089 async getToken(tokenId: number, blockHashAt?: string) {3090 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3091 }30923093 async getTokensByAddress(addressObj: ICrossAccountId) {3094 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3095 }30963097 async getTop10TokenOwners(tokenId: number) {3098 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3099 }31003101 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3102 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3103 }31043105 async getTokenTotalPieces(tokenId: number) {3106 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3107 }31083109 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3110 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3111 }31123113 async getPropertyPermissions(propertyKeys: string[] | null = null) {3114 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3115 }31163117 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3118 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3119 }31203121 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3122 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3123 }31243125 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3126 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3127 }31283129 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3130 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3131 }31323133 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3134 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3135 }31363137 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3138 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3139 }31403141 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3142 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3143 }31443145 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3146 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3147 }31483149 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3150 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3151 }31523153 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3154 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3155 }31563157 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3158 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3159 }31603161 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3162 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3163 }31643165 scheduleAt<T extends UniqueHelper>(3166 scheduledId: string,3167 executionBlockNumber: number,3168 options: ISchedulerOptions = {},3169 ) {3170 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3171 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3172 }31733174 scheduleAfter<T extends UniqueHelper>(3175 scheduledId: string,3176 blocksBeforeExecution: number,3177 options: ISchedulerOptions = {},3178 ) {3179 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3180 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3181 }31823183 getSudo<T extends UniqueHelper>() {3184 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3185 }3186}318731883189export class UniqueFTCollection extends UniqueBaseCollection {3190 async getBalance(addressObj: ICrossAccountId) {3191 return await this.helper.ft.getBalance(this.collectionId, addressObj);3192 }31933194 async getTotalPieces() {3195 return await this.helper.ft.getTotalPieces(this.collectionId);3196 }31973198 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3199 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3200 }32013202 async getTop10Owners() {3203 return await this.helper.ft.getTop10Owners(this.collectionId);3204 }32053206 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3207 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3208 }32093210 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3211 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3212 }32133214 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3215 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3216 }32173218 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3219 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3220 }32213222 async burnTokens(signer: TSigner, amount=1n) {3223 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3224 }32253226 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3227 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3228 }32293230 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3231 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3232 }32333234 scheduleAt<T extends UniqueHelper>(3235 scheduledId: string,3236 executionBlockNumber: number,3237 options: ISchedulerOptions = {},3238 ) {3239 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3240 return new UniqueFTCollection(this.collectionId, scheduledHelper);3241 }32423243 scheduleAfter<T extends UniqueHelper>(3244 scheduledId: string,3245 blocksBeforeExecution: number,3246 options: ISchedulerOptions = {},3247 ) {3248 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3249 return new UniqueFTCollection(this.collectionId, scheduledHelper);3250 }32513252 getSudo<T extends UniqueHelper>() {3253 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3254 }3255}325632573258export class UniqueBaseToken {3259 collection: UniqueNFTCollection | UniqueRFTCollection;3260 collectionId: number;3261 tokenId: number;32623263 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3264 this.collection = collection;3265 this.collectionId = collection.collectionId;3266 this.tokenId = tokenId;3267 }32683269 async getNextSponsored(addressObj: ICrossAccountId) {3270 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3271 }32723273 async getProperties(propertyKeys?: string[] | null) {3274 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3275 }32763277 async setProperties(signer: TSigner, properties: IProperty[]) {3278 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3279 }32803281 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3282 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3283 }32843285 async doesExist() {3286 return await this.collection.doesTokenExist(this.tokenId);3287 }32883289 nestingAccount() {3290 return this.collection.helper.util.getTokenAccount(this);3291 }32923293 scheduleAt<T extends UniqueHelper>(3294 scheduledId: string,3295 executionBlockNumber: number,3296 options: ISchedulerOptions = {},3297 ) {3298 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3299 return new UniqueBaseToken(this.tokenId, scheduledCollection);3300 }33013302 scheduleAfter<T extends UniqueHelper>(3303 scheduledId: string,3304 blocksBeforeExecution: number,3305 options: ISchedulerOptions = {},3306 ) {3307 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3308 return new UniqueBaseToken(this.tokenId, scheduledCollection);3309 }33103311 getSudo<T extends UniqueHelper>() {3312 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3313 }3314}331533163317export class UniqueNFToken extends UniqueBaseToken {3318 collection: UniqueNFTCollection;33193320 constructor(tokenId: number, collection: UniqueNFTCollection) {3321 super(tokenId, collection);3322 this.collection = collection;3323 }33243325 async getData(blockHashAt?: string) {3326 return await this.collection.getToken(this.tokenId, blockHashAt);3327 }33283329 async getOwner(blockHashAt?: string) {3330 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3331 }33323333 async getTopmostOwner(blockHashAt?: string) {3334 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3335 }33363337 async getChildren(blockHashAt?: string) {3338 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3339 }33403341 async nest(signer: TSigner, toTokenObj: IToken) {3342 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3343 }33443345 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3346 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3347 }33483349 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3350 return await this.collection.transferToken(signer, this.tokenId, addressObj);3351 }33523353 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3354 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3355 }33563357 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3358 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3359 }33603361 async isApproved(toAddressObj: ICrossAccountId) {3362 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3363 }33643365 async burn(signer: TSigner) {3366 return await this.collection.burnToken(signer, this.tokenId);3367 }33683369 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3370 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3371 }33723373 scheduleAt<T extends UniqueHelper>(3374 scheduledId: string,3375 executionBlockNumber: number,3376 options: ISchedulerOptions = {},3377 ) {3378 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3379 return new UniqueNFToken(this.tokenId, scheduledCollection);3380 }33813382 scheduleAfter<T extends UniqueHelper>(3383 scheduledId: string,3384 blocksBeforeExecution: number,3385 options: ISchedulerOptions = {},3386 ) {3387 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3388 return new UniqueNFToken(this.tokenId, scheduledCollection);3389 }33903391 getSudo<T extends UniqueHelper>() {3392 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3393 }3394}33953396export class UniqueRFToken extends UniqueBaseToken {3397 collection: UniqueRFTCollection;33983399 constructor(tokenId: number, collection: UniqueRFTCollection) {3400 super(tokenId, collection);3401 this.collection = collection;3402 }34033404 async getData(blockHashAt?: string) {3405 return await this.collection.getToken(this.tokenId, blockHashAt);3406 }34073408 async getTop10Owners() {3409 return await this.collection.getTop10TokenOwners(this.tokenId);3410 }34113412 async getBalance(addressObj: ICrossAccountId) {3413 return await this.collection.getTokenBalance(this.tokenId, addressObj);3414 }34153416 async getTotalPieces() {3417 return await this.collection.getTokenTotalPieces(this.tokenId);3418 }34193420 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3421 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3422 }34233424 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3425 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3426 }34273428 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3429 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3430 }34313432 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3433 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3434 }34353436 async repartition(signer: TSigner, amount: bigint) {3437 return await this.collection.repartitionToken(signer, this.tokenId, amount);3438 }34393440 async burn(signer: TSigner, amount=1n) {3441 return await this.collection.burnToken(signer, this.tokenId, amount);3442 }34433444 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3445 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3446 }34473448 scheduleAt<T extends UniqueHelper>(3449 scheduledId: string,3450 executionBlockNumber: number,3451 options: ISchedulerOptions = {},3452 ) {3453 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3454 return new UniqueRFToken(this.tokenId, scheduledCollection);3455 }34563457 scheduleAfter<T extends UniqueHelper>(3458 scheduledId: string,3459 blocksBeforeExecution: number,3460 options: ISchedulerOptions = {},3461 ) {3462 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3463 return new UniqueRFToken(this.tokenId, scheduledCollection);3464 }34653466 getSudo<T extends UniqueHelper>() {3467 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3468 }3469}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISchedulerOptions, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, IForeignAssetMetadata, TNetworks, MoonbeamAssetInfo, DemocracyStandardAccountVote, AcalaAssetMetadata} from './types';13import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';1415export class CrossAccountId implements ICrossAccountId {16 Substrate?: TSubstrateAccount;17 Ethereum?: TEthereumAccount;1819 constructor(account: ICrossAccountId) {20 if (account.Substrate) this.Substrate = account.Substrate;21 if (account.Ethereum) this.Ethereum = account.Ethereum;22 }2324 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {25 switch (domain) {26 case 'Substrate': return new CrossAccountId({Substrate: account.address});27 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();28 }29 }3031 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {32 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});33 }3435 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {36 return encodeAddress(decodeAddress(address), ss58Format);37 }3839 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {40 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});41 }42 43 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {44 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);45 return this;46 }4748 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {49 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));50 }5152 toEthereum(): CrossAccountId {53 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});54 return this;55 }5657 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {58 return evmToAddress(address, ss58Format);59 }6061 toSubstrate(ss58Format?: number): CrossAccountId {62 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});63 return this;64 }65 66 toLowerCase(): CrossAccountId {67 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();68 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();69 return this;70 }71}7273const nesting = {74 toChecksumAddress(address: string): string {75 if (typeof address === 'undefined') return '';7677 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);7879 address = address.toLowerCase().replace(/^0x/i,'');80 const addressHash = keccakAsHex(address).replace(/^0x/i,'');81 const checksumAddress = ['0x'];8283 for (let i = 0; i < address.length; i++) {84 // If ith character is 8 to f then make it uppercase85 if (parseInt(addressHash[i], 16) > 7) {86 checksumAddress.push(address[i].toUpperCase());87 } else {88 checksumAddress.push(address[i]);89 }90 }91 return checksumAddress.join('');92 },93 tokenIdToAddress(collectionId: number, tokenId: number) {94 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);95 },96};9798class UniqueUtil {99 static transactionStatus = {100 NOT_READY: 'NotReady',101 FAIL: 'Fail',102 SUCCESS: 'Success',103 };104105 static chainLogType = {106 EXTRINSIC: 'extrinsic',107 RPC: 'rpc',108 };109110 static getTokenAccount(token: IToken): CrossAccountId {111 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});112 }113114 static getTokenAddress(token: IToken): string {115 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);116 }117118 static getDefaultLogger(): ILogger {119 return {120 log(msg: any, level = 'INFO') {121 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));122 },123 level: {124 ERROR: 'ERROR',125 WARNING: 'WARNING',126 INFO: 'INFO',127 },128 };129 }130131 static vec2str(arr: string[] | number[]) {132 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');133 }134135 static str2vec(string: string) {136 if (typeof string !== 'string') return string;137 return Array.from(string).map(x => x.charCodeAt(0));138 }139140 static fromSeed(seed: string, ss58Format = 42) {141 const keyring = new Keyring({type: 'sr25519', ss58Format});142 return keyring.addFromUri(seed);143 }144145 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {146 if (creationResult.status !== this.transactionStatus.SUCCESS) {147 throw Error('Unable to create collection!');148 }149150 let collectionId = null;151 creationResult.result.events.forEach(({event: {data, method, section}}) => {152 if ((section === 'common') && (method === 'CollectionCreated')) {153 collectionId = parseInt(data[0].toString(), 10);154 }155 });156157 if (collectionId === null) {158 throw Error('No CollectionCreated event was found!');159 }160161 return collectionId;162 }163164 static extractTokensFromCreationResult(creationResult: ITransactionResult): {165 success: boolean, 166 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],167 } {168 if (creationResult.status !== this.transactionStatus.SUCCESS) {169 throw Error('Unable to create tokens!');170 }171 let success = false;172 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];173 creationResult.result.events.forEach(({event: {data, method, section}}) => {174 if (method === 'ExtrinsicSuccess') {175 success = true;176 } else if ((section === 'common') && (method === 'ItemCreated')) {177 tokens.push({178 collectionId: parseInt(data[0].toString(), 10),179 tokenId: parseInt(data[1].toString(), 10),180 owner: data[2].toHuman(),181 amount: data[3].toBigInt(),182 });183 }184 });185 return {success, tokens};186 }187188 static extractTokensFromBurnResult(burnResult: ITransactionResult): {189 success: boolean, 190 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],191 } {192 if (burnResult.status !== this.transactionStatus.SUCCESS) {193 throw Error('Unable to burn tokens!');194 }195 let success = false;196 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];197 burnResult.result.events.forEach(({event: {data, method, section}}) => {198 if (method === 'ExtrinsicSuccess') {199 success = true;200 } else if ((section === 'common') && (method === 'ItemDestroyed')) {201 tokens.push({202 collectionId: parseInt(data[0].toString(), 10),203 tokenId: parseInt(data[1].toString(), 10),204 owner: data[2].toHuman(),205 amount: data[3].toBigInt(),206 });207 }208 });209 return {success, tokens};210 }211212 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {213 let eventId = null;214 events.forEach(({event: {data, method, section}}) => {215 if ((section === expectedSection) && (method === expectedMethod)) {216 eventId = parseInt(data[0].toString(), 10);217 }218 });219220 if (eventId === null) {221 throw Error(`No ${expectedMethod} event was found!`);222 }223 return eventId === collectionId;224 }225226 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {227 const normalizeAddress = (address: string | ICrossAccountId) => {228 if(typeof address === 'string') return address;229 const obj = {} as any;230 Object.keys(address).forEach(k => {231 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];232 });233 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);234 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();235 return address;236 };237 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;238 events.forEach(({event: {data, method, section}}) => {239 if ((section === 'common') && (method === 'Transfer')) {240 const hData = (data as any).toJSON();241 transfer = {242 collectionId: hData[0],243 tokenId: hData[1],244 from: normalizeAddress(hData[2]),245 to: normalizeAddress(hData[3]),246 amount: BigInt(hData[4]),247 };248 }249 });250 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;251 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);252 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);253 isSuccess = isSuccess && amount === transfer.amount;254 return isSuccess;255 }256257 static bigIntToDecimals(number: bigint, decimals = 18) {258 const numberStr = number.toString();259 const dotPos = numberStr.length - decimals;260 261 if (dotPos <= 0) {262 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;263 } else {264 const intPart = numberStr.substring(0, dotPos);265 const fractPart = numberStr.substring(dotPos);266 return intPart + '.' + fractPart;267 }268 }269}270271class UniqueEventHelper {272 private static extractIndex(index: any): [number, number] | string {273 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];274 return index.toJSON();275 }276277 private static extractSub(data: any, subTypes: any): {[key: string]: any} {278 let obj: any = {};279 let index = 0;280281 if (data.entries) {282 for(const [key, value] of data.entries()) {283 obj[key] = this.extractData(value, subTypes[index]);284 index++;285 }286 } else obj = data.toJSON();287288 return obj;289 }290 291 private static extractData(data: any, type: any): any {292 if(!type) return data.toHuman();293 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();294 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();295 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);296 return data.toHuman();297 }298299 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {300 const parsedEvents: IEvent[] = [];301302 events.forEach((record) => {303 const {event, phase} = record;304 const types = event.typeDef;305306 const eventData: IEvent = {307 section: event.section.toString(),308 method: event.method.toString(),309 index: this.extractIndex(event.index),310 data: [],311 phase: phase.toJSON(),312 };313314 event.data.forEach((val: any, index: number) => {315 eventData.data.push(this.extractData(val, types[index]));316 });317318 parsedEvents.push(eventData);319 });320321 return parsedEvents;322 }323}324325export class ChainHelperBase {326 helperBase: any;327328 transactionStatus = UniqueUtil.transactionStatus;329 chainLogType = UniqueUtil.chainLogType;330 util: typeof UniqueUtil;331 eventHelper: typeof UniqueEventHelper;332 logger: ILogger;333 api: ApiPromise | null;334 forcedNetwork: TNetworks | null;335 network: TNetworks | null;336 chainLog: IUniqueHelperLog[];337 children: ChainHelperBase[];338 address: AddressGroup;339 chain: ChainGroup;340341 constructor(logger?: ILogger, helperBase?: any) {342 this.helperBase = helperBase;343344 this.util = UniqueUtil;345 this.eventHelper = UniqueEventHelper;346 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();347 this.logger = logger;348 this.api = null;349 this.forcedNetwork = null;350 this.network = null;351 this.chainLog = [];352 this.children = [];353 this.address = new AddressGroup(this);354 this.chain = new ChainGroup(this);355 }356357 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {358 Object.setPrototypeOf(helperCls.prototype, this);359 const newHelper = new helperCls(this.logger, options);360361 newHelper.api = this.api;362 newHelper.network = this.network;363 newHelper.forceNetwork = this.forceNetwork;364365 this.children.push(newHelper);366367 return newHelper;368 }369370 getApi(): ApiPromise {371 if(this.api === null) throw Error('API not initialized');372 return this.api;373 }374375 clearChainLog(): void {376 this.chainLog = [];377 }378379 forceNetwork(value: TNetworks): void {380 this.forcedNetwork = value;381 }382383 async connect(wsEndpoint: string, listeners?: IApiListeners) {384 if (this.api !== null) throw Error('Already connected');385 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);386 this.api = api;387 this.network = network;388 }389390 async disconnect() {391 for (const child of this.children) {392 child.clearApi();393 }394395 if (this.api === null) return;396 await this.api.disconnect();397 this.clearApi();398 }399400 clearApi() {401 this.api = null;402 this.network = null;403 }404405 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {406 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;407 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];408409 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;410411 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;412 return 'opal';413 }414415 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {416 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});417 await api.isReady;418419 const network = await this.detectNetwork(api);420421 await api.disconnect();422423 return network;424 }425426 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{427 api: ApiPromise;428 network: TNetworks;429 }> {430 if(typeof network === 'undefined' || network === null) network = 'opal';431 const supportedRPC = {432 opal: {433 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,434 },435 quartz: {436 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,437 },438 unique: {439 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,440 },441 rococo: {},442 westend: {},443 moonbeam: {},444 moonriver: {},445 acala: {},446 karura: {},447 westmint: {},448 };449 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);450 const rpc = supportedRPC[network];451452 // TODO: investigate how to replace rpc in runtime453 // api._rpcCore.addUserInterfaces(rpc);454455 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});456457 await api.isReadyOrError;458459 if (typeof listeners === 'undefined') listeners = {};460 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {461 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;462 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);463 }464465 return {api, network};466 }467468 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {469 const {events, status} = data;470 if (status.isReady) {471 return this.transactionStatus.NOT_READY;472 }473 if (status.isBroadcast) {474 return this.transactionStatus.NOT_READY;475 }476 if (status.isInBlock || status.isFinalized) {477 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');478 if (errors.length > 0) {479 return this.transactionStatus.FAIL;480 }481 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {482 return this.transactionStatus.SUCCESS;483 }484 }485486 return this.transactionStatus.FAIL;487 }488489 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {490 const sign = (callback: any) => {491 if(options !== null) return transaction.signAndSend(sender, options, callback);492 return transaction.signAndSend(sender, callback);493 };494 // eslint-disable-next-line no-async-promise-executor495 return new Promise(async (resolve, reject) => {496 try {497 const unsub = await sign((result: any) => {498 const status = this.getTransactionStatus(result);499500 if (status === this.transactionStatus.SUCCESS) {501 this.logger.log(`${label} successful`);502 unsub();503 resolve({result, status});504 } else if (status === this.transactionStatus.FAIL) {505 let moduleError = null;506507 if (result.hasOwnProperty('dispatchError')) {508 const dispatchError = result['dispatchError'];509510 if (dispatchError) {511 if (dispatchError.isModule) {512 const modErr = dispatchError.asModule;513 const errorMeta = dispatchError.registry.findMetaError(modErr);514515 moduleError = `${errorMeta.section}.${errorMeta.name}`;516 } else {517 moduleError = dispatchError.toHuman();518 }519 } else {520 this.logger.log(result, this.logger.level.ERROR);521 }522 }523524 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);525 unsub();526 reject({status, moduleError, result});527 }528 });529 } catch (e) {530 this.logger.log(e, this.logger.level.ERROR);531 reject(e);532 }533 });534 }535536 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {537 const api = this.getApi();538 const signingInfo = await api.derive.tx.signingInfo(signer.address);539540 // We need to sign the tx because541 // unsigned transactions does not have an inclusion fee542 tx.sign(signer, {543 blockHash: api.genesisHash,544 genesisHash: api.genesisHash,545 runtimeVersion: api.runtimeVersion,546 nonce: signingInfo.nonce,547 });548549 if (len === null) {550 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;551 } else {552 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;553 }554 }555556 constructApiCall(apiCall: string, params: any[]) {557 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);558 let call = this.getApi() as any;559 for(const part of apiCall.slice(4).split('.')) {560 call = call[part];561 }562 return call(...params);563 }564565 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {566 if(this.api === null) throw Error('API not initialized');567 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);568569 const startTime = (new Date()).getTime();570 let result: ITransactionResult;571 let events: IEvent[] = [];572 try {573 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;574 events = this.eventHelper.extractEvents(result.result.events);575 }576 catch(e) {577 if(!(e as object).hasOwnProperty('status')) throw e;578 result = e as ITransactionResult;579 }580581 const endTime = (new Date()).getTime();582583 const log = {584 executedAt: endTime,585 executionTime: endTime - startTime,586 type: this.chainLogType.EXTRINSIC,587 status: result.status,588 call: extrinsic,589 signer: this.getSignerAddress(sender),590 params,591 } as IUniqueHelperLog;592593 if(result.status !== this.transactionStatus.SUCCESS) {594 if (result.moduleError) log.moduleError = result.moduleError;595 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;596 }597 if(events.length > 0) log.events = events;598599 this.chainLog.push(log);600601 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {602 if (result.moduleError) throw Error(`${result.moduleError}`);603 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));604 }605 return result;606 }607608 async callRpc(rpc: string, params?: any[]) {609 if(typeof params === 'undefined') params = [];610 if(this.api === null) throw Error('API not initialized');611 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);612613 const startTime = (new Date()).getTime();614 let result;615 let error = null;616 const log = {617 type: this.chainLogType.RPC,618 call: rpc,619 params,620 } as IUniqueHelperLog;621622 try {623 result = await this.constructApiCall(rpc, params);624 }625 catch(e) {626 error = e;627 }628629 const endTime = (new Date()).getTime();630631 log.executedAt = endTime;632 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';633 log.executionTime = endTime - startTime;634635 this.chainLog.push(log);636637 if(error !== null) throw error;638639 return result;640 }641642 getSignerAddress(signer: IKeyringPair | string): string {643 if(typeof signer === 'string') return signer;644 return signer.address;645 }646647 fetchAllPalletNames(): string[] {648 if(this.api === null) throw Error('API not initialized');649 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());650 }651652 fetchMissingPalletNames(requiredPallets: string[]): string[] {653 const palletNames = this.fetchAllPalletNames();654 return requiredPallets.filter(p => !palletNames.includes(p));655 }656}657658659class HelperGroup<T extends ChainHelperBase> {660 helper: T;661662 constructor(uniqueHelper: T) {663 this.helper = uniqueHelper;664 }665}666667668class CollectionGroup extends HelperGroup<UniqueHelper> {669 /**670 * Get number of blocks when sponsored transaction is available.671 *672 * @param collectionId ID of collection673 * @param tokenId ID of token674 * @param addressObj address for which the sponsorship is checked675 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});676 * @returns number of blocks or null if sponsorship hasn't been set677 */678 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {679 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();680 }681682 /**683 * Get the number of created collections.684 *685 * @returns number of created collections686 */687 async getTotalCount(): Promise<number> {688 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();689 }690691 /**692 * Get information about the collection with additional data,693 * including the number of tokens it contains, its administrators,694 * the normalized address of the collection's owner, and decoded name and description.695 *696 * @param collectionId ID of collection697 * @example await getData(2)698 * @returns collection information object699 */700 async getData(collectionId: number): Promise<{701 id: number;702 name: string;703 description: string;704 tokensCount: number;705 admins: CrossAccountId[];706 normalizedOwner: TSubstrateAccount;707 raw: any708 } | null> {709 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);710 const humanCollection = collection.toHuman(), collectionData = {711 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],712 raw: humanCollection,713 } as any, jsonCollection = collection.toJSON();714 if (humanCollection === null) return null;715 collectionData.raw.limits = jsonCollection.limits;716 collectionData.raw.permissions = jsonCollection.permissions;717 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);718 for (const key of ['name', 'description']) {719 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);720 }721722 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))723 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)724 : 0;725 collectionData.admins = await this.getAdmins(collectionId);726727 return collectionData;728 }729730 /**731 * Get the addresses of the collection's administrators, optionally normalized.732 *733 * @param collectionId ID of collection734 * @param normalize whether to normalize the addresses to the default ss58 format735 * @example await getAdmins(1)736 * @returns array of administrators737 */738 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {739 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();740741 return normalize742 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())743 : admins;744 }745746 /**747 * Get the addresses added to the collection allow-list, optionally normalized.748 * @param collectionId ID of collection749 * @param normalize whether to normalize the addresses to the default ss58 format750 * @example await getAllowList(1)751 * @returns array of allow-listed addresses752 */753 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {754 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();755 return normalize756 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())757 : allowListed;758 }759760 /**761 * Get the effective limits of the collection instead of null for default values762 *763 * @param collectionId ID of collection764 * @example await getEffectiveLimits(2)765 * @returns object of collection limits766 */767 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {768 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();769 }770771 /**772 * Burns the collection if the signer has sufficient permissions and collection is empty.773 *774 * @param signer keyring of signer775 * @param collectionId ID of collection776 * @example await helper.collection.burn(aliceKeyring, 3);777 * @returns ```true``` if extrinsic success, otherwise ```false```778 */779 async burn(signer: TSigner, collectionId: number): Promise<boolean> {780 const result = await this.helper.executeExtrinsic(781 signer,782 'api.tx.unique.destroyCollection', [collectionId],783 true,784 );785786 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');787 }788789 /**790 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.791 *792 * @param signer keyring of signer793 * @param collectionId ID of collection794 * @param sponsorAddress Sponsor substrate address795 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")796 * @returns ```true``` if extrinsic success, otherwise ```false```797 */798 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {799 const result = await this.helper.executeExtrinsic(800 signer,801 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],802 true,803 );804805 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');806 }807808 /**809 * Confirms consent to sponsor the collection on behalf of the signer.810 *811 * @param signer keyring of signer812 * @param collectionId ID of collection813 * @example confirmSponsorship(aliceKeyring, 10)814 * @returns ```true``` if extrinsic success, otherwise ```false```815 */816 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {817 const result = await this.helper.executeExtrinsic(818 signer,819 'api.tx.unique.confirmSponsorship', [collectionId],820 true,821 );822823 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');824 }825826 /**827 * Removes the sponsor of a collection, regardless if it consented or not.828 *829 * @param signer keyring of signer830 * @param collectionId ID of collection831 * @example removeSponsor(aliceKeyring, 10)832 * @returns ```true``` if extrinsic success, otherwise ```false```833 */834 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {835 const result = await this.helper.executeExtrinsic(836 signer,837 'api.tx.unique.removeCollectionSponsor', [collectionId],838 true,839 );840841 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');842 }843844 /**845 * Sets the limits of the collection. At least one limit must be specified for a correct call.846 *847 * @param signer keyring of signer848 * @param collectionId ID of collection849 * @param limits collection limits object850 * @example851 * await setLimits(852 * aliceKeyring,853 * 10,854 * {855 * sponsorTransferTimeout: 0,856 * ownerCanDestroy: false857 * }858 * )859 * @returns ```true``` if extrinsic success, otherwise ```false```860 */861 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {862 const result = await this.helper.executeExtrinsic(863 signer,864 'api.tx.unique.setCollectionLimits', [collectionId, limits],865 true,866 );867868 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');869 }870871 /**872 * Changes the owner of the collection to the new Substrate address.873 *874 * @param signer keyring of signer875 * @param collectionId ID of collection876 * @param ownerAddress substrate address of new owner877 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")878 * @returns ```true``` if extrinsic success, otherwise ```false```879 */880 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {881 const result = await this.helper.executeExtrinsic(882 signer,883 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],884 true,885 );886887 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');888 }889890 /**891 * Adds a collection administrator.892 *893 * @param signer keyring of signer894 * @param collectionId ID of collection895 * @param adminAddressObj Administrator address (substrate or ethereum)896 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})897 * @returns ```true``` if extrinsic success, otherwise ```false```898 */899 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {900 const result = await this.helper.executeExtrinsic(901 signer,902 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],903 true,904 );905906 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');907 }908909 /**910 * Removes a collection administrator.911 *912 * @param signer keyring of signer913 * @param collectionId ID of collection914 * @param adminAddressObj Administrator address (substrate or ethereum)915 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})916 * @returns ```true``` if extrinsic success, otherwise ```false```917 */918 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {919 const result = await this.helper.executeExtrinsic(920 signer,921 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],922 true,923 );924925 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');926 }927928 /**929 * Check if user is in allow list.930 * 931 * @param collectionId ID of collection932 * @param user Account to check933 * @example await getAdmins(1)934 * @returns is user in allow list935 */936 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {937 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();938 }939940 /**941 * Adds an address to allow list942 * @param signer keyring of signer943 * @param collectionId ID of collection944 * @param addressObj address to add to the allow list945 * @returns ```true``` if extrinsic success, otherwise ```false```946 */947 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {948 const result = await this.helper.executeExtrinsic(949 signer,950 'api.tx.unique.addToAllowList', [collectionId, addressObj],951 true,952 );953954 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');955 }956957 /**958 * Removes an address from allow list959 *960 * @param signer keyring of signer961 * @param collectionId ID of collection962 * @param addressObj address to remove from the allow list963 * @returns ```true``` if extrinsic success, otherwise ```false```964 */965 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {966 const result = await this.helper.executeExtrinsic(967 signer,968 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],969 true,970 );971972 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');973 }974975 /**976 * Sets onchain permissions for selected collection.977 *978 * @param signer keyring of signer979 * @param collectionId ID of collection980 * @param permissions collection permissions object981 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});982 * @returns ```true``` if extrinsic success, otherwise ```false```983 */984 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {985 const result = await this.helper.executeExtrinsic(986 signer,987 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],988 true,989 );990991 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');992 }993994 /**995 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.996 *997 * @param signer keyring of signer998 * @param collectionId ID of collection999 * @param permissions nesting permissions object1000 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1001 * @returns ```true``` if extrinsic success, otherwise ```false```1002 */1003 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1004 return await this.setPermissions(signer, collectionId, {nesting: permissions});1005 }10061007 /**1008 * Disables nesting for selected collection.1009 *1010 * @param signer keyring of signer1011 * @param collectionId ID of collection1012 * @example disableNesting(aliceKeyring, 10);1013 * @returns ```true``` if extrinsic success, otherwise ```false```1014 */1015 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1016 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1017 }10181019 /**1020 * Sets onchain properties to the collection.1021 *1022 * @param signer keyring of signer1023 * @param collectionId ID of collection1024 * @param properties array of property objects1025 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1026 * @returns ```true``` if extrinsic success, otherwise ```false```1027 */1028 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1029 const result = await this.helper.executeExtrinsic(1030 signer,1031 'api.tx.unique.setCollectionProperties', [collectionId, properties],1032 true,1033 );10341035 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1036 }10371038 /**1039 * Get collection properties.1040 * 1041 * @param collectionId ID of collection1042 * @param propertyKeys optionally filter the returned properties to only these keys1043 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1044 * @returns array of key-value pairs1045 */1046 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1047 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1048 }10491050 async getCollectionOptions(collectionId: number) {1051 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1052 }10531054 /**1055 * Deletes onchain properties from the collection.1056 *1057 * @param signer keyring of signer1058 * @param collectionId ID of collection1059 * @param propertyKeys array of property keys to delete1060 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1061 * @returns ```true``` if extrinsic success, otherwise ```false```1062 */1063 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1064 const result = await this.helper.executeExtrinsic(1065 signer,1066 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1067 true,1068 );10691070 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1071 }10721073 /**1074 * Changes the owner of the token.1075 *1076 * @param signer keyring of signer1077 * @param collectionId ID of collection1078 * @param tokenId ID of token1079 * @param addressObj address of a new owner1080 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1081 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1082 * @returns true if the token success, otherwise false1083 */1084 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1085 const result = await this.helper.executeExtrinsic(1086 signer,1087 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1088 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1089 );10901091 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1092 }10931094 /**1095 *1096 * Change ownership of a token(s) on behalf of the owner.1097 *1098 * @param signer keyring of signer1099 * @param collectionId ID of collection1100 * @param tokenId ID of token1101 * @param fromAddressObj address on behalf of which the token will be sent1102 * @param toAddressObj new token owner1103 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1104 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1105 * @returns true if the token success, otherwise false1106 */1107 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1108 const result = await this.helper.executeExtrinsic(1109 signer,1110 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1111 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1112 );1113 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1114 }11151116 /**1117 *1118 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1119 *1120 * @param signer keyring of signer1121 * @param collectionId ID of collection1122 * @param tokenId ID of token1123 * @param amount amount of tokens to be burned. For NFT must be set to 1n1124 * @example burnToken(aliceKeyring, 10, 5);1125 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1126 */1127 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1128 const burnResult = await this.helper.executeExtrinsic(1129 signer,1130 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1131 true, // `Unable to burn token for ${label}`,1132 );1133 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1134 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1135 return burnedTokens.success;1136 }11371138 /**1139 * Destroys a concrete instance of NFT on behalf of the owner1140 *1141 * @param signer keyring of signer1142 * @param collectionId ID of collection1143 * @param tokenId ID of token1144 * @param fromAddressObj address on behalf of which the token will be burnt1145 * @param amount amount of tokens to be burned. For NFT must be set to 1n1146 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1147 * @returns ```true``` if extrinsic success, otherwise ```false```1148 */1149 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1150 const burnResult = await this.helper.executeExtrinsic(1151 signer,1152 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1153 true, // `Unable to burn token from for ${label}`,1154 );1155 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1156 return burnedTokens.success && burnedTokens.tokens.length > 0;1157 }11581159 /**1160 * Set, change, or remove approved address to transfer the ownership of the NFT.1161 *1162 * @param signer keyring of signer1163 * @param collectionId ID of collection1164 * @param tokenId ID of token1165 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1166 * @param amount amount of token to be approved. For NFT must be set to 1n1167 * @returns ```true``` if extrinsic success, otherwise ```false```1168 */1169 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1170 const approveResult = await this.helper.executeExtrinsic(1171 signer,1172 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1173 true, // `Unable to approve token for ${label}`,1174 );11751176 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1177 }11781179 /**1180 * Get the amount of token pieces approved to transfer or burn. Normally 0.1181 *1182 * @param collectionId ID of collection1183 * @param tokenId ID of token1184 * @param toAccountObj address which is approved to use token pieces1185 * @param fromAccountObj address which may have allowed the use of its owned tokens1186 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1187 * @returns number of approved to transfer pieces1188 */1189 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1190 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1191 }11921193 /**1194 * Get the last created token ID in a collection1195 *1196 * @param collectionId ID of collection1197 * @example getLastTokenId(10);1198 * @returns id of the last created token1199 */1200 async getLastTokenId(collectionId: number): Promise<number> {1201 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1202 }12031204 /**1205 * Check if token exists1206 *1207 * @param collectionId ID of collection1208 * @param tokenId ID of token1209 * @example doesTokenExist(10, 20);1210 * @returns true if the token exists, otherwise false1211 */1212 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1213 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1214 }1215}12161217class NFTnRFT extends CollectionGroup {1218 /**1219 * Get tokens owned by account1220 *1221 * @param collectionId ID of collection1222 * @param addressObj tokens owner1223 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1224 * @returns array of token ids owned by account1225 */1226 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1227 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1228 }12291230 /**1231 * Get token data1232 *1233 * @param collectionId ID of collection1234 * @param tokenId ID of token1235 * @param propertyKeys optionally filter the token properties to only these keys1236 * @param blockHashAt optionally query the data at some block with this hash1237 * @example getToken(10, 5);1238 * @returns human readable token data1239 */1240 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1241 properties: IProperty[];1242 owner: CrossAccountId;1243 normalizedOwner: CrossAccountId;1244 }| null> {1245 let tokenData;1246 if(typeof blockHashAt === 'undefined') {1247 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1248 }1249 else {1250 if(propertyKeys.length == 0) {1251 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1252 if(!collection) return null;1253 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1254 }1255 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1256 }1257 tokenData = tokenData.toHuman();1258 if (tokenData === null || tokenData.owner === null) return null;1259 const owner = {} as any;1260 for (const key of Object.keys(tokenData.owner)) {1261 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1262 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1263 : tokenData.owner[key];1264 }1265 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1266 return tokenData;1267 }12681269 /**1270 * Set permissions to change token properties1271 *1272 * @param signer keyring of signer1273 * @param collectionId ID of collection1274 * @param permissions permissions to change a property by the collection admin or token owner1275 * @example setTokenPropertyPermissions(1276 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1277 * )1278 * @returns true if extrinsic success otherwise false1279 */1280 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1281 const result = await this.helper.executeExtrinsic(1282 signer,1283 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1284 true,1285 );12861287 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1288 }12891290 /**1291 * Get token property permissions.1292 * 1293 * @param collectionId ID of collection1294 * @param propertyKeys optionally filter the returned property permissions to only these keys1295 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1296 * @returns array of key-permission pairs1297 */1298 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1299 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1300 }13011302 /**1303 * Set token properties1304 *1305 * @param signer keyring of signer1306 * @param collectionId ID of collection1307 * @param tokenId ID of token1308 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1309 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1310 * @returns ```true``` if extrinsic success, otherwise ```false```1311 */1312 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1313 const result = await this.helper.executeExtrinsic(1314 signer,1315 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1316 true,1317 );13181319 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1320 }13211322 /**1323 * Get properties, metadata assigned to a token.1324 * 1325 * @param collectionId ID of collection1326 * @param tokenId ID of token1327 * @param propertyKeys optionally filter the returned properties to only these keys1328 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1329 * @returns array of key-value pairs1330 */1331 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1332 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1333 }13341335 /**1336 * Delete the provided properties of a token1337 * @param signer keyring of signer1338 * @param collectionId ID of collection1339 * @param tokenId ID of token1340 * @param propertyKeys property keys to be deleted1341 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1342 * @returns ```true``` if extrinsic success, otherwise ```false```1343 */1344 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1345 const result = await this.helper.executeExtrinsic(1346 signer,1347 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1348 true,1349 );13501351 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1352 }13531354 /**1355 * Mint new collection1356 *1357 * @param signer keyring of signer1358 * @param collectionOptions basic collection options and properties1359 * @param mode NFT or RFT type of a collection1360 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1361 * @returns object of the created collection1362 */1363 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1364 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1365 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1366 for (const key of ['name', 'description', 'tokenPrefix']) {1367 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);1368 }1369 const creationResult = await this.helper.executeExtrinsic(1370 signer,1371 'api.tx.unique.createCollectionEx', [collectionOptions],1372 true, // errorLabel,1373 );1374 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1375 }13761377 getCollectionObject(_collectionId: number): any {1378 return null;1379 }13801381 getTokenObject(_collectionId: number, _tokenId: number): any {1382 return null;1383 }1384}138513861387class NFTGroup extends NFTnRFT {1388 /**1389 * Get collection object1390 * @param collectionId ID of collection1391 * @example getCollectionObject(2);1392 * @returns instance of UniqueNFTCollection1393 */1394 getCollectionObject(collectionId: number): UniqueNFTCollection {1395 return new UniqueNFTCollection(collectionId, this.helper);1396 }13971398 /**1399 * Get token object1400 * @param collectionId ID of collection1401 * @param tokenId ID of token1402 * @example getTokenObject(10, 5);1403 * @returns instance of UniqueNFTToken1404 */1405 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1406 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1407 }14081409 /**1410 * Get token's owner1411 * @param collectionId ID of collection1412 * @param tokenId ID of token1413 * @param blockHashAt optionally query the data at the block with this hash1414 * @example getTokenOwner(10, 5);1415 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1416 */1417 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1418 let owner;1419 if (typeof blockHashAt === 'undefined') {1420 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1421 } else {1422 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1423 }1424 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1425 }14261427 /**1428 * Is token approved to transfer1429 * @param collectionId ID of collection1430 * @param tokenId ID of token1431 * @param toAccountObj address to be approved1432 * @returns ```true``` if extrinsic success, otherwise ```false```1433 */1434 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1435 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1436 }14371438 /**1439 * Changes the owner of the token.1440 *1441 * @param signer keyring of signer1442 * @param collectionId ID of collection1443 * @param tokenId ID of token1444 * @param addressObj address of a new owner1445 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1446 * @returns ```true``` if extrinsic success, otherwise ```false```1447 */1448 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1449 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1450 }14511452 /**1453 *1454 * Change ownership of a NFT on behalf of the owner.1455 *1456 * @param signer keyring of signer1457 * @param collectionId ID of collection1458 * @param tokenId ID of token1459 * @param fromAddressObj address on behalf of which the token will be sent1460 * @param toAddressObj new token owner1461 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1462 * @returns ```true``` if extrinsic success, otherwise ```false```1463 */1464 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1465 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1466 }14671468 /**1469 * Recursively find the address that owns the token1470 * @param collectionId ID of collection1471 * @param tokenId ID of token1472 * @param blockHashAt1473 * @example getTokenTopmostOwner(10, 5);1474 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1475 */1476 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1477 let owner;1478 if (typeof blockHashAt === 'undefined') {1479 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1480 } else {1481 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1482 }14831484 if (owner === null) return null;14851486 return owner.toHuman();1487 }14881489 /**1490 * Get tokens nested in the provided token1491 * @param collectionId ID of collection1492 * @param tokenId ID of token1493 * @param blockHashAt optionally query the data at the block with this hash1494 * @example getTokenChildren(10, 5);1495 * @returns tokens whose depth of nesting is <= 51496 */1497 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1498 let children;1499 if(typeof blockHashAt === 'undefined') {1500 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1501 } else {1502 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1503 }15041505 return children.toJSON().map((x: any) => {1506 return {collectionId: x.collection, tokenId: x.token};1507 });1508 }15091510 /**1511 * Nest one token into another1512 * @param signer keyring of signer1513 * @param tokenObj token to be nested1514 * @param rootTokenObj token to be parent1515 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1516 * @returns ```true``` if extrinsic success, otherwise ```false```1517 */1518 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1519 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1520 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1521 if(!result) {1522 throw Error('Unable to nest token!');1523 }1524 return result;1525 }15261527 /**1528 * Remove token from nested state1529 * @param signer keyring of signer1530 * @param tokenObj token to unnest1531 * @param rootTokenObj parent of a token1532 * @param toAddressObj address of a new token owner1533 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1534 * @returns ```true``` if extrinsic success, otherwise ```false```1535 */1536 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1537 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1538 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1539 if(!result) {1540 throw Error('Unable to unnest token!');1541 }1542 return result;1543 }15441545 /**1546 * Mint new collection1547 * @param signer keyring of signer1548 * @param collectionOptions Collection options1549 * @example1550 * mintCollection(aliceKeyring, {1551 * name: 'New',1552 * description: 'New collection',1553 * tokenPrefix: 'NEW',1554 * })1555 * @returns object of the created collection1556 */1557 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1558 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1559 }15601561 /**1562 * Mint new token1563 * @param signer keyring of signer1564 * @param data token data1565 * @returns created token object1566 */1567 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1568 const creationResult = await this.helper.executeExtrinsic(1569 signer,1570 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1571 nft: {1572 properties: data.properties,1573 },1574 }],1575 true,1576 );1577 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1578 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1579 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1580 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1581 }15821583 /**1584 * Mint multiple NFT tokens1585 * @param signer keyring of signer1586 * @param collectionId ID of collection1587 * @param tokens array of tokens with owner and properties1588 * @example1589 * mintMultipleTokens(aliceKeyring, 10, [{1590 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1591 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1592 * },{1593 * owner: {Ethereum: "0x9F0583DbB855d..."},1594 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1595 * }]);1596 * @returns ```true``` if extrinsic success, otherwise ```false```1597 */1598 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1599 const creationResult = await this.helper.executeExtrinsic(1600 signer,1601 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1602 true,1603 );1604 const collection = this.getCollectionObject(collectionId);1605 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1606 }16071608 /**1609 * Mint multiple NFT tokens with one owner1610 * @param signer keyring of signer1611 * @param collectionId ID of collection1612 * @param owner tokens owner1613 * @param tokens array of tokens with owner and properties1614 * @example1615 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1616 * properties: [{1617 * key: "gender",1618 * value: "female",1619 * },{1620 * key: "age",1621 * value: "33",1622 * }],1623 * }]);1624 * @returns array of newly created tokens1625 */1626 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1627 const rawTokens = [];1628 for (const token of tokens) {1629 const raw = {NFT: {properties: token.properties}};1630 rawTokens.push(raw);1631 }1632 const creationResult = await this.helper.executeExtrinsic(1633 signer,1634 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1635 true,1636 );1637 const collection = this.getCollectionObject(collectionId);1638 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1639 }16401641 /**1642 * Set, change, or remove approved address to transfer the ownership of the NFT.1643 *1644 * @param signer keyring of signer1645 * @param collectionId ID of collection1646 * @param tokenId ID of token1647 * @param toAddressObj address to approve1648 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1649 * @returns ```true``` if extrinsic success, otherwise ```false```1650 */1651 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1652 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1653 }1654}165516561657class RFTGroup extends NFTnRFT {1658 /**1659 * Get collection object1660 * @param collectionId ID of collection1661 * @example getCollectionObject(2);1662 * @returns instance of UniqueRFTCollection1663 */1664 getCollectionObject(collectionId: number): UniqueRFTCollection {1665 return new UniqueRFTCollection(collectionId, this.helper);1666 }16671668 /**1669 * Get token object1670 * @param collectionId ID of collection1671 * @param tokenId ID of token1672 * @example getTokenObject(10, 5);1673 * @returns instance of UniqueNFTToken1674 */1675 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1676 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1677 }16781679 /**1680 * Get top 10 token owners with the largest number of pieces1681 * @param collectionId ID of collection1682 * @param tokenId ID of token1683 * @example getTokenTop10Owners(10, 5);1684 * @returns array of top 10 owners1685 */1686 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1687 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1688 }16891690 /**1691 * Get number of pieces owned by address1692 * @param collectionId ID of collection1693 * @param tokenId ID of token1694 * @param addressObj address token owner1695 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1696 * @returns number of pieces ownerd by address1697 */1698 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1699 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1700 }17011702 /**1703 * Transfer pieces of token to another address1704 * @param signer keyring of signer1705 * @param collectionId ID of collection1706 * @param tokenId ID of token1707 * @param addressObj address of a new owner1708 * @param amount number of pieces to be transfered1709 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1710 * @returns ```true``` if extrinsic success, otherwise ```false```1711 */1712 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1713 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1714 }17151716 /**1717 * Change ownership of some pieces of RFT on behalf of the owner.1718 * @param signer keyring of signer1719 * @param collectionId ID of collection1720 * @param tokenId ID of token1721 * @param fromAddressObj address on behalf of which the token will be sent1722 * @param toAddressObj new token owner1723 * @param amount number of pieces to be transfered1724 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1725 * @returns ```true``` if extrinsic success, otherwise ```false```1726 */1727 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1728 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1729 }17301731 /**1732 * Mint new collection1733 * @param signer keyring of signer1734 * @param collectionOptions Collection options1735 * @example1736 * mintCollection(aliceKeyring, {1737 * name: 'New',1738 * description: 'New collection',1739 * tokenPrefix: 'NEW',1740 * })1741 * @returns object of the created collection1742 */1743 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1744 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1745 }17461747 /**1748 * Mint new token1749 * @param signer keyring of signer1750 * @param data token data1751 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1752 * @returns created token object1753 */1754 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1755 const creationResult = await this.helper.executeExtrinsic(1756 signer,1757 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1758 refungible: {1759 pieces: data.pieces,1760 properties: data.properties,1761 },1762 }],1763 true,1764 );1765 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1766 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1767 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1768 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1769 }17701771 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1772 throw Error('Not implemented');1773 const creationResult = await this.helper.executeExtrinsic(1774 signer,1775 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1776 true, // `Unable to mint RFT tokens for ${label}`,1777 );1778 const collection = this.getCollectionObject(collectionId);1779 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1780 }17811782 /**1783 * Mint multiple RFT tokens with one owner1784 * @param signer keyring of signer1785 * @param collectionId ID of collection1786 * @param owner tokens owner1787 * @param tokens array of tokens with properties and pieces1788 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1789 * @returns array of newly created RFT tokens1790 */1791 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1792 const rawTokens = [];1793 for (const token of tokens) {1794 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1795 rawTokens.push(raw);1796 }1797 const creationResult = await this.helper.executeExtrinsic(1798 signer,1799 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1800 true,1801 );1802 const collection = this.getCollectionObject(collectionId);1803 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1804 }18051806 /**1807 * Destroys a concrete instance of RFT.1808 * @param signer keyring of signer1809 * @param collectionId ID of collection1810 * @param tokenId ID of token1811 * @param amount number of pieces to be burnt1812 * @example burnToken(aliceKeyring, 10, 5);1813 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1814 */1815 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1816 return await super.burnToken(signer, collectionId, tokenId, amount);1817 }18181819 /**1820 * Destroys a concrete instance of RFT on behalf of the owner.1821 * @param signer keyring of signer1822 * @param collectionId ID of collection1823 * @param tokenId ID of token1824 * @param fromAddressObj address on behalf of which the token will be burnt1825 * @param amount number of pieces to be burnt1826 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1827 * @returns ```true``` if extrinsic success, otherwise ```false```1828 */1829 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1830 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1831 }18321833 /**1834 * Set, change, or remove approved address to transfer the ownership of the RFT.1835 *1836 * @param signer keyring of signer1837 * @param collectionId ID of collection1838 * @param tokenId ID of token1839 * @param toAddressObj address to approve1840 * @param amount number of pieces to be approved1841 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1842 * @returns true if the token success, otherwise false1843 */1844 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1845 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1846 }18471848 /**1849 * Get total number of pieces1850 * @param collectionId ID of collection1851 * @param tokenId ID of token1852 * @example getTokenTotalPieces(10, 5);1853 * @returns number of pieces1854 */1855 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1856 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1857 }18581859 /**1860 * Change number of token pieces. Signer must be the owner of all token pieces.1861 * @param signer keyring of signer1862 * @param collectionId ID of collection1863 * @param tokenId ID of token1864 * @param amount new number of pieces1865 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1866 * @returns true if the repartion was success, otherwise false1867 */1868 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1869 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1870 const repartitionResult = await this.helper.executeExtrinsic(1871 signer,1872 'api.tx.unique.repartition', [collectionId, tokenId, amount],1873 true,1874 );1875 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1876 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1877 }1878}187918801881class FTGroup extends CollectionGroup {1882 /**1883 * Get collection object1884 * @param collectionId ID of collection1885 * @example getCollectionObject(2);1886 * @returns instance of UniqueFTCollection1887 */1888 getCollectionObject(collectionId: number): UniqueFTCollection {1889 return new UniqueFTCollection(collectionId, this.helper);1890 }18911892 /**1893 * Mint new fungible collection1894 * @param signer keyring of signer1895 * @param collectionOptions Collection options1896 * @param decimalPoints number of token decimals1897 * @example1898 * mintCollection(aliceKeyring, {1899 * name: 'New',1900 * description: 'New collection',1901 * tokenPrefix: 'NEW',1902 * }, 18)1903 * @returns newly created fungible collection1904 */1905 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1906 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1907 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1908 collectionOptions.mode = {fungible: decimalPoints};1909 for (const key of ['name', 'description', 'tokenPrefix']) {1910 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);1911 }1912 const creationResult = await this.helper.executeExtrinsic(1913 signer,1914 'api.tx.unique.createCollectionEx', [collectionOptions],1915 true,1916 );1917 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1918 }19191920 /**1921 * Mint tokens1922 * @param signer keyring of signer1923 * @param collectionId ID of collection1924 * @param owner address owner of new tokens1925 * @param amount amount of tokens to be meanted1926 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1927 * @returns ```true``` if extrinsic success, otherwise ```false```1928 */1929 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1930 const creationResult = await this.helper.executeExtrinsic(1931 signer,1932 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1933 fungible: {1934 value: amount,1935 },1936 }],1937 true, // `Unable to mint fungible tokens for ${label}`,1938 );1939 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1940 }19411942 /**1943 * Mint multiple Fungible tokens with one owner1944 * @param signer keyring of signer1945 * @param collectionId ID of collection1946 * @param owner tokens owner1947 * @param tokens array of tokens with properties and pieces1948 * @returns ```true``` if extrinsic success, otherwise ```false```1949 */1950 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1951 const rawTokens = [];1952 for (const token of tokens) {1953 const raw = {Fungible: {Value: token.value}};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 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1962 }19631964 /**1965 * Get the top 10 owners with the largest balance for the Fungible collection1966 * @param collectionId ID of collection1967 * @example getTop10Owners(10);1968 * @returns array of ```ICrossAccountId```1969 */1970 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1971 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1972 }19731974 /**1975 * Get account balance1976 * @param collectionId ID of collection1977 * @param addressObj address of owner1978 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1979 * @returns amount of fungible tokens owned by address1980 */1981 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1982 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1983 }19841985 /**1986 * Transfer tokens to address1987 * @param signer keyring of signer1988 * @param collectionId ID of collection1989 * @param toAddressObj address recipient1990 * @param amount amount of tokens to be sent1991 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1992 * @returns ```true``` if extrinsic success, otherwise ```false```1993 */1994 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1995 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1996 }19971998 /**1999 * Transfer some tokens on behalf of the owner.2000 * @param signer keyring of signer2001 * @param collectionId ID of collection2002 * @param fromAddressObj address on behalf of which tokens will be sent2003 * @param toAddressObj address where token to be sent2004 * @param amount number of tokens to be sent2005 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2006 * @returns ```true``` if extrinsic success, otherwise ```false```2007 */2008 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2009 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2010 }20112012 /**2013 * Destroy some amount of tokens2014 * @param signer keyring of signer2015 * @param collectionId ID of collection2016 * @param amount amount of tokens to be destroyed2017 * @example burnTokens(aliceKeyring, 10, 1000n);2018 * @returns ```true``` if extrinsic success, otherwise ```false```2019 */2020 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2021 return await super.burnToken(signer, collectionId, 0, amount);2022 }20232024 /**2025 * Burn some tokens on behalf of the owner.2026 * @param signer keyring of signer2027 * @param collectionId ID of collection2028 * @param fromAddressObj address on behalf of which tokens will be burnt2029 * @param amount amount of tokens to be burnt2030 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2031 * @returns ```true``` if extrinsic success, otherwise ```false```2032 */2033 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2034 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2035 }20362037 /**2038 * Get total collection supply2039 * @param collectionId2040 * @returns2041 */2042 async getTotalPieces(collectionId: number): Promise<bigint> {2043 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2044 }20452046 /**2047 * Set, change, or remove approved address to transfer tokens.2048 *2049 * @param signer keyring of signer2050 * @param collectionId ID of collection2051 * @param toAddressObj address to be approved2052 * @param amount amount of tokens to be approved2053 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2054 * @returns ```true``` if extrinsic success, otherwise ```false```2055 */2056 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2057 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2058 }20592060 /**2061 * Get amount of fungible tokens approved to transfer2062 * @param collectionId ID of collection2063 * @param fromAddressObj owner of tokens2064 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2065 * @returns number of tokens approved for the transfer2066 */2067 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2068 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2069 }2070}207120722073class ChainGroup extends HelperGroup<ChainHelperBase> {2074 /**2075 * Get system properties of a chain2076 * @example getChainProperties();2077 * @returns ss58Format, token decimals, and token symbol2078 */2079 getChainProperties(): IChainProperties {2080 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2081 return {2082 ss58Format: properties.ss58Format.toJSON(),2083 tokenDecimals: properties.tokenDecimals.toJSON(),2084 tokenSymbol: properties.tokenSymbol.toJSON(),2085 };2086 }20872088 /**2089 * Get chain header2090 * @example getLatestBlockNumber();2091 * @returns the number of the last block2092 */2093 async getLatestBlockNumber(): Promise<number> {2094 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2095 }20962097 /**2098 * Get block hash by block number2099 * @param blockNumber number of block2100 * @example getBlockHashByNumber(12345);2101 * @returns hash of a block2102 */2103 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2104 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2105 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2106 return blockHash;2107 }21082109 // TODO add docs2110 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2111 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2112 if (!blockHash) return null;2113 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2114 }21152116 /**2117 * Get account nonce2118 * @param address substrate address2119 * @example getNonce("5GrwvaEF5zXb26Fz...");2120 * @returns number, account's nonce2121 */2122 async getNonce(address: TSubstrateAccount): Promise<number> {2123 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2124 }2125}21262127class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2128 /**2129 * Get substrate address balance2130 * @param address substrate address2131 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2132 * @returns amount of tokens on address2133 */2134 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2135 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2136 }21372138 /**2139 * Transfer tokens to substrate address2140 * @param signer keyring of signer2141 * @param address substrate address of a recipient2142 * @param amount amount of tokens to be transfered2143 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2144 * @returns ```true``` if extrinsic success, otherwise ```false```2145 */2146 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2147 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}`*/);21482149 let transfer = {from: null, to: null, amount: 0n} as any;2150 result.result.events.forEach(({event: {data, method, section}}) => {2151 if ((section === 'balances') && (method === 'Transfer')) {2152 transfer = {2153 from: this.helper.address.normalizeSubstrate(data[0]),2154 to: this.helper.address.normalizeSubstrate(data[1]),2155 amount: BigInt(data[2]),2156 };2157 }2158 });2159 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2160 && this.helper.address.normalizeSubstrate(address) === transfer.to 2161 && BigInt(amount) === transfer.amount;2162 return isSuccess;2163 }21642165 /**2166 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2167 * @param address substrate address2168 * @returns2169 */2170 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2171 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2172 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2173 }2174}21752176class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2177 /**2178 * Get ethereum address balance2179 * @param address ethereum address2180 * @example getEthereum("0x9F0583DbB855d...")2181 * @returns amount of tokens on address2182 */2183 async getEthereum(address: TEthereumAccount): Promise<bigint> {2184 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2185 }21862187 /**2188 * Transfer tokens to address2189 * @param signer keyring of signer2190 * @param address Ethereum address of a recipient2191 * @param amount amount of tokens to be transfered2192 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2193 * @returns ```true``` if extrinsic success, otherwise ```false```2194 */2195 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2196 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);21972198 let transfer = {from: null, to: null, amount: 0n} as any;2199 result.result.events.forEach(({event: {data, method, section}}) => {2200 if ((section === 'balances') && (method === 'Transfer')) {2201 transfer = {2202 from: data[0].toString(),2203 to: data[1].toString(),2204 amount: BigInt(data[2]),2205 };2206 }2207 });2208 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from 2209 && address === transfer.to 2210 && BigInt(amount) === transfer.amount;2211 return isSuccess;2212 }2213}22142215class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2216 subBalanceGroup: SubstrateBalanceGroup<T>;2217 ethBalanceGroup: EthereumBalanceGroup<T>;22182219 constructor(helper: T) {2220 super(helper);2221 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2222 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2223 }22242225 getCollectionCreationPrice(): bigint {2226 return 2n * this.getOneTokenNominal();2227 }2228 /**2229 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2230 * @example getOneTokenNominal()2231 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2232 */2233 getOneTokenNominal(): bigint {2234 const chainProperties = this.helper.chain.getChainProperties();2235 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2236 }22372238 /**2239 * Get substrate address balance2240 * @param address substrate address2241 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2242 * @returns amount of tokens on address2243 */2244 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2245 return this.subBalanceGroup.getSubstrate(address);2246 }22472248 /**2249 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2250 * @param address substrate address2251 * @returns2252 */2253 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2254 return this.subBalanceGroup.getSubstrateFull(address);2255 }22562257 /**2258 * Get ethereum address balance2259 * @param address ethereum address2260 * @example getEthereum("0x9F0583DbB855d...")2261 * @returns amount of tokens on address2262 */2263 async getEthereum(address: TEthereumAccount): Promise<bigint> {2264 return this.ethBalanceGroup.getEthereum(address);2265 }22662267 /**2268 * Transfer tokens to substrate address2269 * @param signer keyring of signer2270 * @param address substrate address of a recipient2271 * @param amount amount of tokens to be transfered2272 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2273 * @returns ```true``` if extrinsic success, otherwise ```false```2274 */2275 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2276 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2277 }22782279 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2280 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);22812282 let transfer = {from: null, to: null, amount: 0n} as any;2283 result.result.events.forEach(({event: {data, method, section}}) => {2284 if ((section === 'balances') && (method === 'Transfer')) {2285 transfer = {2286 from: this.helper.address.normalizeSubstrate(data[0]),2287 to: this.helper.address.normalizeSubstrate(data[1]),2288 amount: BigInt(data[2]),2289 };2290 }2291 });2292 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2293 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2294 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2295 return isSuccess;2296 }2297}22982299class AddressGroup extends HelperGroup<ChainHelperBase> {2300 /**2301 * Normalizes the address to the specified ss58 format, by default ```42```.2302 * @param address substrate address2303 * @param ss58Format format for address conversion, by default ```42```2304 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2305 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2306 */2307 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2308 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2309 }23102311 /**2312 * Get address in the connected chain format2313 * @param address substrate address2314 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2315 * @returns address in chain format2316 */2317 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2318 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2319 }23202321 /**2322 * Get substrate mirror of an ethereum address2323 * @param ethAddress ethereum address2324 * @param toChainFormat false for normalized account2325 * @example ethToSubstrate('0x9F0583DbB855d...')2326 * @returns substrate mirror of a provided ethereum address2327 */2328 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2329 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2330 }23312332 /**2333 * Get ethereum mirror of a substrate address2334 * @param subAddress substrate account2335 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2336 * @returns ethereum mirror of a provided substrate address2337 */2338 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2339 return CrossAccountId.translateSubToEth(subAddress);2340 }23412342 paraSiblingSovereignAccount(paraid: number) {2343 // We are getting a *sibling* parachain sovereign account,2344 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2345 const siblingPrefix = '0x7369626c';23462347 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2348 const suffix = '000000000000000000000000000000000000000000000000';23492350 return siblingPrefix + encodedParaId + suffix;2351 }2352}23532354class StakingGroup extends HelperGroup<UniqueHelper> {2355 /**2356 * Stake tokens for App Promotion2357 * @param signer keyring of signer2358 * @param amountToStake amount of tokens to stake2359 * @param label extra label for log2360 * @returns2361 */2362 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2363 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2364 const _stakeResult = await this.helper.executeExtrinsic(2365 signer, 'api.tx.appPromotion.stake',2366 [amountToStake], true,2367 );2368 // TODO extract info from stakeResult2369 return true;2370 }23712372 /**2373 * Unstake tokens for App Promotion2374 * @param signer keyring of signer2375 * @param amountToUnstake amount of tokens to unstake2376 * @param label extra label for log2377 * @returns block number where balances will be unlocked2378 */2379 async unstake(signer: TSigner, label?: string): Promise<number> {2380 if(typeof label === 'undefined') label = `${signer.address}`;2381 const _unstakeResult = await this.helper.executeExtrinsic(2382 signer, 'api.tx.appPromotion.unstake',2383 [], true,2384 );2385 // TODO extract block number fron events2386 return 1;2387 }23882389 /**2390 * Get total staked amount for address2391 * @param address substrate or ethereum address2392 * @returns total staked amount2393 */2394 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2395 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2396 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2397 }23982399 /**2400 * Get total staked per block2401 * @param address substrate or ethereum address2402 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2403 */2404 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2405 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2406 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2407 return { 2408 block: block.toBigInt(),2409 amount: amount.toBigInt(),2410 };2411 });2412 }24132414 /**2415 * Get total pending unstake amount for address2416 * @param address substrate or ethereum address2417 * @returns total pending unstake amount2418 */2419 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2420 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2421 }24222423 /**2424 * Get pending unstake amount per block for address2425 * @param address substrate or ethereum address2426 * @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 block2427 */2428 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2429 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2430 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2431 return {2432 block: block.toBigInt(),2433 amount: amount.toBigInt(),2434 };2435 });2436 return result;2437 }2438}24392440class SchedulerGroup extends HelperGroup<UniqueHelper> {2441 constructor(helper: UniqueHelper) {2442 super(helper);2443 }24442445 async cancelScheduled(signer: TSigner, scheduledId: string) {2446 return this.helper.executeExtrinsic(2447 signer,2448 'api.tx.scheduler.cancelNamed',2449 [scheduledId],2450 true,2451 );2452 }24532454 async changePriority(signer: TSigner, scheduledId: string, priority: number) {2455 return this.helper.executeExtrinsic(2456 signer,2457 'api.tx.scheduler.changeNamedPriority',2458 [scheduledId, priority],2459 true,2460 );2461 }24622463 scheduleAt<T extends UniqueHelper>(2464 scheduledId: string,2465 executionBlockNumber: number,2466 options: ISchedulerOptions = {},2467 ) {2468 return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2469 }24702471 scheduleAfter<T extends UniqueHelper>(2472 scheduledId: string,2473 blocksBeforeExecution: number,2474 options: ISchedulerOptions = {},2475 ) {2476 return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2477 }24782479 schedule<T extends UniqueHelper>(2480 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2481 scheduledId: string,2482 blocksNum: number,2483 options: ISchedulerOptions = {},2484 ) {2485 // eslint-disable-next-line @typescript-eslint/naming-convention2486 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2487 return this.helper.clone(ScheduledHelperType, {2488 scheduleFn,2489 scheduledId,2490 blocksNum,2491 options,2492 }) as T;2493 }2494}24952496class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2497 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2498 await this.helper.executeExtrinsic(2499 signer,2500 'api.tx.foreignAssets.registerForeignAsset',2501 [ownerAddress, location, metadata],2502 true,2503 );2504 }25052506 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2507 await this.helper.executeExtrinsic(2508 signer,2509 'api.tx.foreignAssets.updateForeignAsset',2510 [foreignAssetId, location, metadata],2511 true,2512 );2513 }2514}25152516class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2517 palletName: string;25182519 constructor(helper: T, palletName: string) {2520 super(helper);25212522 this.palletName = palletName;2523 }25242525 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2526 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2527 }2528}25292530class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2531 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2532 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2533 }25342535 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2536 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2537 }25382539 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2540 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2541 }2542}25432544class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2545 async accounts(address: string, currencyId: any) {2546 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2547 return BigInt(free);2548 }2549}25502551class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2552 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2553 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2554 }25552556 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2557 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2558 }25592560 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2561 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2562 }25632564 async account(assetId: string | number, address: string) {2565 const accountAsset = (2566 await this.helper.callRpc('api.query.assets.account', [assetId, address])2567 ).toJSON()! as any;25682569 if (accountAsset !== null) {2570 return BigInt(accountAsset['balance']);2571 } else {2572 return null;2573 }2574 }2575}25762577class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2578 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2579 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2580 }2581}25822583class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2584 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2585 const apiPrefix = 'api.tx.assetManager.';25862587 const registerTx = this.helper.constructApiCall(2588 apiPrefix + 'registerForeignAsset',2589 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2590 );25912592 const setUnitsTx = this.helper.constructApiCall(2593 apiPrefix + 'setAssetUnitsPerSecond',2594 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2595 );25962597 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2598 const encodedProposal = batchCall?.method.toHex() || '';2599 return encodedProposal;2600 }26012602 async assetTypeId(location: any) {2603 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2604 }2605}26062607class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2608 async notePreimage(signer: TSigner, encodedProposal: string) {2609 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2610 }26112612 externalProposeMajority(proposalHash: string) {2613 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2614 }26152616 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2617 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2618 }26192620 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2621 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2622 }2623}26242625class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2626 collective: string;26272628 constructor(helper: MoonbeamHelper, collective: string) {2629 super(helper);26302631 this.collective = collective;2632 }26332634 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2635 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2636 }26372638 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2639 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2640 }26412642 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2643 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2644 }26452646 async proposalCount() {2647 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2648 }2649}26502651export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2652export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;26532654export class UniqueHelper extends ChainHelperBase {2655 balance: BalanceGroup<UniqueHelper>;2656 collection: CollectionGroup;2657 nft: NFTGroup;2658 rft: RFTGroup;2659 ft: FTGroup;2660 staking: StakingGroup;2661 scheduler: SchedulerGroup;2662 foreignAssets: ForeignAssetsGroup;2663 xcm: XcmGroup<UniqueHelper>;2664 xTokens: XTokensGroup<UniqueHelper>;2665 tokens: TokensGroup<UniqueHelper>;26662667 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2668 super(logger, options.helperBase ?? UniqueHelper);26692670 this.balance = new BalanceGroup(this);2671 this.collection = new CollectionGroup(this);2672 this.nft = new NFTGroup(this);2673 this.rft = new RFTGroup(this);2674 this.ft = new FTGroup(this);2675 this.staking = new StakingGroup(this);2676 this.scheduler = new SchedulerGroup(this);2677 this.foreignAssets = new ForeignAssetsGroup(this);2678 this.xcm = new XcmGroup(this, 'polkadotXcm');2679 this.xTokens = new XTokensGroup(this);2680 this.tokens = new TokensGroup(this);2681 }26822683 getSudo<T extends UniqueHelper>() {2684 // eslint-disable-next-line @typescript-eslint/naming-convention2685 const SudoHelperType = SudoHelper(this.helperBase);2686 return this.clone(SudoHelperType) as T;2687 }2688}26892690export class XcmChainHelper extends ChainHelperBase {2691 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2692 const wsProvider = new WsProvider(wsEndpoint);2693 this.api = new ApiPromise({2694 provider: wsProvider,2695 });2696 await this.api.isReadyOrError;2697 this.network = await UniqueHelper.detectNetwork(this.api);2698 }2699}27002701export class RelayHelper extends XcmChainHelper {2702 xcm: XcmGroup<RelayHelper>;27032704 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2705 super(logger, options.helperBase ?? RelayHelper);27062707 this.xcm = new XcmGroup(this, 'xcmPallet');2708 }2709}27102711export class WestmintHelper extends XcmChainHelper {2712 balance: SubstrateBalanceGroup<WestmintHelper>;2713 xcm: XcmGroup<WestmintHelper>;2714 assets: AssetsGroup<WestmintHelper>;2715 xTokens: XTokensGroup<WestmintHelper>;27162717 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2718 super(logger, options.helperBase ?? WestmintHelper);27192720 this.balance = new SubstrateBalanceGroup(this);2721 this.xcm = new XcmGroup(this, 'polkadotXcm');2722 this.assets = new AssetsGroup(this);2723 this.xTokens = new XTokensGroup(this);2724 }2725}27262727export class MoonbeamHelper extends XcmChainHelper {2728 balance: EthereumBalanceGroup<MoonbeamHelper>;2729 assetManager: MoonbeamAssetManagerGroup;2730 assets: AssetsGroup<MoonbeamHelper>;2731 xTokens: XTokensGroup<MoonbeamHelper>;2732 democracy: MoonbeamDemocracyGroup;2733 collective: {2734 council: MoonbeamCollectiveGroup,2735 techCommittee: MoonbeamCollectiveGroup,2736 };27372738 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2739 super(logger, options.helperBase ?? MoonbeamHelper);27402741 this.balance = new EthereumBalanceGroup(this);2742 this.assetManager = new MoonbeamAssetManagerGroup(this);2743 this.assets = new AssetsGroup(this);2744 this.xTokens = new XTokensGroup(this);2745 this.democracy = new MoonbeamDemocracyGroup(this);2746 this.collective = {2747 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2748 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2749 };2750 }2751}27522753export class AcalaHelper extends XcmChainHelper {2754 balance: SubstrateBalanceGroup<AcalaHelper>;2755 assetRegistry: AcalaAssetRegistryGroup;2756 xTokens: XTokensGroup<AcalaHelper>;2757 tokens: TokensGroup<AcalaHelper>;27582759 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2760 super(logger, options.helperBase ?? AcalaHelper);27612762 this.balance = new SubstrateBalanceGroup(this);2763 this.assetRegistry = new AcalaAssetRegistryGroup(this);2764 this.xTokens = new XTokensGroup(this);2765 this.tokens = new TokensGroup(this);2766 }27672768 getSudo<T extends AcalaHelper>() {2769 // eslint-disable-next-line @typescript-eslint/naming-convention2770 const SudoHelperType = SudoHelper(this.helperBase);2771 return this.clone(SudoHelperType) as T;2772 }2773}27742775// eslint-disable-next-line @typescript-eslint/naming-convention2776function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2777 return class extends Base {2778 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2779 scheduledId: string;2780 blocksNum: number;2781 options: ISchedulerOptions;27822783 constructor(...args: any[]) {2784 const logger = args[0] as ILogger;2785 const options = args[1] as {2786 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2787 scheduledId: string,2788 blocksNum: number,2789 options: ISchedulerOptions2790 };27912792 super(logger);27932794 this.scheduleFn = options.scheduleFn;2795 this.scheduledId = options.scheduledId;2796 this.blocksNum = options.blocksNum;2797 this.options = options.options;2798 }27992800 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2801 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2802 const extrinsic = 'api.tx.scheduler.' + this.scheduleFn;28032804 return super.executeExtrinsic(2805 sender,2806 extrinsic,2807 [2808 this.scheduledId,2809 this.blocksNum,2810 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2811 this.options.priority ?? null,2812 {Value: scheduledTx},2813 ],2814 expectSuccess,2815 );2816 }2817 };2818}28192820// eslint-disable-next-line @typescript-eslint/naming-convention2821function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2822 return class extends Base {2823 constructor(...args: any[]) {2824 super(...args);2825 }28262827 executeExtrinsic (2828 sender: IKeyringPair,2829 extrinsic: string,2830 params: any[],2831 expectSuccess?: boolean,2832 ): Promise<ITransactionResult> {2833 const call = this.constructApiCall(extrinsic, params);2834 return super.executeExtrinsic(2835 sender,2836 'api.tx.sudo.sudo',2837 [call],2838 expectSuccess,2839 );2840 }2841 };2842}28432844export class UniqueBaseCollection {2845 helper: UniqueHelper;2846 collectionId: number;28472848 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2849 this.collectionId = collectionId;2850 this.helper = uniqueHelper;2851 }28522853 async getData() {2854 return await this.helper.collection.getData(this.collectionId);2855 }28562857 async getLastTokenId() {2858 return await this.helper.collection.getLastTokenId(this.collectionId);2859 }28602861 async doesTokenExist(tokenId: number) {2862 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2863 }28642865 async getAdmins() {2866 return await this.helper.collection.getAdmins(this.collectionId);2867 }28682869 async getAllowList() {2870 return await this.helper.collection.getAllowList(this.collectionId);2871 }28722873 async getEffectiveLimits() {2874 return await this.helper.collection.getEffectiveLimits(this.collectionId);2875 }28762877 async getProperties(propertyKeys?: string[] | null) {2878 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2879 }28802881 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2882 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2883 }28842885 async getOptions() {2886 return await this.helper.collection.getCollectionOptions(this.collectionId);2887 }28882889 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2890 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2891 }28922893 async confirmSponsorship(signer: TSigner) {2894 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2895 }28962897 async removeSponsor(signer: TSigner) {2898 return await this.helper.collection.removeSponsor(signer, this.collectionId);2899 }29002901 async setLimits(signer: TSigner, limits: ICollectionLimits) {2902 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2903 }29042905 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2906 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2907 }29082909 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2910 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2911 }29122913 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2914 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2915 }29162917 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2918 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2919 }29202921 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2922 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2923 }29242925 async setProperties(signer: TSigner, properties: IProperty[]) {2926 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2927 }29282929 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2930 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2931 }29322933 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2934 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2935 }29362937 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2938 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2939 }29402941 async disableNesting(signer: TSigner) {2942 return await this.helper.collection.disableNesting(signer, this.collectionId);2943 }29442945 async burn(signer: TSigner) {2946 return await this.helper.collection.burn(signer, this.collectionId);2947 }29482949 scheduleAt<T extends UniqueHelper>(2950 scheduledId: string,2951 executionBlockNumber: number,2952 options: ISchedulerOptions = {},2953 ) {2954 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2955 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2956 }29572958 scheduleAfter<T extends UniqueHelper>(2959 scheduledId: string,2960 blocksBeforeExecution: number,2961 options: ISchedulerOptions = {},2962 ) {2963 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2964 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2965 }29662967 getSudo<T extends UniqueHelper>() {2968 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2969 }2970}297129722973export class UniqueNFTCollection extends UniqueBaseCollection {2974 getTokenObject(tokenId: number) {2975 return new UniqueNFToken(tokenId, this);2976 }29772978 async getTokensByAddress(addressObj: ICrossAccountId) {2979 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2980 }29812982 async getToken(tokenId: number, blockHashAt?: string) {2983 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2984 }29852986 async getTokenOwner(tokenId: number, blockHashAt?: string) {2987 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2988 }29892990 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2991 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2992 }29932994 async getTokenChildren(tokenId: number, blockHashAt?: string) {2995 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2996 }29972998 async getPropertyPermissions(propertyKeys: string[] | null = null) {2999 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3000 }30013002 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3003 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3004 }30053006 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3007 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3008 }30093010 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3011 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3012 }30133014 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3015 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3016 }30173018 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3019 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3020 }30213022 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3023 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3024 }30253026 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3027 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3028 }30293030 async burnToken(signer: TSigner, tokenId: number) {3031 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3032 }30333034 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3035 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3036 }30373038 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3039 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3040 }30413042 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3043 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3044 }30453046 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3047 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3048 }30493050 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3051 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3052 }30533054 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3055 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3056 }30573058 scheduleAt<T extends UniqueHelper>(3059 scheduledId: string,3060 executionBlockNumber: number,3061 options: ISchedulerOptions = {},3062 ) {3063 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3064 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3065 }30663067 scheduleAfter<T extends UniqueHelper>(3068 scheduledId: string,3069 blocksBeforeExecution: number,3070 options: ISchedulerOptions = {},3071 ) {3072 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3073 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3074 }30753076 getSudo<T extends UniqueHelper>() {3077 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3078 }3079}308030813082export class UniqueRFTCollection extends UniqueBaseCollection {3083 getTokenObject(tokenId: number) {3084 return new UniqueRFToken(tokenId, this);3085 }30863087 async getToken(tokenId: number, blockHashAt?: string) {3088 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3089 }30903091 async getTokensByAddress(addressObj: ICrossAccountId) {3092 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3093 }30943095 async getTop10TokenOwners(tokenId: number) {3096 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3097 }30983099 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3100 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3101 }31023103 async getTokenTotalPieces(tokenId: number) {3104 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3105 }31063107 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3108 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3109 }31103111 async getPropertyPermissions(propertyKeys: string[] | null = null) {3112 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3113 }31143115 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3116 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3117 }31183119 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3120 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3121 }31223123 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3124 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3125 }31263127 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3128 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3129 }31303131 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3132 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3133 }31343135 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3136 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3137 }31383139 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3140 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3141 }31423143 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3144 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3145 }31463147 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3148 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3149 }31503151 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3152 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3153 }31543155 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3156 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3157 }31583159 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3160 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3161 }31623163 scheduleAt<T extends UniqueHelper>(3164 scheduledId: string,3165 executionBlockNumber: number,3166 options: ISchedulerOptions = {},3167 ) {3168 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3169 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3170 }31713172 scheduleAfter<T extends UniqueHelper>(3173 scheduledId: string,3174 blocksBeforeExecution: number,3175 options: ISchedulerOptions = {},3176 ) {3177 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3178 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3179 }31803181 getSudo<T extends UniqueHelper>() {3182 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3183 }3184}318531863187export class UniqueFTCollection extends UniqueBaseCollection {3188 async getBalance(addressObj: ICrossAccountId) {3189 return await this.helper.ft.getBalance(this.collectionId, addressObj);3190 }31913192 async getTotalPieces() {3193 return await this.helper.ft.getTotalPieces(this.collectionId);3194 }31953196 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3197 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3198 }31993200 async getTop10Owners() {3201 return await this.helper.ft.getTop10Owners(this.collectionId);3202 }32033204 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3205 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3206 }32073208 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3209 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3210 }32113212 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3213 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3214 }32153216 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3217 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3218 }32193220 async burnTokens(signer: TSigner, amount=1n) {3221 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3222 }32233224 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3225 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3226 }32273228 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3229 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3230 }32313232 scheduleAt<T extends UniqueHelper>(3233 scheduledId: string,3234 executionBlockNumber: number,3235 options: ISchedulerOptions = {},3236 ) {3237 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3238 return new UniqueFTCollection(this.collectionId, scheduledHelper);3239 }32403241 scheduleAfter<T extends UniqueHelper>(3242 scheduledId: string,3243 blocksBeforeExecution: number,3244 options: ISchedulerOptions = {},3245 ) {3246 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3247 return new UniqueFTCollection(this.collectionId, scheduledHelper);3248 }32493250 getSudo<T extends UniqueHelper>() {3251 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3252 }3253}325432553256export class UniqueBaseToken {3257 collection: UniqueNFTCollection | UniqueRFTCollection;3258 collectionId: number;3259 tokenId: number;32603261 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3262 this.collection = collection;3263 this.collectionId = collection.collectionId;3264 this.tokenId = tokenId;3265 }32663267 async getNextSponsored(addressObj: ICrossAccountId) {3268 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3269 }32703271 async getProperties(propertyKeys?: string[] | null) {3272 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3273 }32743275 async setProperties(signer: TSigner, properties: IProperty[]) {3276 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3277 }32783279 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3280 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3281 }32823283 async doesExist() {3284 return await this.collection.doesTokenExist(this.tokenId);3285 }32863287 nestingAccount() {3288 return this.collection.helper.util.getTokenAccount(this);3289 }32903291 scheduleAt<T extends UniqueHelper>(3292 scheduledId: string,3293 executionBlockNumber: number,3294 options: ISchedulerOptions = {},3295 ) {3296 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3297 return new UniqueBaseToken(this.tokenId, scheduledCollection);3298 }32993300 scheduleAfter<T extends UniqueHelper>(3301 scheduledId: string,3302 blocksBeforeExecution: number,3303 options: ISchedulerOptions = {},3304 ) {3305 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3306 return new UniqueBaseToken(this.tokenId, scheduledCollection);3307 }33083309 getSudo<T extends UniqueHelper>() {3310 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3311 }3312}331333143315export class UniqueNFToken extends UniqueBaseToken {3316 collection: UniqueNFTCollection;33173318 constructor(tokenId: number, collection: UniqueNFTCollection) {3319 super(tokenId, collection);3320 this.collection = collection;3321 }33223323 async getData(blockHashAt?: string) {3324 return await this.collection.getToken(this.tokenId, blockHashAt);3325 }33263327 async getOwner(blockHashAt?: string) {3328 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3329 }33303331 async getTopmostOwner(blockHashAt?: string) {3332 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3333 }33343335 async getChildren(blockHashAt?: string) {3336 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3337 }33383339 async nest(signer: TSigner, toTokenObj: IToken) {3340 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3341 }33423343 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3344 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3345 }33463347 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3348 return await this.collection.transferToken(signer, this.tokenId, addressObj);3349 }33503351 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3352 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3353 }33543355 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3356 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3357 }33583359 async isApproved(toAddressObj: ICrossAccountId) {3360 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3361 }33623363 async burn(signer: TSigner) {3364 return await this.collection.burnToken(signer, this.tokenId);3365 }33663367 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3368 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3369 }33703371 scheduleAt<T extends UniqueHelper>(3372 scheduledId: string,3373 executionBlockNumber: number,3374 options: ISchedulerOptions = {},3375 ) {3376 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3377 return new UniqueNFToken(this.tokenId, scheduledCollection);3378 }33793380 scheduleAfter<T extends UniqueHelper>(3381 scheduledId: string,3382 blocksBeforeExecution: number,3383 options: ISchedulerOptions = {},3384 ) {3385 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3386 return new UniqueNFToken(this.tokenId, scheduledCollection);3387 }33883389 getSudo<T extends UniqueHelper>() {3390 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3391 }3392}33933394export class UniqueRFToken extends UniqueBaseToken {3395 collection: UniqueRFTCollection;33963397 constructor(tokenId: number, collection: UniqueRFTCollection) {3398 super(tokenId, collection);3399 this.collection = collection;3400 }34013402 async getData(blockHashAt?: string) {3403 return await this.collection.getToken(this.tokenId, blockHashAt);3404 }34053406 async getTop10Owners() {3407 return await this.collection.getTop10TokenOwners(this.tokenId);3408 }34093410 async getBalance(addressObj: ICrossAccountId) {3411 return await this.collection.getTokenBalance(this.tokenId, addressObj);3412 }34133414 async getTotalPieces() {3415 return await this.collection.getTokenTotalPieces(this.tokenId);3416 }34173418 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3419 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3420 }34213422 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3423 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3424 }34253426 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3427 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3428 }34293430 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3431 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3432 }34333434 async repartition(signer: TSigner, amount: bigint) {3435 return await this.collection.repartitionToken(signer, this.tokenId, amount);3436 }34373438 async burn(signer: TSigner, amount=1n) {3439 return await this.collection.burnToken(signer, this.tokenId, amount);3440 }34413442 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3443 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3444 }34453446 scheduleAt<T extends UniqueHelper>(3447 scheduledId: string,3448 executionBlockNumber: number,3449 options: ISchedulerOptions = {},3450 ) {3451 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3452 return new UniqueRFToken(this.tokenId, scheduledCollection);3453 }34543455 scheduleAfter<T extends UniqueHelper>(3456 scheduledId: string,3457 blocksBeforeExecution: number,3458 options: ISchedulerOptions = {},3459 ) {3460 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3461 return new UniqueRFToken(this.tokenId, scheduledCollection);3462 }34633464 getSudo<T extends UniqueHelper>() {3465 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3466 }3467}