difftreelog
chore fix test formating
in: master
4 files changed
tests/src/eth/collectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionAdmin.test.ts
+++ b/tests/src/eth/collectionAdmin.test.ts
@@ -14,7 +14,6 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {IKeyringPair} from '@polkadot/types/types';
-import {IEthCrossAccountId} from '../util/playgrounds/types';
import {usingEthPlaygrounds, itEth, expect, EthUniqueHelper} from './util';
async function recordEthFee(helper: EthUniqueHelper, userAddress: string, call: () => Promise<any>) {
tests/src/eth/createFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createFTCollection.test.ts
+++ b/tests/src/eth/createFTCollection.test.ts
@@ -15,7 +15,7 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {IKeyringPair} from '@polkadot/types/types';
-import { evmToAddress } from '@polkadot/util-crypto';
+import {evmToAddress} from '@polkadot/util-crypto';
import {Pallets, requirePalletsOrSkip} from '../util';
import {expect, itEth, usingEthPlaygrounds} from './util';
@@ -27,7 +27,7 @@
before(async function() {
await usingEthPlaygrounds(async (helper, privateKey) => {
requirePalletsOrSkip(this, helper, [Pallets.Fungible]);
- donor = await privateKey('//Alice');
+ donor = await privateKey({filename: __filename});
});
});
@@ -181,7 +181,7 @@
before(async function() {
await usingEthPlaygrounds(async (helper, privateKey) => {
requirePalletsOrSkip(this, helper, [Pallets.Fungible]);
- donor = await privateKey('//Alice');
+ donor = await privateKey({filename: __filename});
nominal = helper.balance.getOneTokenNominal();
});
});
tests/src/eth/destroyCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/destroyCollection.test.ts
+++ b/tests/src/eth/destroyCollection.test.ts
@@ -25,7 +25,7 @@
before(async function() {
await usingEthPlaygrounds(async (helper, privateKey) => {
requirePalletsOrSkip(this, helper, [Pallets.ReFungible, Pallets.NFT]);
- donor = await privateKey('//Alice');
+ donor = await privateKey({filename: __filename});
});
});
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, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {13 IApiListeners,14 IBlock,15 IEvent,16 IChainProperties,17 ICollectionCreationOptions,18 ICollectionLimits,19 ICollectionPermissions,20 ICrossAccountId,21 ICrossAccountIdLower,22 ILogger,23 INestingPermissions,24 IProperty,25 IStakingInfo,26 ISchedulerOptions,27 ISubstrateBalance,28 IToken,29 ITokenPropertyPermission,30 ITransactionResult,31 IUniqueHelperLog,32 TApiAllowedListeners,33 TEthereumAccount,34 TSigner,35 TSubstrateAccount,36 IEthCrossAccountId,37 TNetworks,38 IForeignAssetMetadata,39 AcalaAssetMetadata,40 MoonbeamAssetInfo,41 DemocracyStandardAccountVote,42} from './types';43import {hexToU8a} from '@polkadot/util/hex';44import {u8aConcat} from '@polkadot/util/u8a';4546export class CrossAccountId implements ICrossAccountId {47 Substrate?: TSubstrateAccount;48 Ethereum?: TEthereumAccount;4950 constructor(account: ICrossAccountId) {51 if (account.Substrate) this.Substrate = account.Substrate;52 if (account.Ethereum) this.Ethereum = account.Ethereum;53 }5455 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {56 switch (domain) {57 case 'Substrate': return new CrossAccountId({Substrate: account.address});58 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();59 }60 }6162 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {63 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});64 }6566 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {67 return encodeAddress(decodeAddress(address), ss58Format);68 }6970 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {71 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});72 }73 74 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {75 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);76 return this;77 }7879 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {80 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));81 }8283 toEthereum(): CrossAccountId {84 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});85 return this;86 }8788 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {89 return evmToAddress(address, ss58Format);90 }9192 toSubstrate(ss58Format?: number): CrossAccountId {93 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});94 return this;95 }96 97 toLowerCase(): CrossAccountId {98 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();99 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();100 return this;101 }102}103104const nesting = {105 toChecksumAddress(address: string): string {106 if (typeof address === 'undefined') return '';107108 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);109110 address = address.toLowerCase().replace(/^0x/i,'');111 const addressHash = keccakAsHex(address).replace(/^0x/i,'');112 const checksumAddress = ['0x'];113114 for (let i = 0; i < address.length; i++) {115 // If ith character is 8 to f then make it uppercase116 if (parseInt(addressHash[i], 16) > 7) {117 checksumAddress.push(address[i].toUpperCase());118 } else {119 checksumAddress.push(address[i]);120 }121 }122 return checksumAddress.join('');123 },124 tokenIdToAddress(collectionId: number, tokenId: number) {125 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);126 },127};128129class UniqueUtil {130 static transactionStatus = {131 NOT_READY: 'NotReady',132 FAIL: 'Fail',133 SUCCESS: 'Success',134 };135136 static chainLogType = {137 EXTRINSIC: 'extrinsic',138 RPC: 'rpc',139 };140141 static getTokenAccount(token: IToken): CrossAccountId {142 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});143 }144145 static getTokenAddress(token: IToken): string {146 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);147 }148149 static getDefaultLogger(): ILogger {150 return {151 log(msg: any, level = 'INFO') {152 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));153 },154 level: {155 ERROR: 'ERROR',156 WARNING: 'WARNING',157 INFO: 'INFO',158 },159 };160 }161162 static vec2str(arr: string[] | number[]) {163 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');164 }165166 static str2vec(string: string) {167 if (typeof string !== 'string') return string;168 return Array.from(string).map(x => x.charCodeAt(0));169 }170171 static fromSeed(seed: string, ss58Format = 42) {172 const keyring = new Keyring({type: 'sr25519', ss58Format});173 return keyring.addFromUri(seed);174 }175176 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {177 if (creationResult.status !== this.transactionStatus.SUCCESS) {178 throw Error('Unable to create collection!');179 }180181 let collectionId = null;182 creationResult.result.events.forEach(({event: {data, method, section}}) => {183 if ((section === 'common') && (method === 'CollectionCreated')) {184 collectionId = parseInt(data[0].toString(), 10);185 }186 });187188 if (collectionId === null) {189 throw Error('No CollectionCreated event was found!');190 }191192 return collectionId;193 }194195 static extractTokensFromCreationResult(creationResult: ITransactionResult): {196 success: boolean, 197 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],198 } {199 if (creationResult.status !== this.transactionStatus.SUCCESS) {200 throw Error('Unable to create tokens!');201 }202 let success = false;203 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];204 creationResult.result.events.forEach(({event: {data, method, section}}) => {205 if (method === 'ExtrinsicSuccess') {206 success = true;207 } else if ((section === 'common') && (method === 'ItemCreated')) {208 tokens.push({209 collectionId: parseInt(data[0].toString(), 10),210 tokenId: parseInt(data[1].toString(), 10),211 owner: data[2].toHuman(),212 amount: data[3].toBigInt(),213 });214 }215 });216 return {success, tokens};217 }218219 static extractTokensFromBurnResult(burnResult: ITransactionResult): {220 success: boolean, 221 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],222 } {223 if (burnResult.status !== this.transactionStatus.SUCCESS) {224 throw Error('Unable to burn tokens!');225 }226 let success = false;227 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];228 burnResult.result.events.forEach(({event: {data, method, section}}) => {229 if (method === 'ExtrinsicSuccess') {230 success = true;231 } else if ((section === 'common') && (method === 'ItemDestroyed')) {232 tokens.push({233 collectionId: parseInt(data[0].toString(), 10),234 tokenId: parseInt(data[1].toString(), 10),235 owner: data[2].toHuman(),236 amount: data[3].toBigInt(),237 });238 }239 });240 return {success, tokens};241 }242243 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {244 let eventId = null;245 events.forEach(({event: {data, method, section}}) => {246 if ((section === expectedSection) && (method === expectedMethod)) {247 eventId = parseInt(data[0].toString(), 10);248 }249 });250251 if (eventId === null) {252 throw Error(`No ${expectedMethod} event was found!`);253 }254 return eventId === collectionId;255 }256257 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {258 const normalizeAddress = (address: string | ICrossAccountId) => {259 if(typeof address === 'string') return address;260 const obj = {} as any;261 Object.keys(address).forEach(k => {262 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];263 });264 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);265 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();266 return address;267 };268 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;269 events.forEach(({event: {data, method, section}}) => {270 if ((section === 'common') && (method === 'Transfer')) {271 const hData = (data as any).toJSON();272 transfer = {273 collectionId: hData[0],274 tokenId: hData[1],275 from: normalizeAddress(hData[2]),276 to: normalizeAddress(hData[3]),277 amount: BigInt(hData[4]),278 };279 }280 });281 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;282 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);283 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);284 isSuccess = isSuccess && amount === transfer.amount;285 return isSuccess;286 }287288 static bigIntToDecimals(number: bigint, decimals = 18) {289 const numberStr = number.toString();290 const dotPos = numberStr.length - decimals;291 292 if (dotPos <= 0) {293 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;294 } else {295 const intPart = numberStr.substring(0, dotPos);296 const fractPart = numberStr.substring(dotPos);297 return intPart + '.' + fractPart;298 }299 }300}301302class UniqueEventHelper {303 private static extractIndex(index: any): [number, number] | string {304 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];305 return index.toJSON();306 }307308 private static extractSub(data: any, subTypes: any): {[key: string]: any} {309 let obj: any = {};310 let index = 0;311312 if (data.entries) {313 for(const [key, value] of data.entries()) {314 obj[key] = this.extractData(value, subTypes[index]);315 index++;316 }317 } else obj = data.toJSON();318319 return obj;320 }321 322 private static extractData(data: any, type: any): any {323 if(!type) return data.toHuman();324 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();325 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();326 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);327 return data.toHuman();328 }329330 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {331 const parsedEvents: IEvent[] = [];332333 events.forEach((record) => {334 const {event, phase} = record;335 const types = event.typeDef;336337 const eventData: IEvent = {338 section: event.section.toString(),339 method: event.method.toString(),340 index: this.extractIndex(event.index),341 data: [],342 phase: phase.toJSON(),343 };344345 event.data.forEach((val: any, index: number) => {346 eventData.data.push(this.extractData(val, types[index]));347 });348349 parsedEvents.push(eventData);350 });351352 return parsedEvents;353 }354}355356export class ChainHelperBase {357 helperBase: any;358359 transactionStatus = UniqueUtil.transactionStatus;360 chainLogType = UniqueUtil.chainLogType;361 util: typeof UniqueUtil;362 eventHelper: typeof UniqueEventHelper;363 logger: ILogger;364 api: ApiPromise | null;365 forcedNetwork: TNetworks | null;366 network: TNetworks | null;367 chainLog: IUniqueHelperLog[];368 children: ChainHelperBase[];369 address: AddressGroup;370 chain: ChainGroup;371372 constructor(logger?: ILogger, helperBase?: any) {373 this.helperBase = helperBase;374375 this.util = UniqueUtil;376 this.eventHelper = UniqueEventHelper;377 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();378 this.logger = logger;379 this.api = null;380 this.forcedNetwork = null;381 this.network = null;382 this.chainLog = [];383 this.children = [];384 this.address = new AddressGroup(this);385 this.chain = new ChainGroup(this);386 }387388 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {389 Object.setPrototypeOf(helperCls.prototype, this);390 const newHelper = new helperCls(this.logger, options);391392 newHelper.api = this.api;393 newHelper.network = this.network;394 newHelper.forceNetwork = this.forceNetwork;395396 this.children.push(newHelper);397398 return newHelper;399 }400401 getApi(): ApiPromise {402 if(this.api === null) throw Error('API not initialized');403 return this.api;404 }405406 clearChainLog(): void {407 this.chainLog = [];408 }409410 forceNetwork(value: TNetworks): void {411 this.forcedNetwork = value;412 }413414 async connect(wsEndpoint: string, listeners?: IApiListeners) {415 if (this.api !== null) throw Error('Already connected');416 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);417 this.api = api;418 this.network = network;419 }420421 async disconnect() {422 for (const child of this.children) {423 child.clearApi();424 }425426 if (this.api === null) return;427 await this.api.disconnect();428 this.clearApi();429 }430431 clearApi() {432 this.api = null;433 this.network = null;434 }435436 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {437 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;438 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];439440 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;441442 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;443 return 'opal';444 }445446 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {447 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});448 await api.isReady;449450 const network = await this.detectNetwork(api);451452 await api.disconnect();453454 return network;455 }456457 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{458 api: ApiPromise;459 network: TNetworks;460 }> {461 if(typeof network === 'undefined' || network === null) network = 'opal';462 const supportedRPC = {463 opal: {464 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,465 },466 quartz: {467 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,468 },469 unique: {470 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,471 },472 rococo: {},473 westend: {},474 moonbeam: {},475 moonriver: {},476 acala: {},477 karura: {},478 westmint: {},479 };480 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);481 const rpc = supportedRPC[network];482483 // TODO: investigate how to replace rpc in runtime484 // api._rpcCore.addUserInterfaces(rpc);485486 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});487488 await api.isReadyOrError;489490 if (typeof listeners === 'undefined') listeners = {};491 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {492 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;493 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);494 }495496 return {api, network};497 }498499 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {500 const {events, status} = data;501 if (status.isReady) {502 return this.transactionStatus.NOT_READY;503 }504 if (status.isBroadcast) {505 return this.transactionStatus.NOT_READY;506 }507 if (status.isInBlock || status.isFinalized) {508 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');509 if (errors.length > 0) {510 return this.transactionStatus.FAIL;511 }512 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {513 return this.transactionStatus.SUCCESS;514 }515 }516517 return this.transactionStatus.FAIL;518 }519520 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {521 const sign = (callback: any) => {522 if(options !== null) return transaction.signAndSend(sender, options, callback);523 return transaction.signAndSend(sender, callback);524 };525 // eslint-disable-next-line no-async-promise-executor526 return new Promise(async (resolve, reject) => {527 try {528 const unsub = await sign((result: any) => {529 const status = this.getTransactionStatus(result);530531 if (status === this.transactionStatus.SUCCESS) {532 this.logger.log(`${label} successful`);533 unsub();534 resolve({result, status});535 } else if (status === this.transactionStatus.FAIL) {536 let moduleError = null;537538 if (result.hasOwnProperty('dispatchError')) {539 const dispatchError = result['dispatchError'];540541 if (dispatchError) {542 if (dispatchError.isModule) {543 const modErr = dispatchError.asModule;544 const errorMeta = dispatchError.registry.findMetaError(modErr);545546 moduleError = `${errorMeta.section}.${errorMeta.name}`;547 } else {548 moduleError = dispatchError.toHuman();549 }550 } else {551 this.logger.log(result, this.logger.level.ERROR);552 }553 }554555 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);556 unsub();557 reject({status, moduleError, result});558 }559 });560 } catch (e) {561 this.logger.log(e, this.logger.level.ERROR);562 reject(e);563 }564 });565 }566567 constructApiCall(apiCall: string, params: any[]) {568 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);569 let call = this.getApi() as any;570 for(const part of apiCall.slice(4).split('.')) {571 call = call[part];572 }573 return call(...params);574 }575576 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {577 if(this.api === null) throw Error('API not initialized');578 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);579580 const startTime = (new Date()).getTime();581 let result: ITransactionResult;582 let events: IEvent[] = [];583 try {584 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;585 events = this.eventHelper.extractEvents(result.result.events);586 }587 catch(e) {588 if(!(e as object).hasOwnProperty('status')) throw e;589 result = e as ITransactionResult;590 }591592 const endTime = (new Date()).getTime();593594 const log = {595 executedAt: endTime,596 executionTime: endTime - startTime,597 type: this.chainLogType.EXTRINSIC,598 status: result.status,599 call: extrinsic,600 signer: this.getSignerAddress(sender),601 params,602 } as IUniqueHelperLog;603604 if(result.status !== this.transactionStatus.SUCCESS) {605 if (result.moduleError) log.moduleError = result.moduleError;606 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;607 }608 if(events.length > 0) log.events = events;609610 this.chainLog.push(log);611612 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {613 if (result.moduleError) throw Error(`${result.moduleError}`);614 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));615 }616 return result;617 }618619 async callRpc(rpc: string, params?: any[]) {620 if(typeof params === 'undefined') params = [];621 if(this.api === null) throw Error('API not initialized');622 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);623624 const startTime = (new Date()).getTime();625 let result;626 let error = null;627 const log = {628 type: this.chainLogType.RPC,629 call: rpc,630 params,631 } as IUniqueHelperLog;632633 try {634 result = await this.constructApiCall(rpc, params);635 }636 catch(e) {637 error = e;638 }639640 const endTime = (new Date()).getTime();641642 log.executedAt = endTime;643 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';644 log.executionTime = endTime - startTime;645646 this.chainLog.push(log);647648 if(error !== null) throw error;649650 return result;651 }652653 getSignerAddress(signer: IKeyringPair | string): string {654 if(typeof signer === 'string') return signer;655 return signer.address;656 }657658 fetchAllPalletNames(): string[] {659 if(this.api === null) throw Error('API not initialized');660 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());661 }662663 fetchMissingPalletNames(requiredPallets: string[]): string[] {664 const palletNames = this.fetchAllPalletNames();665 return requiredPallets.filter(p => !palletNames.includes(p));666 }667}668669670class HelperGroup<T extends ChainHelperBase> {671 helper: T;672673 constructor(uniqueHelper: T) {674 this.helper = uniqueHelper;675 }676}677678679class CollectionGroup extends HelperGroup<UniqueHelper> {680 /**681 * Get number of blocks when sponsored transaction is available.682 *683 * @param collectionId ID of collection684 * @param tokenId ID of token685 * @param addressObj address for which the sponsorship is checked686 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});687 * @returns number of blocks or null if sponsorship hasn't been set688 */689 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {690 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();691 }692693 /**694 * Get the number of created collections.695 *696 * @returns number of created collections697 */698 async getTotalCount(): Promise<number> {699 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();700 }701702 /**703 * Get information about the collection with additional data,704 * including the number of tokens it contains, its administrators,705 * the normalized address of the collection's owner, and decoded name and description.706 *707 * @param collectionId ID of collection708 * @example await getData(2)709 * @returns collection information object710 */711 async getData(collectionId: number): Promise<{712 id: number;713 name: string;714 description: string;715 tokensCount: number;716 admins: CrossAccountId[];717 normalizedOwner: TSubstrateAccount;718 raw: any719 } | null> {720 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);721 const humanCollection = collection.toHuman(), collectionData = {722 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],723 raw: humanCollection,724 } as any, jsonCollection = collection.toJSON();725 if (humanCollection === null) return null;726 collectionData.raw.limits = jsonCollection.limits;727 collectionData.raw.permissions = jsonCollection.permissions;728 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);729 for (const key of ['name', 'description']) {730 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);731 }732733 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))734 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)735 : 0;736 collectionData.admins = await this.getAdmins(collectionId);737738 return collectionData;739 }740741 /**742 * Get the addresses of the collection's administrators, optionally normalized.743 *744 * @param collectionId ID of collection745 * @param normalize whether to normalize the addresses to the default ss58 format746 * @example await getAdmins(1)747 * @returns array of administrators748 */749 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {750 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();751752 return normalize753 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())754 : admins;755 }756757 /**758 * Get the addresses added to the collection allow-list, optionally normalized.759 * @param collectionId ID of collection760 * @param normalize whether to normalize the addresses to the default ss58 format761 * @example await getAllowList(1)762 * @returns array of allow-listed addresses763 */764 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {765 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();766 return normalize767 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())768 : allowListed;769 }770771 /**772 * Get the effective limits of the collection instead of null for default values773 *774 * @param collectionId ID of collection775 * @example await getEffectiveLimits(2)776 * @returns object of collection limits777 */778 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {779 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();780 }781782 /**783 * Burns the collection if the signer has sufficient permissions and collection is empty.784 *785 * @param signer keyring of signer786 * @param collectionId ID of collection787 * @example await helper.collection.burn(aliceKeyring, 3);788 * @returns ```true``` if extrinsic success, otherwise ```false```789 */790 async burn(signer: TSigner, collectionId: number): Promise<boolean> {791 const result = await this.helper.executeExtrinsic(792 signer,793 'api.tx.unique.destroyCollection', [collectionId],794 true,795 );796797 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');798 }799800 /**801 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.802 *803 * @param signer keyring of signer804 * @param collectionId ID of collection805 * @param sponsorAddress Sponsor substrate address806 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")807 * @returns ```true``` if extrinsic success, otherwise ```false```808 */809 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {810 const result = await this.helper.executeExtrinsic(811 signer,812 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],813 true,814 );815816 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');817 }818819 /**820 * Confirms consent to sponsor the collection on behalf of the signer.821 *822 * @param signer keyring of signer823 * @param collectionId ID of collection824 * @example confirmSponsorship(aliceKeyring, 10)825 * @returns ```true``` if extrinsic success, otherwise ```false```826 */827 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {828 const result = await this.helper.executeExtrinsic(829 signer,830 'api.tx.unique.confirmSponsorship', [collectionId],831 true,832 );833834 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');835 }836837 /**838 * Removes the sponsor of a collection, regardless if it consented or not.839 *840 * @param signer keyring of signer841 * @param collectionId ID of collection842 * @example removeSponsor(aliceKeyring, 10)843 * @returns ```true``` if extrinsic success, otherwise ```false```844 */845 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {846 const result = await this.helper.executeExtrinsic(847 signer,848 'api.tx.unique.removeCollectionSponsor', [collectionId],849 true,850 );851852 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');853 }854855 /**856 * Sets the limits of the collection. At least one limit must be specified for a correct call.857 *858 * @param signer keyring of signer859 * @param collectionId ID of collection860 * @param limits collection limits object861 * @example862 * await setLimits(863 * aliceKeyring,864 * 10,865 * {866 * sponsorTransferTimeout: 0,867 * ownerCanDestroy: false868 * }869 * )870 * @returns ```true``` if extrinsic success, otherwise ```false```871 */872 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {873 const result = await this.helper.executeExtrinsic(874 signer,875 'api.tx.unique.setCollectionLimits', [collectionId, limits],876 true,877 );878879 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');880 }881882 /**883 * Changes the owner of the collection to the new Substrate address.884 *885 * @param signer keyring of signer886 * @param collectionId ID of collection887 * @param ownerAddress substrate address of new owner888 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")889 * @returns ```true``` if extrinsic success, otherwise ```false```890 */891 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {892 const result = await this.helper.executeExtrinsic(893 signer,894 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],895 true,896 );897898 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');899 }900901 /**902 * Adds a collection administrator.903 *904 * @param signer keyring of signer905 * @param collectionId ID of collection906 * @param adminAddressObj Administrator address (substrate or ethereum)907 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})908 * @returns ```true``` if extrinsic success, otherwise ```false```909 */910 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {911 const result = await this.helper.executeExtrinsic(912 signer,913 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],914 true,915 );916917 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');918 }919920 /**921 * Removes a collection administrator.922 *923 * @param signer keyring of signer924 * @param collectionId ID of collection925 * @param adminAddressObj Administrator address (substrate or ethereum)926 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})927 * @returns ```true``` if extrinsic success, otherwise ```false```928 */929 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {930 const result = await this.helper.executeExtrinsic(931 signer,932 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],933 true,934 );935936 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');937 }938939 /**940 * Check if user is in allow list.941 * 942 * @param collectionId ID of collection943 * @param user Account to check944 * @example await getAdmins(1)945 * @returns is user in allow list946 */947 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {948 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();949 }950951 /**952 * Adds an address to allow list953 * @param signer keyring of signer954 * @param collectionId ID of collection955 * @param addressObj address to add to the allow list956 * @returns ```true``` if extrinsic success, otherwise ```false```957 */958 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {959 const result = await this.helper.executeExtrinsic(960 signer,961 'api.tx.unique.addToAllowList', [collectionId, addressObj],962 true,963 );964965 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');966 }967968 /**969 * Removes an address from allow list970 *971 * @param signer keyring of signer972 * @param collectionId ID of collection973 * @param addressObj address to remove from the allow list974 * @returns ```true``` if extrinsic success, otherwise ```false```975 */976 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {977 const result = await this.helper.executeExtrinsic(978 signer,979 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],980 true,981 );982983 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');984 }985986 /**987 * Sets onchain permissions for selected collection.988 *989 * @param signer keyring of signer990 * @param collectionId ID of collection991 * @param permissions collection permissions object992 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});993 * @returns ```true``` if extrinsic success, otherwise ```false```994 */995 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {996 const result = await this.helper.executeExtrinsic(997 signer,998 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],999 true,1000 );10011002 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');1003 }10041005 /**1006 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1007 *1008 * @param signer keyring of signer1009 * @param collectionId ID of collection1010 * @param permissions nesting permissions object1011 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1012 * @returns ```true``` if extrinsic success, otherwise ```false```1013 */1014 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1015 return await this.setPermissions(signer, collectionId, {nesting: permissions});1016 }10171018 /**1019 * Disables nesting for selected collection.1020 *1021 * @param signer keyring of signer1022 * @param collectionId ID of collection1023 * @example disableNesting(aliceKeyring, 10);1024 * @returns ```true``` if extrinsic success, otherwise ```false```1025 */1026 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1027 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1028 }10291030 /**1031 * Sets onchain properties to the collection.1032 *1033 * @param signer keyring of signer1034 * @param collectionId ID of collection1035 * @param properties array of property objects1036 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1037 * @returns ```true``` if extrinsic success, otherwise ```false```1038 */1039 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1040 const result = await this.helper.executeExtrinsic(1041 signer,1042 'api.tx.unique.setCollectionProperties', [collectionId, properties],1043 true,1044 );10451046 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1047 }10481049 /**1050 * Get collection properties.1051 * 1052 * @param collectionId ID of collection1053 * @param propertyKeys optionally filter the returned properties to only these keys1054 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1055 * @returns array of key-value pairs1056 */1057 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1058 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1059 }10601061 async getCollectionOptions(collectionId: number) {1062 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1063 }10641065 /**1066 * Deletes onchain properties from the collection.1067 *1068 * @param signer keyring of signer1069 * @param collectionId ID of collection1070 * @param propertyKeys array of property keys to delete1071 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1072 * @returns ```true``` if extrinsic success, otherwise ```false```1073 */1074 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1075 const result = await this.helper.executeExtrinsic(1076 signer,1077 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1078 true,1079 );10801081 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1082 }10831084 /**1085 * Changes the owner of the token.1086 *1087 * @param signer keyring of signer1088 * @param collectionId ID of collection1089 * @param tokenId ID of token1090 * @param addressObj address of a new owner1091 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1092 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1093 * @returns true if the token success, otherwise false1094 */1095 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1096 const result = await this.helper.executeExtrinsic(1097 signer,1098 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1099 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1100 );11011102 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1103 }11041105 /**1106 *1107 * Change ownership of a token(s) on behalf of the owner.1108 *1109 * @param signer keyring of signer1110 * @param collectionId ID of collection1111 * @param tokenId ID of token1112 * @param fromAddressObj address on behalf of which the token will be sent1113 * @param toAddressObj new token owner1114 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1115 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1116 * @returns true if the token success, otherwise false1117 */1118 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1119 const result = await this.helper.executeExtrinsic(1120 signer,1121 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1122 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1123 );1124 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1125 }11261127 /**1128 *1129 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1130 *1131 * @param signer keyring of signer1132 * @param collectionId ID of collection1133 * @param tokenId ID of token1134 * @param amount amount of tokens to be burned. For NFT must be set to 1n1135 * @example burnToken(aliceKeyring, 10, 5);1136 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1137 */1138 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1139 const burnResult = await this.helper.executeExtrinsic(1140 signer,1141 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1142 true, // `Unable to burn token for ${label}`,1143 );1144 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1145 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1146 return burnedTokens.success;1147 }11481149 /**1150 * Destroys a concrete instance of NFT on behalf of the owner1151 *1152 * @param signer keyring of signer1153 * @param collectionId ID of collection1154 * @param tokenId ID of token1155 * @param fromAddressObj address on behalf of which the token will be burnt1156 * @param amount amount of tokens to be burned. For NFT must be set to 1n1157 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1158 * @returns ```true``` if extrinsic success, otherwise ```false```1159 */1160 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1161 const burnResult = await this.helper.executeExtrinsic(1162 signer,1163 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1164 true, // `Unable to burn token from for ${label}`,1165 );1166 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1167 return burnedTokens.success && burnedTokens.tokens.length > 0;1168 }11691170 /**1171 * Set, change, or remove approved address to transfer the ownership of the NFT.1172 *1173 * @param signer keyring of signer1174 * @param collectionId ID of collection1175 * @param tokenId ID of token1176 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1177 * @param amount amount of token to be approved. For NFT must be set to 1n1178 * @returns ```true``` if extrinsic success, otherwise ```false```1179 */1180 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1181 const approveResult = await this.helper.executeExtrinsic(1182 signer,1183 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1184 true, // `Unable to approve token for ${label}`,1185 );11861187 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1188 }11891190 /**1191 * Get the amount of token pieces approved to transfer or burn. Normally 0.1192 *1193 * @param collectionId ID of collection1194 * @param tokenId ID of token1195 * @param toAccountObj address which is approved to use token pieces1196 * @param fromAccountObj address which may have allowed the use of its owned tokens1197 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1198 * @returns number of approved to transfer pieces1199 */1200 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1201 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1202 }12031204 /**1205 * Get the last created token ID in a collection1206 *1207 * @param collectionId ID of collection1208 * @example getLastTokenId(10);1209 * @returns id of the last created token1210 */1211 async getLastTokenId(collectionId: number): Promise<number> {1212 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1213 }12141215 /**1216 * Check if token exists1217 *1218 * @param collectionId ID of collection1219 * @param tokenId ID of token1220 * @example doesTokenExist(10, 20);1221 * @returns true if the token exists, otherwise false1222 */1223 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1224 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1225 }1226}12271228class NFTnRFT extends CollectionGroup {1229 /**1230 * Get tokens owned by account1231 *1232 * @param collectionId ID of collection1233 * @param addressObj tokens owner1234 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1235 * @returns array of token ids owned by account1236 */1237 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1238 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1239 }12401241 /**1242 * Get token data1243 *1244 * @param collectionId ID of collection1245 * @param tokenId ID of token1246 * @param propertyKeys optionally filter the token properties to only these keys1247 * @param blockHashAt optionally query the data at some block with this hash1248 * @example getToken(10, 5);1249 * @returns human readable token data1250 */1251 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1252 properties: IProperty[];1253 owner: CrossAccountId;1254 normalizedOwner: CrossAccountId;1255 }| null> {1256 let tokenData;1257 if(typeof blockHashAt === 'undefined') {1258 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1259 }1260 else {1261 if(propertyKeys.length == 0) {1262 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1263 if(!collection) return null;1264 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1265 }1266 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1267 }1268 tokenData = tokenData.toHuman();1269 if (tokenData === null || tokenData.owner === null) return null;1270 const owner = {} as any;1271 for (const key of Object.keys(tokenData.owner)) {1272 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1273 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1274 : tokenData.owner[key];1275 }1276 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1277 return tokenData;1278 }12791280 /**1281 * Set permissions to change token properties1282 *1283 * @param signer keyring of signer1284 * @param collectionId ID of collection1285 * @param permissions permissions to change a property by the collection admin or token owner1286 * @example setTokenPropertyPermissions(1287 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1288 * )1289 * @returns true if extrinsic success otherwise false1290 */1291 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1292 const result = await this.helper.executeExtrinsic(1293 signer,1294 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1295 true,1296 );12971298 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1299 }13001301 /**1302 * Get token property permissions.1303 * 1304 * @param collectionId ID of collection1305 * @param propertyKeys optionally filter the returned property permissions to only these keys1306 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1307 * @returns array of key-permission pairs1308 */1309 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1310 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1311 }13121313 /**1314 * Set token properties1315 *1316 * @param signer keyring of signer1317 * @param collectionId ID of collection1318 * @param tokenId ID of token1319 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1320 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1321 * @returns ```true``` if extrinsic success, otherwise ```false```1322 */1323 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1324 const result = await this.helper.executeExtrinsic(1325 signer,1326 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1327 true,1328 );13291330 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1331 }13321333 /**1334 * Get properties, metadata assigned to a token.1335 * 1336 * @param collectionId ID of collection1337 * @param tokenId ID of token1338 * @param propertyKeys optionally filter the returned properties to only these keys1339 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1340 * @returns array of key-value pairs1341 */1342 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1343 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1344 }13451346 /**1347 * Delete the provided properties of a token1348 * @param signer keyring of signer1349 * @param collectionId ID of collection1350 * @param tokenId ID of token1351 * @param propertyKeys property keys to be deleted1352 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1353 * @returns ```true``` if extrinsic success, otherwise ```false```1354 */1355 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1356 const result = await this.helper.executeExtrinsic(1357 signer,1358 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1359 true,1360 );13611362 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1363 }13641365 /**1366 * Mint new collection1367 *1368 * @param signer keyring of signer1369 * @param collectionOptions basic collection options and properties1370 * @param mode NFT or RFT type of a collection1371 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1372 * @returns object of the created collection1373 */1374 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1375 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1376 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1377 for (const key of ['name', 'description', 'tokenPrefix']) {1378 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);1379 }1380 const creationResult = await this.helper.executeExtrinsic(1381 signer,1382 'api.tx.unique.createCollectionEx', [collectionOptions],1383 true, // errorLabel,1384 );1385 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1386 }13871388 getCollectionObject(_collectionId: number): any {1389 return null;1390 }13911392 getTokenObject(_collectionId: number, _tokenId: number): any {1393 return null;1394 }1395}139613971398class NFTGroup extends NFTnRFT {1399 /**1400 * Get collection object1401 * @param collectionId ID of collection1402 * @example getCollectionObject(2);1403 * @returns instance of UniqueNFTCollection1404 */1405 getCollectionObject(collectionId: number): UniqueNFTCollection {1406 return new UniqueNFTCollection(collectionId, this.helper);1407 }14081409 /**1410 * Get token object1411 * @param collectionId ID of collection1412 * @param tokenId ID of token1413 * @example getTokenObject(10, 5);1414 * @returns instance of UniqueNFTToken1415 */1416 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1417 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1418 }14191420 /**1421 * Get token's owner1422 * @param collectionId ID of collection1423 * @param tokenId ID of token1424 * @param blockHashAt optionally query the data at the block with this hash1425 * @example getTokenOwner(10, 5);1426 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1427 */1428 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1429 let owner;1430 if (typeof blockHashAt === 'undefined') {1431 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1432 } else {1433 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1434 }1435 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1436 }14371438 /**1439 * Is token approved to transfer1440 * @param collectionId ID of collection1441 * @param tokenId ID of token1442 * @param toAccountObj address to be approved1443 * @returns ```true``` if extrinsic success, otherwise ```false```1444 */1445 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1446 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1447 }14481449 /**1450 * Changes the owner of the token.1451 *1452 * @param signer keyring of signer1453 * @param collectionId ID of collection1454 * @param tokenId ID of token1455 * @param addressObj address of a new owner1456 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1457 * @returns ```true``` if extrinsic success, otherwise ```false```1458 */1459 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1460 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1461 }14621463 /**1464 *1465 * Change ownership of a NFT on behalf of the owner.1466 *1467 * @param signer keyring of signer1468 * @param collectionId ID of collection1469 * @param tokenId ID of token1470 * @param fromAddressObj address on behalf of which the token will be sent1471 * @param toAddressObj new token owner1472 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1473 * @returns ```true``` if extrinsic success, otherwise ```false```1474 */1475 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1476 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1477 }14781479 /**1480 * Recursively find the address that owns the token1481 * @param collectionId ID of collection1482 * @param tokenId ID of token1483 * @param blockHashAt1484 * @example getTokenTopmostOwner(10, 5);1485 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1486 */1487 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1488 let owner;1489 if (typeof blockHashAt === 'undefined') {1490 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1491 } else {1492 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1493 }14941495 if (owner === null) return null;14961497 return owner.toHuman();1498 }14991500 /**1501 * Get tokens nested in the provided token1502 * @param collectionId ID of collection1503 * @param tokenId ID of token1504 * @param blockHashAt optionally query the data at the block with this hash1505 * @example getTokenChildren(10, 5);1506 * @returns tokens whose depth of nesting is <= 51507 */1508 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1509 let children;1510 if(typeof blockHashAt === 'undefined') {1511 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1512 } else {1513 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1514 }15151516 return children.toJSON().map((x: any) => {1517 return {collectionId: x.collection, tokenId: x.token};1518 });1519 }15201521 /**1522 * Nest one token into another1523 * @param signer keyring of signer1524 * @param tokenObj token to be nested1525 * @param rootTokenObj token to be parent1526 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1527 * @returns ```true``` if extrinsic success, otherwise ```false```1528 */1529 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1530 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1531 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1532 if(!result) {1533 throw Error('Unable to nest token!');1534 }1535 return result;1536 }15371538 /**1539 * Remove token from nested state1540 * @param signer keyring of signer1541 * @param tokenObj token to unnest1542 * @param rootTokenObj parent of a token1543 * @param toAddressObj address of a new token owner1544 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1545 * @returns ```true``` if extrinsic success, otherwise ```false```1546 */1547 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1548 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1549 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1550 if(!result) {1551 throw Error('Unable to unnest token!');1552 }1553 return result;1554 }15551556 /**1557 * Mint new collection1558 * @param signer keyring of signer1559 * @param collectionOptions Collection options1560 * @example1561 * mintCollection(aliceKeyring, {1562 * name: 'New',1563 * description: 'New collection',1564 * tokenPrefix: 'NEW',1565 * })1566 * @returns object of the created collection1567 */1568 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1569 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1570 }15711572 /**1573 * Mint new token1574 * @param signer keyring of signer1575 * @param data token data1576 * @returns created token object1577 */1578 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1579 const creationResult = await this.helper.executeExtrinsic(1580 signer,1581 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1582 nft: {1583 properties: data.properties,1584 },1585 }],1586 true,1587 );1588 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1589 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1590 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1591 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1592 }15931594 /**1595 * Mint multiple NFT tokens1596 * @param signer keyring of signer1597 * @param collectionId ID of collection1598 * @param tokens array of tokens with owner and properties1599 * @example1600 * mintMultipleTokens(aliceKeyring, 10, [{1601 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1602 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1603 * },{1604 * owner: {Ethereum: "0x9F0583DbB855d..."},1605 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1606 * }]);1607 * @returns ```true``` if extrinsic success, otherwise ```false```1608 */1609 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1610 const creationResult = await this.helper.executeExtrinsic(1611 signer,1612 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1613 true,1614 );1615 const collection = this.getCollectionObject(collectionId);1616 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1617 }16181619 /**1620 * Mint multiple NFT tokens with one owner1621 * @param signer keyring of signer1622 * @param collectionId ID of collection1623 * @param owner tokens owner1624 * @param tokens array of tokens with owner and properties1625 * @example1626 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1627 * properties: [{1628 * key: "gender",1629 * value: "female",1630 * },{1631 * key: "age",1632 * value: "33",1633 * }],1634 * }]);1635 * @returns array of newly created tokens1636 */1637 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1638 const rawTokens = [];1639 for (const token of tokens) {1640 const raw = {NFT: {properties: token.properties}};1641 rawTokens.push(raw);1642 }1643 const creationResult = await this.helper.executeExtrinsic(1644 signer,1645 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1646 true,1647 );1648 const collection = this.getCollectionObject(collectionId);1649 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1650 }16511652 /**1653 * Set, change, or remove approved address to transfer the ownership of the NFT.1654 *1655 * @param signer keyring of signer1656 * @param collectionId ID of collection1657 * @param tokenId ID of token1658 * @param toAddressObj address to approve1659 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1660 * @returns ```true``` if extrinsic success, otherwise ```false```1661 */1662 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1663 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1664 }1665}166616671668class RFTGroup extends NFTnRFT {1669 /**1670 * Get collection object1671 * @param collectionId ID of collection1672 * @example getCollectionObject(2);1673 * @returns instance of UniqueRFTCollection1674 */1675 getCollectionObject(collectionId: number): UniqueRFTCollection {1676 return new UniqueRFTCollection(collectionId, this.helper);1677 }16781679 /**1680 * Get token object1681 * @param collectionId ID of collection1682 * @param tokenId ID of token1683 * @example getTokenObject(10, 5);1684 * @returns instance of UniqueNFTToken1685 */1686 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1687 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1688 }16891690 /**1691 * Get top 10 token owners with the largest number of pieces1692 * @param collectionId ID of collection1693 * @param tokenId ID of token1694 * @example getTokenTop10Owners(10, 5);1695 * @returns array of top 10 owners1696 */1697 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1698 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1699 }17001701 /**1702 * Get number of pieces owned by address1703 * @param collectionId ID of collection1704 * @param tokenId ID of token1705 * @param addressObj address token owner1706 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1707 * @returns number of pieces ownerd by address1708 */1709 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1710 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1711 }17121713 /**1714 * Transfer pieces of token to another address1715 * @param signer keyring of signer1716 * @param collectionId ID of collection1717 * @param tokenId ID of token1718 * @param addressObj address of a new owner1719 * @param amount number of pieces to be transfered1720 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1721 * @returns ```true``` if extrinsic success, otherwise ```false```1722 */1723 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1724 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1725 }17261727 /**1728 * Change ownership of some pieces of RFT on behalf of the owner.1729 * @param signer keyring of signer1730 * @param collectionId ID of collection1731 * @param tokenId ID of token1732 * @param fromAddressObj address on behalf of which the token will be sent1733 * @param toAddressObj new token owner1734 * @param amount number of pieces to be transfered1735 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1736 * @returns ```true``` if extrinsic success, otherwise ```false```1737 */1738 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1739 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1740 }17411742 /**1743 * Mint new collection1744 * @param signer keyring of signer1745 * @param collectionOptions Collection options1746 * @example1747 * mintCollection(aliceKeyring, {1748 * name: 'New',1749 * description: 'New collection',1750 * tokenPrefix: 'NEW',1751 * })1752 * @returns object of the created collection1753 */1754 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1755 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1756 }17571758 /**1759 * Mint new token1760 * @param signer keyring of signer1761 * @param data token data1762 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1763 * @returns created token object1764 */1765 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1766 const creationResult = await this.helper.executeExtrinsic(1767 signer,1768 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1769 refungible: {1770 pieces: data.pieces,1771 properties: data.properties,1772 },1773 }],1774 true,1775 );1776 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1777 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1778 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1779 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1780 }17811782 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1783 throw Error('Not implemented');1784 const creationResult = await this.helper.executeExtrinsic(1785 signer,1786 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1787 true, // `Unable to mint RFT tokens for ${label}`,1788 );1789 const collection = this.getCollectionObject(collectionId);1790 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1791 }17921793 /**1794 * Mint multiple RFT tokens with one owner1795 * @param signer keyring of signer1796 * @param collectionId ID of collection1797 * @param owner tokens owner1798 * @param tokens array of tokens with properties and pieces1799 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1800 * @returns array of newly created RFT tokens1801 */1802 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1803 const rawTokens = [];1804 for (const token of tokens) {1805 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1806 rawTokens.push(raw);1807 }1808 const creationResult = await this.helper.executeExtrinsic(1809 signer,1810 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1811 true,1812 );1813 const collection = this.getCollectionObject(collectionId);1814 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1815 }18161817 /**1818 * Destroys a concrete instance of RFT.1819 * @param signer keyring of signer1820 * @param collectionId ID of collection1821 * @param tokenId ID of token1822 * @param amount number of pieces to be burnt1823 * @example burnToken(aliceKeyring, 10, 5);1824 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1825 */1826 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1827 return await super.burnToken(signer, collectionId, tokenId, amount);1828 }18291830 /**1831 * Destroys a concrete instance of RFT on behalf of the owner.1832 * @param signer keyring of signer1833 * @param collectionId ID of collection1834 * @param tokenId ID of token1835 * @param fromAddressObj address on behalf of which the token will be burnt1836 * @param amount number of pieces to be burnt1837 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1838 * @returns ```true``` if extrinsic success, otherwise ```false```1839 */1840 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1841 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1842 }18431844 /**1845 * Set, change, or remove approved address to transfer the ownership of the RFT.1846 *1847 * @param signer keyring of signer1848 * @param collectionId ID of collection1849 * @param tokenId ID of token1850 * @param toAddressObj address to approve1851 * @param amount number of pieces to be approved1852 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1853 * @returns true if the token success, otherwise false1854 */1855 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1856 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1857 }18581859 /**1860 * Get total number of pieces1861 * @param collectionId ID of collection1862 * @param tokenId ID of token1863 * @example getTokenTotalPieces(10, 5);1864 * @returns number of pieces1865 */1866 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1867 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1868 }18691870 /**1871 * Change number of token pieces. Signer must be the owner of all token pieces.1872 * @param signer keyring of signer1873 * @param collectionId ID of collection1874 * @param tokenId ID of token1875 * @param amount new number of pieces1876 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1877 * @returns true if the repartion was success, otherwise false1878 */1879 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1880 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1881 const repartitionResult = await this.helper.executeExtrinsic(1882 signer,1883 'api.tx.unique.repartition', [collectionId, tokenId, amount],1884 true,1885 );1886 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1887 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1888 }1889}189018911892class FTGroup extends CollectionGroup {1893 /**1894 * Get collection object1895 * @param collectionId ID of collection1896 * @example getCollectionObject(2);1897 * @returns instance of UniqueFTCollection1898 */1899 getCollectionObject(collectionId: number): UniqueFTCollection {1900 return new UniqueFTCollection(collectionId, this.helper);1901 }19021903 /**1904 * Mint new fungible collection1905 * @param signer keyring of signer1906 * @param collectionOptions Collection options1907 * @param decimalPoints number of token decimals1908 * @example1909 * mintCollection(aliceKeyring, {1910 * name: 'New',1911 * description: 'New collection',1912 * tokenPrefix: 'NEW',1913 * }, 18)1914 * @returns newly created fungible collection1915 */1916 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1917 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1918 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1919 collectionOptions.mode = {fungible: decimalPoints};1920 for (const key of ['name', 'description', 'tokenPrefix']) {1921 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);1922 }1923 const creationResult = await this.helper.executeExtrinsic(1924 signer,1925 'api.tx.unique.createCollectionEx', [collectionOptions],1926 true,1927 );1928 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1929 }19301931 /**1932 * Mint tokens1933 * @param signer keyring of signer1934 * @param collectionId ID of collection1935 * @param owner address owner of new tokens1936 * @param amount amount of tokens to be meanted1937 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1938 * @returns ```true``` if extrinsic success, otherwise ```false```1939 */1940 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1941 const creationResult = await this.helper.executeExtrinsic(1942 signer,1943 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1944 fungible: {1945 value: amount,1946 },1947 }],1948 true, // `Unable to mint fungible tokens for ${label}`,1949 );1950 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1951 }19521953 /**1954 * Mint multiple Fungible tokens with one owner1955 * @param signer keyring of signer1956 * @param collectionId ID of collection1957 * @param owner tokens owner1958 * @param tokens array of tokens with properties and pieces1959 * @returns ```true``` if extrinsic success, otherwise ```false```1960 */1961 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1962 const rawTokens = [];1963 for (const token of tokens) {1964 const raw = {Fungible: {Value: token.value}};1965 rawTokens.push(raw);1966 }1967 const creationResult = await this.helper.executeExtrinsic(1968 signer,1969 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1970 true,1971 );1972 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1973 }19741975 /**1976 * Get the top 10 owners with the largest balance for the Fungible collection1977 * @param collectionId ID of collection1978 * @example getTop10Owners(10);1979 * @returns array of ```ICrossAccountId```1980 */1981 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1982 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1983 }19841985 /**1986 * Get account balance1987 * @param collectionId ID of collection1988 * @param addressObj address of owner1989 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1990 * @returns amount of fungible tokens owned by address1991 */1992 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1993 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1994 }19951996 /**1997 * Transfer tokens to address1998 * @param signer keyring of signer1999 * @param collectionId ID of collection2000 * @param toAddressObj address recipient2001 * @param amount amount of tokens to be sent2002 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2003 * @returns ```true``` if extrinsic success, otherwise ```false```2004 */2005 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2006 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2007 }20082009 /**2010 * Transfer some tokens on behalf of the owner.2011 * @param signer keyring of signer2012 * @param collectionId ID of collection2013 * @param fromAddressObj address on behalf of which tokens will be sent2014 * @param toAddressObj address where token to be sent2015 * @param amount number of tokens to be sent2016 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2017 * @returns ```true``` if extrinsic success, otherwise ```false```2018 */2019 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2020 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2021 }20222023 /**2024 * Destroy some amount of tokens2025 * @param signer keyring of signer2026 * @param collectionId ID of collection2027 * @param amount amount of tokens to be destroyed2028 * @example burnTokens(aliceKeyring, 10, 1000n);2029 * @returns ```true``` if extrinsic success, otherwise ```false```2030 */2031 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2032 return await super.burnToken(signer, collectionId, 0, amount);2033 }20342035 /**2036 * Burn some tokens on behalf of the owner.2037 * @param signer keyring of signer2038 * @param collectionId ID of collection2039 * @param fromAddressObj address on behalf of which tokens will be burnt2040 * @param amount amount of tokens to be burnt2041 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2042 * @returns ```true``` if extrinsic success, otherwise ```false```2043 */2044 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2045 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2046 }20472048 /**2049 * Get total collection supply2050 * @param collectionId2051 * @returns2052 */2053 async getTotalPieces(collectionId: number): Promise<bigint> {2054 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2055 }20562057 /**2058 * Set, change, or remove approved address to transfer tokens.2059 *2060 * @param signer keyring of signer2061 * @param collectionId ID of collection2062 * @param toAddressObj address to be approved2063 * @param amount amount of tokens to be approved2064 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2065 * @returns ```true``` if extrinsic success, otherwise ```false```2066 */2067 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2068 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2069 }20702071 /**2072 * Get amount of fungible tokens approved to transfer2073 * @param collectionId ID of collection2074 * @param fromAddressObj owner of tokens2075 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2076 * @returns number of tokens approved for the transfer2077 */2078 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2079 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2080 }2081}208220832084class ChainGroup extends HelperGroup<ChainHelperBase> {2085 /**2086 * Get system properties of a chain2087 * @example getChainProperties();2088 * @returns ss58Format, token decimals, and token symbol2089 */2090 getChainProperties(): IChainProperties {2091 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2092 return {2093 ss58Format: properties.ss58Format.toJSON(),2094 tokenDecimals: properties.tokenDecimals.toJSON(),2095 tokenSymbol: properties.tokenSymbol.toJSON(),2096 };2097 }20982099 /**2100 * Get chain header2101 * @example getLatestBlockNumber();2102 * @returns the number of the last block2103 */2104 async getLatestBlockNumber(): Promise<number> {2105 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2106 }21072108 /**2109 * Get block hash by block number2110 * @param blockNumber number of block2111 * @example getBlockHashByNumber(12345);2112 * @returns hash of a block2113 */2114 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2115 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2116 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2117 return blockHash;2118 }21192120 // TODO add docs2121 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2122 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2123 if (!blockHash) return null;2124 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2125 }21262127 /**2128 * Get account nonce2129 * @param address substrate address2130 * @example getNonce("5GrwvaEF5zXb26Fz...");2131 * @returns number, account's nonce2132 */2133 async getNonce(address: TSubstrateAccount): Promise<number> {2134 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2135 }2136}21372138class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2139 /**2140 * Get substrate address balance2141 * @param address substrate address2142 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2143 * @returns amount of tokens on address2144 */2145 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2146 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2147 }21482149 /**2150 * Transfer tokens to substrate address2151 * @param signer keyring of signer2152 * @param address substrate address of a recipient2153 * @param amount amount of tokens to be transfered2154 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2155 * @returns ```true``` if extrinsic success, otherwise ```false```2156 */2157 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2158 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}`*/);21592160 let transfer = {from: null, to: null, amount: 0n} as any;2161 result.result.events.forEach(({event: {data, method, section}}) => {2162 if ((section === 'balances') && (method === 'Transfer')) {2163 transfer = {2164 from: this.helper.address.normalizeSubstrate(data[0]),2165 to: this.helper.address.normalizeSubstrate(data[1]),2166 amount: BigInt(data[2]),2167 };2168 }2169 });2170 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2171 && this.helper.address.normalizeSubstrate(address) === transfer.to 2172 && BigInt(amount) === transfer.amount;2173 return isSuccess;2174 }21752176 /**2177 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2178 * @param address substrate address2179 * @returns2180 */2181 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2182 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2183 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2184 }2185}21862187class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2188 /**2189 * Get ethereum address balance2190 * @param address ethereum address2191 * @example getEthereum("0x9F0583DbB855d...")2192 * @returns amount of tokens on address2193 */2194 async getEthereum(address: TEthereumAccount): Promise<bigint> {2195 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2196 }21972198 /**2199 * Transfer tokens to address2200 * @param signer keyring of signer2201 * @param address Ethereum address of a recipient2202 * @param amount amount of tokens to be transfered2203 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2204 * @returns ```true``` if extrinsic success, otherwise ```false```2205 */2206 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2207 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);22082209 let transfer = {from: null, to: null, amount: 0n} as any;2210 result.result.events.forEach(({event: {data, method, section}}) => {2211 if ((section === 'balances') && (method === 'Transfer')) {2212 transfer = {2213 from: data[0].toString(),2214 to: data[1].toString(),2215 amount: BigInt(data[2]),2216 };2217 }2218 });2219 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from 2220 && address === transfer.to 2221 && BigInt(amount) === transfer.amount;2222 return isSuccess;2223 }2224}22252226class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2227 subBalanceGroup: SubstrateBalanceGroup<T>;2228 ethBalanceGroup: EthereumBalanceGroup<T>;22292230 constructor(helper: T) {2231 super(helper);2232 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2233 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2234 }22352236 getCollectionCreationPrice(): bigint {2237 return 2n * this.getOneTokenNominal();2238 }2239 /**2240 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2241 * @example getOneTokenNominal()2242 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2243 */2244 getOneTokenNominal(): bigint {2245 const chainProperties = this.helper.chain.getChainProperties();2246 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2247 }22482249 /**2250 * Get substrate address balance2251 * @param address substrate address2252 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2253 * @returns amount of tokens on address2254 */2255 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2256 return this.subBalanceGroup.getSubstrate(address);2257 }22582259 /**2260 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2261 * @param address substrate address2262 * @returns2263 */2264 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2265 return this.subBalanceGroup.getSubstrateFull(address);2266 }22672268 /**2269 * Get ethereum address balance2270 * @param address ethereum address2271 * @example getEthereum("0x9F0583DbB855d...")2272 * @returns amount of tokens on address2273 */2274 async getEthereum(address: TEthereumAccount): Promise<bigint> {2275 return this.ethBalanceGroup.getEthereum(address);2276 }22772278 /**2279 * Transfer tokens to substrate address2280 * @param signer keyring of signer2281 * @param address substrate address of a recipient2282 * @param amount amount of tokens to be transfered2283 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2284 * @returns ```true``` if extrinsic success, otherwise ```false```2285 */2286 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2287 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2288 }2289}22902291class AddressGroup extends HelperGroup<ChainHelperBase> {2292 /**2293 * Normalizes the address to the specified ss58 format, by default ```42```.2294 * @param address substrate address2295 * @param ss58Format format for address conversion, by default ```42```2296 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2297 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2298 */2299 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2300 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2301 }23022303 /**2304 * Get address in the connected chain format2305 * @param address substrate address2306 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2307 * @returns address in chain format2308 */2309 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2310 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2311 }23122313 /**2314 * Get substrate mirror of an ethereum address2315 * @param ethAddress ethereum address2316 * @param toChainFormat false for normalized account2317 * @example ethToSubstrate('0x9F0583DbB855d...')2318 * @returns substrate mirror of a provided ethereum address2319 */2320 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2321 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2322 }23232324 /**2325 * Get ethereum mirror of a substrate address2326 * @param subAddress substrate account2327 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2328 * @returns ethereum mirror of a provided substrate address2329 */2330 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2331 return CrossAccountId.translateSubToEth(subAddress);2332 }23332334 paraSiblingSovereignAccount(paraid: number) {2335 // We are getting a *sibling* parachain sovereign account,2336 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2337 const siblingPrefix = '0x7369626c';23382339 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2340 const suffix = '000000000000000000000000000000000000000000000000';23412342 return siblingPrefix + encodedParaId + suffix;2343 }2344}23452346class StakingGroup extends HelperGroup<UniqueHelper> {2347 /**2348 * Stake tokens for App Promotion2349 * @param signer keyring of signer2350 * @param amountToStake amount of tokens to stake2351 * @param label extra label for log2352 * @returns2353 */2354 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2355 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2356 const _stakeResult = await this.helper.executeExtrinsic(2357 signer, 'api.tx.appPromotion.stake',2358 [amountToStake], true,2359 );2360 // TODO extract info from stakeResult2361 return true;2362 }23632364 /**2365 * Unstake tokens for App Promotion2366 * @param signer keyring of signer2367 * @param amountToUnstake amount of tokens to unstake2368 * @param label extra label for log2369 * @returns block number where balances will be unlocked2370 */2371 async unstake(signer: TSigner, label?: string): Promise<number> {2372 if(typeof label === 'undefined') label = `${signer.address}`;2373 const _unstakeResult = await this.helper.executeExtrinsic(2374 signer, 'api.tx.appPromotion.unstake',2375 [], true,2376 );2377 // TODO extract block number fron events2378 return 1;2379 }23802381 /**2382 * Get total staked amount for address2383 * @param address substrate or ethereum address2384 * @returns total staked amount2385 */2386 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2387 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2388 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2389 }23902391 /**2392 * Get total staked per block2393 * @param address substrate or ethereum address2394 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2395 */2396 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2397 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2398 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2399 return { 2400 block: block.toBigInt(),2401 amount: amount.toBigInt(),2402 };2403 });2404 }24052406 /**2407 * Get total pending unstake amount for address2408 * @param address substrate or ethereum address2409 * @returns total pending unstake amount2410 */2411 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2412 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2413 }24142415 /**2416 * Get pending unstake amount per block for address2417 * @param address substrate or ethereum address2418 * @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 block2419 */2420 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2421 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2422 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2423 return {2424 block: block.toBigInt(),2425 amount: amount.toBigInt(),2426 };2427 });2428 return result;2429 }2430}24312432class SchedulerGroup extends HelperGroup<UniqueHelper> {2433 constructor(helper: UniqueHelper) {2434 super(helper);2435 }24362437 async cancelScheduled(signer: TSigner, scheduledId: string) {2438 return this.helper.executeExtrinsic(2439 signer,2440 'api.tx.scheduler.cancelNamed',2441 [scheduledId],2442 true,2443 );2444 }24452446 async changePriority(signer: TSigner, scheduledId: string, priority: number) {2447 return this.helper.executeExtrinsic(2448 signer,2449 'api.tx.scheduler.changeNamedPriority',2450 [scheduledId, priority],2451 true,2452 );2453 }24542455 scheduleAt<T extends UniqueHelper>(2456 scheduledId: string,2457 executionBlockNumber: number,2458 options: ISchedulerOptions = {},2459 ) {2460 return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2461 }24622463 scheduleAfter<T extends UniqueHelper>(2464 scheduledId: string,2465 blocksBeforeExecution: number,2466 options: ISchedulerOptions = {},2467 ) {2468 return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2469 }24702471 schedule<T extends UniqueHelper>(2472 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2473 scheduledId: string,2474 blocksNum: number,2475 options: ISchedulerOptions = {},2476 ) {2477 // eslint-disable-next-line @typescript-eslint/naming-convention2478 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2479 return this.helper.clone(ScheduledHelperType, {2480 scheduleFn,2481 scheduledId,2482 blocksNum,2483 options,2484 }) as T;2485 }2486}24872488class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2489 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2490 await this.helper.executeExtrinsic(2491 signer,2492 'api.tx.foreignAssets.registerForeignAsset',2493 [ownerAddress, location, metadata],2494 true,2495 );2496 }24972498 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2499 await this.helper.executeExtrinsic(2500 signer,2501 'api.tx.foreignAssets.updateForeignAsset',2502 [foreignAssetId, location, metadata],2503 true,2504 );2505 }2506}25072508class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2509 palletName: string;25102511 constructor(helper: T, palletName: string) {2512 super(helper);25132514 this.palletName = palletName;2515 }25162517 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2518 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2519 }2520}25212522class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2523 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2524 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2525 }25262527 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2528 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2529 }25302531 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2532 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2533 }2534}25352536class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2537 async accounts(address: string, currencyId: any) {2538 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2539 return BigInt(free);2540 }2541}25422543class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2544 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2545 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2546 }25472548 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2549 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2550 }25512552 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2553 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2554 }25552556 async account(assetId: string | number, address: string) {2557 const accountAsset = (2558 await this.helper.callRpc('api.query.assets.account', [assetId, address])2559 ).toJSON()! as any;25602561 if (accountAsset !== null) {2562 return BigInt(accountAsset['balance']);2563 } else {2564 return null;2565 }2566 }2567}25682569class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2570 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2571 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2572 }2573}25742575class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2576 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2577 const apiPrefix = 'api.tx.assetManager.';25782579 const registerTx = this.helper.constructApiCall(2580 apiPrefix + 'registerForeignAsset',2581 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2582 );25832584 const setUnitsTx = this.helper.constructApiCall(2585 apiPrefix + 'setAssetUnitsPerSecond',2586 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2587 );25882589 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2590 const encodedProposal = batchCall?.method.toHex() || '';2591 return encodedProposal;2592 }25932594 async assetTypeId(location: any) {2595 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2596 }2597}25982599class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2600 async notePreimage(signer: TSigner, encodedProposal: string) {2601 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2602 }26032604 externalProposeMajority(proposalHash: string) {2605 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2606 }26072608 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2609 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2610 }26112612 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2613 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2614 }2615}26162617class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2618 collective: string;26192620 constructor(helper: MoonbeamHelper, collective: string) {2621 super(helper);26222623 this.collective = collective;2624 }26252626 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2627 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2628 }26292630 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2631 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2632 }26332634 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2635 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2636 }26372638 async proposalCount() {2639 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2640 }2641}26422643export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2644export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;26452646export class UniqueHelper extends ChainHelperBase {2647 balance: BalanceGroup<UniqueHelper>;2648 collection: CollectionGroup;2649 nft: NFTGroup;2650 rft: RFTGroup;2651 ft: FTGroup;2652 staking: StakingGroup;2653 scheduler: SchedulerGroup;2654 foreignAssets: ForeignAssetsGroup;2655 xcm: XcmGroup<UniqueHelper>;2656 xTokens: XTokensGroup<UniqueHelper>;2657 tokens: TokensGroup<UniqueHelper>;26582659 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2660 super(logger, options.helperBase ?? UniqueHelper);26612662 this.balance = new BalanceGroup(this);2663 this.collection = new CollectionGroup(this);2664 this.nft = new NFTGroup(this);2665 this.rft = new RFTGroup(this);2666 this.ft = new FTGroup(this);2667 this.staking = new StakingGroup(this);2668 this.scheduler = new SchedulerGroup(this);2669 this.foreignAssets = new ForeignAssetsGroup(this);2670 this.xcm = new XcmGroup(this, 'polkadotXcm');2671 this.xTokens = new XTokensGroup(this);2672 this.tokens = new TokensGroup(this);2673 }26742675 getSudo<T extends UniqueHelper>() {2676 // eslint-disable-next-line @typescript-eslint/naming-convention2677 const SudoHelperType = SudoHelper(this.helperBase);2678 return this.clone(SudoHelperType) as T;2679 }2680}26812682export class XcmChainHelper extends ChainHelperBase {2683 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2684 const wsProvider = new WsProvider(wsEndpoint);2685 this.api = new ApiPromise({2686 provider: wsProvider,2687 });2688 await this.api.isReadyOrError;2689 this.network = await UniqueHelper.detectNetwork(this.api);2690 }2691}26922693export class RelayHelper extends XcmChainHelper {2694 xcm: XcmGroup<RelayHelper>;26952696 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2697 super(logger, options.helperBase ?? RelayHelper);26982699 this.xcm = new XcmGroup(this, 'xcmPallet');2700 }2701}27022703export class WestmintHelper extends XcmChainHelper {2704 balance: SubstrateBalanceGroup<WestmintHelper>;2705 xcm: XcmGroup<WestmintHelper>;2706 assets: AssetsGroup<WestmintHelper>;2707 xTokens: XTokensGroup<WestmintHelper>;27082709 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2710 super(logger, options.helperBase ?? WestmintHelper);27112712 this.balance = new SubstrateBalanceGroup(this);2713 this.xcm = new XcmGroup(this, 'polkadotXcm');2714 this.assets = new AssetsGroup(this);2715 this.xTokens = new XTokensGroup(this);2716 }2717}27182719export class MoonbeamHelper extends XcmChainHelper {2720 balance: EthereumBalanceGroup<MoonbeamHelper>;2721 assetManager: MoonbeamAssetManagerGroup;2722 assets: AssetsGroup<MoonbeamHelper>;2723 xTokens: XTokensGroup<MoonbeamHelper>;2724 democracy: MoonbeamDemocracyGroup;2725 collective: {2726 council: MoonbeamCollectiveGroup,2727 techCommittee: MoonbeamCollectiveGroup,2728 };27292730 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2731 super(logger, options.helperBase ?? MoonbeamHelper);27322733 this.balance = new EthereumBalanceGroup(this);2734 this.assetManager = new MoonbeamAssetManagerGroup(this);2735 this.assets = new AssetsGroup(this);2736 this.xTokens = new XTokensGroup(this);2737 this.democracy = new MoonbeamDemocracyGroup(this);2738 this.collective = {2739 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2740 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2741 };2742 }2743}27442745export class AcalaHelper extends XcmChainHelper {2746 balance: SubstrateBalanceGroup<AcalaHelper>;2747 assetRegistry: AcalaAssetRegistryGroup;2748 xTokens: XTokensGroup<AcalaHelper>;2749 tokens: TokensGroup<AcalaHelper>;27502751 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2752 super(logger, options.helperBase ?? AcalaHelper);27532754 this.balance = new SubstrateBalanceGroup(this);2755 this.assetRegistry = new AcalaAssetRegistryGroup(this);2756 this.xTokens = new XTokensGroup(this);2757 this.tokens = new TokensGroup(this);2758 }27592760 getSudo<T extends AcalaHelper>() {2761 // eslint-disable-next-line @typescript-eslint/naming-convention2762 const SudoHelperType = SudoHelper(this.helperBase);2763 return this.clone(SudoHelperType) as T;2764 }2765}27662767// eslint-disable-next-line @typescript-eslint/naming-convention2768function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2769 return class extends Base {2770 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2771 scheduledId: string;2772 blocksNum: number;2773 options: ISchedulerOptions;27742775 constructor(...args: any[]) {2776 const logger = args[0] as ILogger;2777 const options = args[1] as {2778 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2779 scheduledId: string,2780 blocksNum: number,2781 options: ISchedulerOptions2782 };27832784 super(logger);27852786 this.scheduleFn = options.scheduleFn;2787 this.scheduledId = options.scheduledId;2788 this.blocksNum = options.blocksNum;2789 this.options = options.options;2790 }27912792 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2793 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2794 const extrinsic = 'api.tx.scheduler.' + this.scheduleFn;27952796 return super.executeExtrinsic(2797 sender,2798 extrinsic,2799 [2800 this.scheduledId,2801 this.blocksNum,2802 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2803 this.options.priority ?? null,2804 {Value: scheduledTx},2805 ],2806 expectSuccess,2807 );2808 }2809 };2810}28112812// eslint-disable-next-line @typescript-eslint/naming-convention2813function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2814 return class extends Base {2815 constructor(...args: any[]) {2816 super(...args);2817 }28182819 executeExtrinsic (2820 sender: IKeyringPair,2821 extrinsic: string,2822 params: any[],2823 expectSuccess?: boolean,2824 ): Promise<ITransactionResult> {2825 const call = this.constructApiCall(extrinsic, params);28262827 return super.executeExtrinsic(2828 sender,2829 'api.tx.sudo.sudo',2830 [call],2831 expectSuccess,2832 );2833 }2834 };2835}28362837export class UniqueBaseCollection {2838 helper: UniqueHelper;2839 collectionId: number;28402841 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2842 this.collectionId = collectionId;2843 this.helper = uniqueHelper;2844 }28452846 async getData() {2847 return await this.helper.collection.getData(this.collectionId);2848 }28492850 async getLastTokenId() {2851 return await this.helper.collection.getLastTokenId(this.collectionId);2852 }28532854 async doesTokenExist(tokenId: number) {2855 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2856 }28572858 async getAdmins() {2859 return await this.helper.collection.getAdmins(this.collectionId);2860 }28612862 async getAllowList() {2863 return await this.helper.collection.getAllowList(this.collectionId);2864 }28652866 async getEffectiveLimits() {2867 return await this.helper.collection.getEffectiveLimits(this.collectionId);2868 }28692870 async getProperties(propertyKeys?: string[] | null) {2871 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2872 }28732874 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2875 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2876 }28772878 async getOptions() {2879 return await this.helper.collection.getCollectionOptions(this.collectionId);2880 }28812882 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2883 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2884 }28852886 async confirmSponsorship(signer: TSigner) {2887 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2888 }28892890 async removeSponsor(signer: TSigner) {2891 return await this.helper.collection.removeSponsor(signer, this.collectionId);2892 }28932894 async setLimits(signer: TSigner, limits: ICollectionLimits) {2895 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2896 }28972898 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2899 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2900 }29012902 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2903 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2904 }29052906 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2907 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2908 }29092910 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2911 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2912 }29132914 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2915 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2916 }29172918 async setProperties(signer: TSigner, properties: IProperty[]) {2919 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2920 }29212922 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2923 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2924 }29252926 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2927 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2928 }29292930 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2931 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2932 }29332934 async disableNesting(signer: TSigner) {2935 return await this.helper.collection.disableNesting(signer, this.collectionId);2936 }29372938 async burn(signer: TSigner) {2939 return await this.helper.collection.burn(signer, this.collectionId);2940 }29412942 scheduleAt<T extends UniqueHelper>(2943 scheduledId: string,2944 executionBlockNumber: number,2945 options: ISchedulerOptions = {},2946 ) {2947 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2948 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2949 }29502951 scheduleAfter<T extends UniqueHelper>(2952 scheduledId: string,2953 blocksBeforeExecution: number,2954 options: ISchedulerOptions = {},2955 ) {2956 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2957 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2958 }29592960 getSudo<T extends UniqueHelper>() {2961 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2962 }2963}296429652966export class UniqueNFTCollection extends UniqueBaseCollection {2967 getTokenObject(tokenId: number) {2968 return new UniqueNFToken(tokenId, this);2969 }29702971 async getTokensByAddress(addressObj: ICrossAccountId) {2972 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2973 }29742975 async getToken(tokenId: number, blockHashAt?: string) {2976 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2977 }29782979 async getTokenOwner(tokenId: number, blockHashAt?: string) {2980 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2981 }29822983 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2984 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2985 }29862987 async getTokenChildren(tokenId: number, blockHashAt?: string) {2988 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2989 }29902991 async getPropertyPermissions(propertyKeys: string[] | null = null) {2992 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2993 }29942995 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2996 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2997 }29982999 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3000 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3001 }30023003 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3004 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3005 }30063007 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3008 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3009 }30103011 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3012 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3013 }30143015 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3016 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3017 }30183019 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3020 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3021 }30223023 async burnToken(signer: TSigner, tokenId: number) {3024 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3025 }30263027 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3028 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3029 }30303031 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3032 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3033 }30343035 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3036 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3037 }30383039 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3040 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3041 }30423043 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3044 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3045 }30463047 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3048 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3049 }30503051 scheduleAt<T extends UniqueHelper>(3052 scheduledId: string,3053 executionBlockNumber: number,3054 options: ISchedulerOptions = {},3055 ) {3056 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3057 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3058 }30593060 scheduleAfter<T extends UniqueHelper>(3061 scheduledId: string,3062 blocksBeforeExecution: number,3063 options: ISchedulerOptions = {},3064 ) {3065 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3066 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3067 }30683069 getSudo<T extends UniqueHelper>() {3070 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3071 }3072}307330743075export class UniqueRFTCollection extends UniqueBaseCollection {3076 getTokenObject(tokenId: number) {3077 return new UniqueRFToken(tokenId, this);3078 }30793080 async getToken(tokenId: number, blockHashAt?: string) {3081 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3082 }30833084 async getTokensByAddress(addressObj: ICrossAccountId) {3085 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3086 }30873088 async getTop10TokenOwners(tokenId: number) {3089 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3090 }30913092 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3093 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3094 }30953096 async getTokenTotalPieces(tokenId: number) {3097 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3098 }30993100 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3101 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3102 }31033104 async getPropertyPermissions(propertyKeys: string[] | null = null) {3105 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3106 }31073108 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3109 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3110 }31113112 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3113 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3114 }31153116 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3117 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3118 }31193120 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3121 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3122 }31233124 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3125 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3126 }31273128 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3129 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3130 }31313132 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3133 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3134 }31353136 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3137 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3138 }31393140 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3141 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3142 }31433144 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3145 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3146 }31473148 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3149 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3150 }31513152 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3153 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3154 }31553156 scheduleAt<T extends UniqueHelper>(3157 scheduledId: string,3158 executionBlockNumber: number,3159 options: ISchedulerOptions = {},3160 ) {3161 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3162 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3163 }31643165 scheduleAfter<T extends UniqueHelper>(3166 scheduledId: string,3167 blocksBeforeExecution: number,3168 options: ISchedulerOptions = {},3169 ) {3170 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3171 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3172 }31733174 getSudo<T extends UniqueHelper>() {3175 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3176 }3177}317831793180export class UniqueFTCollection extends UniqueBaseCollection {3181 async getBalance(addressObj: ICrossAccountId) {3182 return await this.helper.ft.getBalance(this.collectionId, addressObj);3183 }31843185 async getTotalPieces() {3186 return await this.helper.ft.getTotalPieces(this.collectionId);3187 }31883189 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3190 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3191 }31923193 async getTop10Owners() {3194 return await this.helper.ft.getTop10Owners(this.collectionId);3195 }31963197 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3198 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3199 }32003201 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3202 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3203 }32043205 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3206 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3207 }32083209 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3210 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3211 }32123213 async burnTokens(signer: TSigner, amount=1n) {3214 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3215 }32163217 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3218 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3219 }32203221 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3222 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3223 }32243225 scheduleAt<T extends UniqueHelper>(3226 scheduledId: string,3227 executionBlockNumber: number,3228 options: ISchedulerOptions = {},3229 ) {3230 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3231 return new UniqueFTCollection(this.collectionId, scheduledHelper);3232 }32333234 scheduleAfter<T extends UniqueHelper>(3235 scheduledId: string,3236 blocksBeforeExecution: number,3237 options: ISchedulerOptions = {},3238 ) {3239 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3240 return new UniqueFTCollection(this.collectionId, scheduledHelper);3241 }32423243 getSudo<T extends UniqueHelper>() {3244 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3245 }3246}324732483249export class UniqueBaseToken {3250 collection: UniqueNFTCollection | UniqueRFTCollection;3251 collectionId: number;3252 tokenId: number;32533254 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3255 this.collection = collection;3256 this.collectionId = collection.collectionId;3257 this.tokenId = tokenId;3258 }32593260 async getNextSponsored(addressObj: ICrossAccountId) {3261 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3262 }32633264 async getProperties(propertyKeys?: string[] | null) {3265 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3266 }32673268 async setProperties(signer: TSigner, properties: IProperty[]) {3269 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3270 }32713272 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3273 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3274 }32753276 async doesExist() {3277 return await this.collection.doesTokenExist(this.tokenId);3278 }32793280 nestingAccount() {3281 return this.collection.helper.util.getTokenAccount(this);3282 }32833284 scheduleAt<T extends UniqueHelper>(3285 scheduledId: string,3286 executionBlockNumber: number,3287 options: ISchedulerOptions = {},3288 ) {3289 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3290 return new UniqueBaseToken(this.tokenId, scheduledCollection);3291 }32923293 scheduleAfter<T extends UniqueHelper>(3294 scheduledId: string,3295 blocksBeforeExecution: number,3296 options: ISchedulerOptions = {},3297 ) {3298 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3299 return new UniqueBaseToken(this.tokenId, scheduledCollection);3300 }33013302 getSudo<T extends UniqueHelper>() {3303 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3304 }3305}330633073308export class UniqueNFToken extends UniqueBaseToken {3309 collection: UniqueNFTCollection;33103311 constructor(tokenId: number, collection: UniqueNFTCollection) {3312 super(tokenId, collection);3313 this.collection = collection;3314 }33153316 async getData(blockHashAt?: string) {3317 return await this.collection.getToken(this.tokenId, blockHashAt);3318 }33193320 async getOwner(blockHashAt?: string) {3321 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3322 }33233324 async getTopmostOwner(blockHashAt?: string) {3325 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3326 }33273328 async getChildren(blockHashAt?: string) {3329 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3330 }33313332 async nest(signer: TSigner, toTokenObj: IToken) {3333 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3334 }33353336 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3337 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3338 }33393340 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3341 return await this.collection.transferToken(signer, this.tokenId, addressObj);3342 }33433344 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3345 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3346 }33473348 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3349 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3350 }33513352 async isApproved(toAddressObj: ICrossAccountId) {3353 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3354 }33553356 async burn(signer: TSigner) {3357 return await this.collection.burnToken(signer, this.tokenId);3358 }33593360 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3361 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3362 }33633364 scheduleAt<T extends UniqueHelper>(3365 scheduledId: string,3366 executionBlockNumber: number,3367 options: ISchedulerOptions = {},3368 ) {3369 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3370 return new UniqueNFToken(this.tokenId, scheduledCollection);3371 }33723373 scheduleAfter<T extends UniqueHelper>(3374 scheduledId: string,3375 blocksBeforeExecution: number,3376 options: ISchedulerOptions = {},3377 ) {3378 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3379 return new UniqueNFToken(this.tokenId, scheduledCollection);3380 }33813382 getSudo<T extends UniqueHelper>() {3383 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3384 }3385}33863387export class UniqueRFToken extends UniqueBaseToken {3388 collection: UniqueRFTCollection;33893390 constructor(tokenId: number, collection: UniqueRFTCollection) {3391 super(tokenId, collection);3392 this.collection = collection;3393 }33943395 async getData(blockHashAt?: string) {3396 return await this.collection.getToken(this.tokenId, blockHashAt);3397 }33983399 async getTop10Owners() {3400 return await this.collection.getTop10TokenOwners(this.tokenId);3401 }34023403 async getBalance(addressObj: ICrossAccountId) {3404 return await this.collection.getTokenBalance(this.tokenId, addressObj);3405 }34063407 async getTotalPieces() {3408 return await this.collection.getTokenTotalPieces(this.tokenId);3409 }34103411 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3412 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3413 }34143415 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3416 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3417 }34183419 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3420 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3421 }34223423 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3424 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3425 }34263427 async repartition(signer: TSigner, amount: bigint) {3428 return await this.collection.repartitionToken(signer, this.tokenId, amount);3429 }34303431 async burn(signer: TSigner, amount=1n) {3432 return await this.collection.burnToken(signer, this.tokenId, amount);3433 }34343435 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3436 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3437 }34383439 scheduleAt<T extends UniqueHelper>(3440 scheduledId: string,3441 executionBlockNumber: number,3442 options: ISchedulerOptions = {},3443 ) {3444 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3445 return new UniqueRFToken(this.tokenId, scheduledCollection);3446 }34473448 scheduleAfter<T extends UniqueHelper>(3449 scheduledId: string,3450 blocksBeforeExecution: number,3451 options: ISchedulerOptions = {},3452 ) {3453 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3454 return new UniqueRFToken(this.tokenId, scheduledCollection);3455 }34563457 getSudo<T extends UniqueHelper>() {3458 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3459 }3460}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 {13 IApiListeners,14 IBlock,15 IEvent,16 IChainProperties,17 ICollectionCreationOptions,18 ICollectionLimits,19 ICollectionPermissions,20 ICrossAccountId,21 ICrossAccountIdLower,22 ILogger,23 INestingPermissions,24 IProperty,25 IStakingInfo,26 ISchedulerOptions,27 ISubstrateBalance,28 IToken,29 ITokenPropertyPermission,30 ITransactionResult,31 IUniqueHelperLog,32 TApiAllowedListeners,33 TEthereumAccount,34 TSigner,35 TSubstrateAccount,36 TNetworks,37 IForeignAssetMetadata,38 AcalaAssetMetadata,39 MoonbeamAssetInfo,40 DemocracyStandardAccountVote,41} from './types';4243export class CrossAccountId implements ICrossAccountId {44 Substrate?: TSubstrateAccount;45 Ethereum?: TEthereumAccount;4647 constructor(account: ICrossAccountId) {48 if (account.Substrate) this.Substrate = account.Substrate;49 if (account.Ethereum) this.Ethereum = account.Ethereum;50 }5152 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {53 switch (domain) {54 case 'Substrate': return new CrossAccountId({Substrate: account.address});55 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();56 }57 }5859 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {60 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});61 }6263 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {64 return encodeAddress(decodeAddress(address), ss58Format);65 }6667 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {68 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});69 }70 71 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {72 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);73 return this;74 }7576 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {77 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));78 }7980 toEthereum(): CrossAccountId {81 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});82 return this;83 }8485 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {86 return evmToAddress(address, ss58Format);87 }8889 toSubstrate(ss58Format?: number): CrossAccountId {90 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});91 return this;92 }93 94 toLowerCase(): CrossAccountId {95 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();96 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();97 return this;98 }99}100101const nesting = {102 toChecksumAddress(address: string): string {103 if (typeof address === 'undefined') return '';104105 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);106107 address = address.toLowerCase().replace(/^0x/i,'');108 const addressHash = keccakAsHex(address).replace(/^0x/i,'');109 const checksumAddress = ['0x'];110111 for (let i = 0; i < address.length; i++) {112 // If ith character is 8 to f then make it uppercase113 if (parseInt(addressHash[i], 16) > 7) {114 checksumAddress.push(address[i].toUpperCase());115 } else {116 checksumAddress.push(address[i]);117 }118 }119 return checksumAddress.join('');120 },121 tokenIdToAddress(collectionId: number, tokenId: number) {122 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);123 },124};125126class UniqueUtil {127 static transactionStatus = {128 NOT_READY: 'NotReady',129 FAIL: 'Fail',130 SUCCESS: 'Success',131 };132133 static chainLogType = {134 EXTRINSIC: 'extrinsic',135 RPC: 'rpc',136 };137138 static getTokenAccount(token: IToken): CrossAccountId {139 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});140 }141142 static getTokenAddress(token: IToken): string {143 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);144 }145146 static getDefaultLogger(): ILogger {147 return {148 log(msg: any, level = 'INFO') {149 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));150 },151 level: {152 ERROR: 'ERROR',153 WARNING: 'WARNING',154 INFO: 'INFO',155 },156 };157 }158159 static vec2str(arr: string[] | number[]) {160 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');161 }162163 static str2vec(string: string) {164 if (typeof string !== 'string') return string;165 return Array.from(string).map(x => x.charCodeAt(0));166 }167168 static fromSeed(seed: string, ss58Format = 42) {169 const keyring = new Keyring({type: 'sr25519', ss58Format});170 return keyring.addFromUri(seed);171 }172173 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {174 if (creationResult.status !== this.transactionStatus.SUCCESS) {175 throw Error('Unable to create collection!');176 }177178 let collectionId = null;179 creationResult.result.events.forEach(({event: {data, method, section}}) => {180 if ((section === 'common') && (method === 'CollectionCreated')) {181 collectionId = parseInt(data[0].toString(), 10);182 }183 });184185 if (collectionId === null) {186 throw Error('No CollectionCreated event was found!');187 }188189 return collectionId;190 }191192 static extractTokensFromCreationResult(creationResult: ITransactionResult): {193 success: boolean, 194 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],195 } {196 if (creationResult.status !== this.transactionStatus.SUCCESS) {197 throw Error('Unable to create tokens!');198 }199 let success = false;200 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];201 creationResult.result.events.forEach(({event: {data, method, section}}) => {202 if (method === 'ExtrinsicSuccess') {203 success = true;204 } else if ((section === 'common') && (method === 'ItemCreated')) {205 tokens.push({206 collectionId: parseInt(data[0].toString(), 10),207 tokenId: parseInt(data[1].toString(), 10),208 owner: data[2].toHuman(),209 amount: data[3].toBigInt(),210 });211 }212 });213 return {success, tokens};214 }215216 static extractTokensFromBurnResult(burnResult: ITransactionResult): {217 success: boolean, 218 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],219 } {220 if (burnResult.status !== this.transactionStatus.SUCCESS) {221 throw Error('Unable to burn tokens!');222 }223 let success = false;224 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];225 burnResult.result.events.forEach(({event: {data, method, section}}) => {226 if (method === 'ExtrinsicSuccess') {227 success = true;228 } else if ((section === 'common') && (method === 'ItemDestroyed')) {229 tokens.push({230 collectionId: parseInt(data[0].toString(), 10),231 tokenId: parseInt(data[1].toString(), 10),232 owner: data[2].toHuman(),233 amount: data[3].toBigInt(),234 });235 }236 });237 return {success, tokens};238 }239240 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {241 let eventId = null;242 events.forEach(({event: {data, method, section}}) => {243 if ((section === expectedSection) && (method === expectedMethod)) {244 eventId = parseInt(data[0].toString(), 10);245 }246 });247248 if (eventId === null) {249 throw Error(`No ${expectedMethod} event was found!`);250 }251 return eventId === collectionId;252 }253254 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {255 const normalizeAddress = (address: string | ICrossAccountId) => {256 if(typeof address === 'string') return address;257 const obj = {} as any;258 Object.keys(address).forEach(k => {259 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];260 });261 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);262 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();263 return address;264 };265 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;266 events.forEach(({event: {data, method, section}}) => {267 if ((section === 'common') && (method === 'Transfer')) {268 const hData = (data as any).toJSON();269 transfer = {270 collectionId: hData[0],271 tokenId: hData[1],272 from: normalizeAddress(hData[2]),273 to: normalizeAddress(hData[3]),274 amount: BigInt(hData[4]),275 };276 }277 });278 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;279 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);280 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);281 isSuccess = isSuccess && amount === transfer.amount;282 return isSuccess;283 }284285 static bigIntToDecimals(number: bigint, decimals = 18) {286 const numberStr = number.toString();287 const dotPos = numberStr.length - decimals;288 289 if (dotPos <= 0) {290 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;291 } else {292 const intPart = numberStr.substring(0, dotPos);293 const fractPart = numberStr.substring(dotPos);294 return intPart + '.' + fractPart;295 }296 }297}298299class UniqueEventHelper {300 private static extractIndex(index: any): [number, number] | string {301 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];302 return index.toJSON();303 }304305 private static extractSub(data: any, subTypes: any): {[key: string]: any} {306 let obj: any = {};307 let index = 0;308309 if (data.entries) {310 for(const [key, value] of data.entries()) {311 obj[key] = this.extractData(value, subTypes[index]);312 index++;313 }314 } else obj = data.toJSON();315316 return obj;317 }318 319 private static extractData(data: any, type: any): any {320 if(!type) return data.toHuman();321 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();322 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();323 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);324 return data.toHuman();325 }326327 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {328 const parsedEvents: IEvent[] = [];329330 events.forEach((record) => {331 const {event, phase} = record;332 const types = event.typeDef;333334 const eventData: IEvent = {335 section: event.section.toString(),336 method: event.method.toString(),337 index: this.extractIndex(event.index),338 data: [],339 phase: phase.toJSON(),340 };341342 event.data.forEach((val: any, index: number) => {343 eventData.data.push(this.extractData(val, types[index]));344 });345346 parsedEvents.push(eventData);347 });348349 return parsedEvents;350 }351}352353export class ChainHelperBase {354 helperBase: any;355356 transactionStatus = UniqueUtil.transactionStatus;357 chainLogType = UniqueUtil.chainLogType;358 util: typeof UniqueUtil;359 eventHelper: typeof UniqueEventHelper;360 logger: ILogger;361 api: ApiPromise | null;362 forcedNetwork: TNetworks | null;363 network: TNetworks | null;364 chainLog: IUniqueHelperLog[];365 children: ChainHelperBase[];366 address: AddressGroup;367 chain: ChainGroup;368369 constructor(logger?: ILogger, helperBase?: any) {370 this.helperBase = helperBase;371372 this.util = UniqueUtil;373 this.eventHelper = UniqueEventHelper;374 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();375 this.logger = logger;376 this.api = null;377 this.forcedNetwork = null;378 this.network = null;379 this.chainLog = [];380 this.children = [];381 this.address = new AddressGroup(this);382 this.chain = new ChainGroup(this);383 }384385 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {386 Object.setPrototypeOf(helperCls.prototype, this);387 const newHelper = new helperCls(this.logger, options);388389 newHelper.api = this.api;390 newHelper.network = this.network;391 newHelper.forceNetwork = this.forceNetwork;392393 this.children.push(newHelper);394395 return newHelper;396 }397398 getApi(): ApiPromise {399 if(this.api === null) throw Error('API not initialized');400 return this.api;401 }402403 clearChainLog(): void {404 this.chainLog = [];405 }406407 forceNetwork(value: TNetworks): void {408 this.forcedNetwork = value;409 }410411 async connect(wsEndpoint: string, listeners?: IApiListeners) {412 if (this.api !== null) throw Error('Already connected');413 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);414 this.api = api;415 this.network = network;416 }417418 async disconnect() {419 for (const child of this.children) {420 child.clearApi();421 }422423 if (this.api === null) return;424 await this.api.disconnect();425 this.clearApi();426 }427428 clearApi() {429 this.api = null;430 this.network = null;431 }432433 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {434 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;435 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];436437 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;438439 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;440 return 'opal';441 }442443 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {444 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});445 await api.isReady;446447 const network = await this.detectNetwork(api);448449 await api.disconnect();450451 return network;452 }453454 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{455 api: ApiPromise;456 network: TNetworks;457 }> {458 if(typeof network === 'undefined' || network === null) network = 'opal';459 const supportedRPC = {460 opal: {461 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,462 },463 quartz: {464 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,465 },466 unique: {467 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,468 },469 rococo: {},470 westend: {},471 moonbeam: {},472 moonriver: {},473 acala: {},474 karura: {},475 westmint: {},476 };477 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);478 const rpc = supportedRPC[network];479480 // TODO: investigate how to replace rpc in runtime481 // api._rpcCore.addUserInterfaces(rpc);482483 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});484485 await api.isReadyOrError;486487 if (typeof listeners === 'undefined') listeners = {};488 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {489 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;490 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);491 }492493 return {api, network};494 }495496 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {497 const {events, status} = data;498 if (status.isReady) {499 return this.transactionStatus.NOT_READY;500 }501 if (status.isBroadcast) {502 return this.transactionStatus.NOT_READY;503 }504 if (status.isInBlock || status.isFinalized) {505 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');506 if (errors.length > 0) {507 return this.transactionStatus.FAIL;508 }509 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {510 return this.transactionStatus.SUCCESS;511 }512 }513514 return this.transactionStatus.FAIL;515 }516517 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {518 const sign = (callback: any) => {519 if(options !== null) return transaction.signAndSend(sender, options, callback);520 return transaction.signAndSend(sender, callback);521 };522 // eslint-disable-next-line no-async-promise-executor523 return new Promise(async (resolve, reject) => {524 try {525 const unsub = await sign((result: any) => {526 const status = this.getTransactionStatus(result);527528 if (status === this.transactionStatus.SUCCESS) {529 this.logger.log(`${label} successful`);530 unsub();531 resolve({result, status});532 } else if (status === this.transactionStatus.FAIL) {533 let moduleError = null;534535 if (result.hasOwnProperty('dispatchError')) {536 const dispatchError = result['dispatchError'];537538 if (dispatchError) {539 if (dispatchError.isModule) {540 const modErr = dispatchError.asModule;541 const errorMeta = dispatchError.registry.findMetaError(modErr);542543 moduleError = `${errorMeta.section}.${errorMeta.name}`;544 } else {545 moduleError = dispatchError.toHuman();546 }547 } else {548 this.logger.log(result, this.logger.level.ERROR);549 }550 }551552 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);553 unsub();554 reject({status, moduleError, result});555 }556 });557 } catch (e) {558 this.logger.log(e, this.logger.level.ERROR);559 reject(e);560 }561 });562 }563564 constructApiCall(apiCall: string, params: any[]) {565 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);566 let call = this.getApi() as any;567 for(const part of apiCall.slice(4).split('.')) {568 call = call[part];569 }570 return call(...params);571 }572573 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {574 if(this.api === null) throw Error('API not initialized');575 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);576577 const startTime = (new Date()).getTime();578 let result: ITransactionResult;579 let events: IEvent[] = [];580 try {581 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;582 events = this.eventHelper.extractEvents(result.result.events);583 }584 catch(e) {585 if(!(e as object).hasOwnProperty('status')) throw e;586 result = e as ITransactionResult;587 }588589 const endTime = (new Date()).getTime();590591 const log = {592 executedAt: endTime,593 executionTime: endTime - startTime,594 type: this.chainLogType.EXTRINSIC,595 status: result.status,596 call: extrinsic,597 signer: this.getSignerAddress(sender),598 params,599 } as IUniqueHelperLog;600601 if(result.status !== this.transactionStatus.SUCCESS) {602 if (result.moduleError) log.moduleError = result.moduleError;603 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;604 }605 if(events.length > 0) log.events = events;606607 this.chainLog.push(log);608609 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {610 if (result.moduleError) throw Error(`${result.moduleError}`);611 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));612 }613 return result;614 }615616 async callRpc(rpc: string, params?: any[]) {617 if(typeof params === 'undefined') params = [];618 if(this.api === null) throw Error('API not initialized');619 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);620621 const startTime = (new Date()).getTime();622 let result;623 let error = null;624 const log = {625 type: this.chainLogType.RPC,626 call: rpc,627 params,628 } as IUniqueHelperLog;629630 try {631 result = await this.constructApiCall(rpc, params);632 }633 catch(e) {634 error = e;635 }636637 const endTime = (new Date()).getTime();638639 log.executedAt = endTime;640 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';641 log.executionTime = endTime - startTime;642643 this.chainLog.push(log);644645 if(error !== null) throw error;646647 return result;648 }649650 getSignerAddress(signer: IKeyringPair | string): string {651 if(typeof signer === 'string') return signer;652 return signer.address;653 }654655 fetchAllPalletNames(): string[] {656 if(this.api === null) throw Error('API not initialized');657 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());658 }659660 fetchMissingPalletNames(requiredPallets: string[]): string[] {661 const palletNames = this.fetchAllPalletNames();662 return requiredPallets.filter(p => !palletNames.includes(p));663 }664}665666667class HelperGroup<T extends ChainHelperBase> {668 helper: T;669670 constructor(uniqueHelper: T) {671 this.helper = uniqueHelper;672 }673}674675676class CollectionGroup extends HelperGroup<UniqueHelper> {677 /**678 * Get number of blocks when sponsored transaction is available.679 *680 * @param collectionId ID of collection681 * @param tokenId ID of token682 * @param addressObj address for which the sponsorship is checked683 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});684 * @returns number of blocks or null if sponsorship hasn't been set685 */686 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {687 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();688 }689690 /**691 * Get the number of created collections.692 *693 * @returns number of created collections694 */695 async getTotalCount(): Promise<number> {696 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();697 }698699 /**700 * Get information about the collection with additional data,701 * including the number of tokens it contains, its administrators,702 * the normalized address of the collection's owner, and decoded name and description.703 *704 * @param collectionId ID of collection705 * @example await getData(2)706 * @returns collection information object707 */708 async getData(collectionId: number): Promise<{709 id: number;710 name: string;711 description: string;712 tokensCount: number;713 admins: CrossAccountId[];714 normalizedOwner: TSubstrateAccount;715 raw: any716 } | null> {717 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);718 const humanCollection = collection.toHuman(), collectionData = {719 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],720 raw: humanCollection,721 } as any, jsonCollection = collection.toJSON();722 if (humanCollection === null) return null;723 collectionData.raw.limits = jsonCollection.limits;724 collectionData.raw.permissions = jsonCollection.permissions;725 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);726 for (const key of ['name', 'description']) {727 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);728 }729730 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))731 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)732 : 0;733 collectionData.admins = await this.getAdmins(collectionId);734735 return collectionData;736 }737738 /**739 * Get the addresses of the collection's administrators, optionally normalized.740 *741 * @param collectionId ID of collection742 * @param normalize whether to normalize the addresses to the default ss58 format743 * @example await getAdmins(1)744 * @returns array of administrators745 */746 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {747 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();748749 return normalize750 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())751 : admins;752 }753754 /**755 * Get the addresses added to the collection allow-list, optionally normalized.756 * @param collectionId ID of collection757 * @param normalize whether to normalize the addresses to the default ss58 format758 * @example await getAllowList(1)759 * @returns array of allow-listed addresses760 */761 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {762 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();763 return normalize764 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())765 : allowListed;766 }767768 /**769 * Get the effective limits of the collection instead of null for default values770 *771 * @param collectionId ID of collection772 * @example await getEffectiveLimits(2)773 * @returns object of collection limits774 */775 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {776 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();777 }778779 /**780 * Burns the collection if the signer has sufficient permissions and collection is empty.781 *782 * @param signer keyring of signer783 * @param collectionId ID of collection784 * @example await helper.collection.burn(aliceKeyring, 3);785 * @returns ```true``` if extrinsic success, otherwise ```false```786 */787 async burn(signer: TSigner, collectionId: number): Promise<boolean> {788 const result = await this.helper.executeExtrinsic(789 signer,790 'api.tx.unique.destroyCollection', [collectionId],791 true,792 );793794 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');795 }796797 /**798 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.799 *800 * @param signer keyring of signer801 * @param collectionId ID of collection802 * @param sponsorAddress Sponsor substrate address803 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")804 * @returns ```true``` if extrinsic success, otherwise ```false```805 */806 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {807 const result = await this.helper.executeExtrinsic(808 signer,809 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],810 true,811 );812813 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');814 }815816 /**817 * Confirms consent to sponsor the collection on behalf of the signer.818 *819 * @param signer keyring of signer820 * @param collectionId ID of collection821 * @example confirmSponsorship(aliceKeyring, 10)822 * @returns ```true``` if extrinsic success, otherwise ```false```823 */824 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {825 const result = await this.helper.executeExtrinsic(826 signer,827 'api.tx.unique.confirmSponsorship', [collectionId],828 true,829 );830831 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');832 }833834 /**835 * Removes the sponsor of a collection, regardless if it consented or not.836 *837 * @param signer keyring of signer838 * @param collectionId ID of collection839 * @example removeSponsor(aliceKeyring, 10)840 * @returns ```true``` if extrinsic success, otherwise ```false```841 */842 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {843 const result = await this.helper.executeExtrinsic(844 signer,845 'api.tx.unique.removeCollectionSponsor', [collectionId],846 true,847 );848849 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');850 }851852 /**853 * Sets the limits of the collection. At least one limit must be specified for a correct call.854 *855 * @param signer keyring of signer856 * @param collectionId ID of collection857 * @param limits collection limits object858 * @example859 * await setLimits(860 * aliceKeyring,861 * 10,862 * {863 * sponsorTransferTimeout: 0,864 * ownerCanDestroy: false865 * }866 * )867 * @returns ```true``` if extrinsic success, otherwise ```false```868 */869 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {870 const result = await this.helper.executeExtrinsic(871 signer,872 'api.tx.unique.setCollectionLimits', [collectionId, limits],873 true,874 );875876 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');877 }878879 /**880 * Changes the owner of the collection to the new Substrate address.881 *882 * @param signer keyring of signer883 * @param collectionId ID of collection884 * @param ownerAddress substrate address of new owner885 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")886 * @returns ```true``` if extrinsic success, otherwise ```false```887 */888 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {889 const result = await this.helper.executeExtrinsic(890 signer,891 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],892 true,893 );894895 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');896 }897898 /**899 * Adds a collection administrator.900 *901 * @param signer keyring of signer902 * @param collectionId ID of collection903 * @param adminAddressObj Administrator address (substrate or ethereum)904 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})905 * @returns ```true``` if extrinsic success, otherwise ```false```906 */907 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {908 const result = await this.helper.executeExtrinsic(909 signer,910 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],911 true,912 );913914 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');915 }916917 /**918 * Removes a collection administrator.919 *920 * @param signer keyring of signer921 * @param collectionId ID of collection922 * @param adminAddressObj Administrator address (substrate or ethereum)923 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})924 * @returns ```true``` if extrinsic success, otherwise ```false```925 */926 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {927 const result = await this.helper.executeExtrinsic(928 signer,929 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],930 true,931 );932933 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');934 }935936 /**937 * Check if user is in allow list.938 * 939 * @param collectionId ID of collection940 * @param user Account to check941 * @example await getAdmins(1)942 * @returns is user in allow list943 */944 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {945 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();946 }947948 /**949 * Adds an address to allow list950 * @param signer keyring of signer951 * @param collectionId ID of collection952 * @param addressObj address to add to the allow list953 * @returns ```true``` if extrinsic success, otherwise ```false```954 */955 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {956 const result = await this.helper.executeExtrinsic(957 signer,958 'api.tx.unique.addToAllowList', [collectionId, addressObj],959 true,960 );961962 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');963 }964965 /**966 * Removes an address from allow list967 *968 * @param signer keyring of signer969 * @param collectionId ID of collection970 * @param addressObj address to remove from the allow list971 * @returns ```true``` if extrinsic success, otherwise ```false```972 */973 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {974 const result = await this.helper.executeExtrinsic(975 signer,976 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],977 true,978 );979980 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');981 }982983 /**984 * Sets onchain permissions for selected collection.985 *986 * @param signer keyring of signer987 * @param collectionId ID of collection988 * @param permissions collection permissions object989 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});990 * @returns ```true``` if extrinsic success, otherwise ```false```991 */992 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {993 const result = await this.helper.executeExtrinsic(994 signer,995 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],996 true,997 );998999 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');1000 }10011002 /**1003 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1004 *1005 * @param signer keyring of signer1006 * @param collectionId ID of collection1007 * @param permissions nesting permissions object1008 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1009 * @returns ```true``` if extrinsic success, otherwise ```false```1010 */1011 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1012 return await this.setPermissions(signer, collectionId, {nesting: permissions});1013 }10141015 /**1016 * Disables nesting for selected collection.1017 *1018 * @param signer keyring of signer1019 * @param collectionId ID of collection1020 * @example disableNesting(aliceKeyring, 10);1021 * @returns ```true``` if extrinsic success, otherwise ```false```1022 */1023 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1024 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1025 }10261027 /**1028 * Sets onchain properties to the collection.1029 *1030 * @param signer keyring of signer1031 * @param collectionId ID of collection1032 * @param properties array of property objects1033 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1034 * @returns ```true``` if extrinsic success, otherwise ```false```1035 */1036 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1037 const result = await this.helper.executeExtrinsic(1038 signer,1039 'api.tx.unique.setCollectionProperties', [collectionId, properties],1040 true,1041 );10421043 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1044 }10451046 /**1047 * Get collection properties.1048 * 1049 * @param collectionId ID of collection1050 * @param propertyKeys optionally filter the returned properties to only these keys1051 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1052 * @returns array of key-value pairs1053 */1054 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1055 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1056 }10571058 async getCollectionOptions(collectionId: number) {1059 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1060 }10611062 /**1063 * Deletes onchain properties from the collection.1064 *1065 * @param signer keyring of signer1066 * @param collectionId ID of collection1067 * @param propertyKeys array of property keys to delete1068 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1069 * @returns ```true``` if extrinsic success, otherwise ```false```1070 */1071 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1072 const result = await this.helper.executeExtrinsic(1073 signer,1074 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1075 true,1076 );10771078 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1079 }10801081 /**1082 * Changes the owner of the token.1083 *1084 * @param signer keyring of signer1085 * @param collectionId ID of collection1086 * @param tokenId ID of token1087 * @param addressObj address of a new owner1088 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1089 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1090 * @returns true if the token success, otherwise false1091 */1092 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1093 const result = await this.helper.executeExtrinsic(1094 signer,1095 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1096 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1097 );10981099 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1100 }11011102 /**1103 *1104 * Change ownership of a token(s) on behalf of the owner.1105 *1106 * @param signer keyring of signer1107 * @param collectionId ID of collection1108 * @param tokenId ID of token1109 * @param fromAddressObj address on behalf of which the token will be sent1110 * @param toAddressObj new token owner1111 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1112 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1113 * @returns true if the token success, otherwise false1114 */1115 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1116 const result = await this.helper.executeExtrinsic(1117 signer,1118 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1119 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1120 );1121 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1122 }11231124 /**1125 *1126 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1127 *1128 * @param signer keyring of signer1129 * @param collectionId ID of collection1130 * @param tokenId ID of token1131 * @param amount amount of tokens to be burned. For NFT must be set to 1n1132 * @example burnToken(aliceKeyring, 10, 5);1133 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1134 */1135 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1136 const burnResult = await this.helper.executeExtrinsic(1137 signer,1138 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1139 true, // `Unable to burn token for ${label}`,1140 );1141 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1142 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1143 return burnedTokens.success;1144 }11451146 /**1147 * Destroys a concrete instance of NFT on behalf of the owner1148 *1149 * @param signer keyring of signer1150 * @param collectionId ID of collection1151 * @param tokenId ID of token1152 * @param fromAddressObj address on behalf of which the token will be burnt1153 * @param amount amount of tokens to be burned. For NFT must be set to 1n1154 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1155 * @returns ```true``` if extrinsic success, otherwise ```false```1156 */1157 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1158 const burnResult = await this.helper.executeExtrinsic(1159 signer,1160 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1161 true, // `Unable to burn token from for ${label}`,1162 );1163 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1164 return burnedTokens.success && burnedTokens.tokens.length > 0;1165 }11661167 /**1168 * Set, change, or remove approved address to transfer the ownership of the NFT.1169 *1170 * @param signer keyring of signer1171 * @param collectionId ID of collection1172 * @param tokenId ID of token1173 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1174 * @param amount amount of token to be approved. For NFT must be set to 1n1175 * @returns ```true``` if extrinsic success, otherwise ```false```1176 */1177 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1178 const approveResult = await this.helper.executeExtrinsic(1179 signer,1180 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1181 true, // `Unable to approve token for ${label}`,1182 );11831184 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1185 }11861187 /**1188 * Get the amount of token pieces approved to transfer or burn. Normally 0.1189 *1190 * @param collectionId ID of collection1191 * @param tokenId ID of token1192 * @param toAccountObj address which is approved to use token pieces1193 * @param fromAccountObj address which may have allowed the use of its owned tokens1194 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1195 * @returns number of approved to transfer pieces1196 */1197 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1198 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1199 }12001201 /**1202 * Get the last created token ID in a collection1203 *1204 * @param collectionId ID of collection1205 * @example getLastTokenId(10);1206 * @returns id of the last created token1207 */1208 async getLastTokenId(collectionId: number): Promise<number> {1209 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1210 }12111212 /**1213 * Check if token exists1214 *1215 * @param collectionId ID of collection1216 * @param tokenId ID of token1217 * @example doesTokenExist(10, 20);1218 * @returns true if the token exists, otherwise false1219 */1220 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1221 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1222 }1223}12241225class NFTnRFT extends CollectionGroup {1226 /**1227 * Get tokens owned by account1228 *1229 * @param collectionId ID of collection1230 * @param addressObj tokens owner1231 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1232 * @returns array of token ids owned by account1233 */1234 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1235 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1236 }12371238 /**1239 * Get token data1240 *1241 * @param collectionId ID of collection1242 * @param tokenId ID of token1243 * @param propertyKeys optionally filter the token properties to only these keys1244 * @param blockHashAt optionally query the data at some block with this hash1245 * @example getToken(10, 5);1246 * @returns human readable token data1247 */1248 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1249 properties: IProperty[];1250 owner: CrossAccountId;1251 normalizedOwner: CrossAccountId;1252 }| null> {1253 let tokenData;1254 if(typeof blockHashAt === 'undefined') {1255 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1256 }1257 else {1258 if(propertyKeys.length == 0) {1259 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1260 if(!collection) return null;1261 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1262 }1263 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1264 }1265 tokenData = tokenData.toHuman();1266 if (tokenData === null || tokenData.owner === null) return null;1267 const owner = {} as any;1268 for (const key of Object.keys(tokenData.owner)) {1269 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1270 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1271 : tokenData.owner[key];1272 }1273 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1274 return tokenData;1275 }12761277 /**1278 * Set permissions to change token properties1279 *1280 * @param signer keyring of signer1281 * @param collectionId ID of collection1282 * @param permissions permissions to change a property by the collection admin or token owner1283 * @example setTokenPropertyPermissions(1284 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1285 * )1286 * @returns true if extrinsic success otherwise false1287 */1288 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1289 const result = await this.helper.executeExtrinsic(1290 signer,1291 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1292 true,1293 );12941295 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1296 }12971298 /**1299 * Get token property permissions.1300 * 1301 * @param collectionId ID of collection1302 * @param propertyKeys optionally filter the returned property permissions to only these keys1303 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1304 * @returns array of key-permission pairs1305 */1306 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1307 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1308 }13091310 /**1311 * Set token properties1312 *1313 * @param signer keyring of signer1314 * @param collectionId ID of collection1315 * @param tokenId ID of token1316 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1317 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1318 * @returns ```true``` if extrinsic success, otherwise ```false```1319 */1320 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1321 const result = await this.helper.executeExtrinsic(1322 signer,1323 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1324 true,1325 );13261327 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1328 }13291330 /**1331 * Get properties, metadata assigned to a token.1332 * 1333 * @param collectionId ID of collection1334 * @param tokenId ID of token1335 * @param propertyKeys optionally filter the returned properties to only these keys1336 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1337 * @returns array of key-value pairs1338 */1339 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1340 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1341 }13421343 /**1344 * Delete the provided properties of a token1345 * @param signer keyring of signer1346 * @param collectionId ID of collection1347 * @param tokenId ID of token1348 * @param propertyKeys property keys to be deleted1349 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1350 * @returns ```true``` if extrinsic success, otherwise ```false```1351 */1352 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1353 const result = await this.helper.executeExtrinsic(1354 signer,1355 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1356 true,1357 );13581359 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1360 }13611362 /**1363 * Mint new collection1364 *1365 * @param signer keyring of signer1366 * @param collectionOptions basic collection options and properties1367 * @param mode NFT or RFT type of a collection1368 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1369 * @returns object of the created collection1370 */1371 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1372 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1373 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1374 for (const key of ['name', 'description', 'tokenPrefix']) {1375 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);1376 }1377 const creationResult = await this.helper.executeExtrinsic(1378 signer,1379 'api.tx.unique.createCollectionEx', [collectionOptions],1380 true, // errorLabel,1381 );1382 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1383 }13841385 getCollectionObject(_collectionId: number): any {1386 return null;1387 }13881389 getTokenObject(_collectionId: number, _tokenId: number): any {1390 return null;1391 }1392}139313941395class NFTGroup extends NFTnRFT {1396 /**1397 * Get collection object1398 * @param collectionId ID of collection1399 * @example getCollectionObject(2);1400 * @returns instance of UniqueNFTCollection1401 */1402 getCollectionObject(collectionId: number): UniqueNFTCollection {1403 return new UniqueNFTCollection(collectionId, this.helper);1404 }14051406 /**1407 * Get token object1408 * @param collectionId ID of collection1409 * @param tokenId ID of token1410 * @example getTokenObject(10, 5);1411 * @returns instance of UniqueNFTToken1412 */1413 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1414 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1415 }14161417 /**1418 * Get token's owner1419 * @param collectionId ID of collection1420 * @param tokenId ID of token1421 * @param blockHashAt optionally query the data at the block with this hash1422 * @example getTokenOwner(10, 5);1423 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1424 */1425 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1426 let owner;1427 if (typeof blockHashAt === 'undefined') {1428 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1429 } else {1430 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1431 }1432 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1433 }14341435 /**1436 * Is token approved to transfer1437 * @param collectionId ID of collection1438 * @param tokenId ID of token1439 * @param toAccountObj address to be approved1440 * @returns ```true``` if extrinsic success, otherwise ```false```1441 */1442 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1443 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1444 }14451446 /**1447 * Changes the owner of the token.1448 *1449 * @param signer keyring of signer1450 * @param collectionId ID of collection1451 * @param tokenId ID of token1452 * @param addressObj address of a new owner1453 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1454 * @returns ```true``` if extrinsic success, otherwise ```false```1455 */1456 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1457 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1458 }14591460 /**1461 *1462 * Change ownership of a NFT on behalf of the owner.1463 *1464 * @param signer keyring of signer1465 * @param collectionId ID of collection1466 * @param tokenId ID of token1467 * @param fromAddressObj address on behalf of which the token will be sent1468 * @param toAddressObj new token owner1469 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1470 * @returns ```true``` if extrinsic success, otherwise ```false```1471 */1472 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1473 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1474 }14751476 /**1477 * Recursively find the address that owns the token1478 * @param collectionId ID of collection1479 * @param tokenId ID of token1480 * @param blockHashAt1481 * @example getTokenTopmostOwner(10, 5);1482 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1483 */1484 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1485 let owner;1486 if (typeof blockHashAt === 'undefined') {1487 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1488 } else {1489 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1490 }14911492 if (owner === null) return null;14931494 return owner.toHuman();1495 }14961497 /**1498 * Get tokens nested in the provided token1499 * @param collectionId ID of collection1500 * @param tokenId ID of token1501 * @param blockHashAt optionally query the data at the block with this hash1502 * @example getTokenChildren(10, 5);1503 * @returns tokens whose depth of nesting is <= 51504 */1505 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1506 let children;1507 if(typeof blockHashAt === 'undefined') {1508 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1509 } else {1510 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1511 }15121513 return children.toJSON().map((x: any) => {1514 return {collectionId: x.collection, tokenId: x.token};1515 });1516 }15171518 /**1519 * Nest one token into another1520 * @param signer keyring of signer1521 * @param tokenObj token to be nested1522 * @param rootTokenObj token to be parent1523 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1524 * @returns ```true``` if extrinsic success, otherwise ```false```1525 */1526 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1527 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1528 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1529 if(!result) {1530 throw Error('Unable to nest token!');1531 }1532 return result;1533 }15341535 /**1536 * Remove token from nested state1537 * @param signer keyring of signer1538 * @param tokenObj token to unnest1539 * @param rootTokenObj parent of a token1540 * @param toAddressObj address of a new token owner1541 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1542 * @returns ```true``` if extrinsic success, otherwise ```false```1543 */1544 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1545 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1546 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1547 if(!result) {1548 throw Error('Unable to unnest token!');1549 }1550 return result;1551 }15521553 /**1554 * Mint new collection1555 * @param signer keyring of signer1556 * @param collectionOptions Collection options1557 * @example1558 * mintCollection(aliceKeyring, {1559 * name: 'New',1560 * description: 'New collection',1561 * tokenPrefix: 'NEW',1562 * })1563 * @returns object of the created collection1564 */1565 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1566 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1567 }15681569 /**1570 * Mint new token1571 * @param signer keyring of signer1572 * @param data token data1573 * @returns created token object1574 */1575 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1576 const creationResult = await this.helper.executeExtrinsic(1577 signer,1578 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1579 nft: {1580 properties: data.properties,1581 },1582 }],1583 true,1584 );1585 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1586 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1587 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1588 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1589 }15901591 /**1592 * Mint multiple NFT tokens1593 * @param signer keyring of signer1594 * @param collectionId ID of collection1595 * @param tokens array of tokens with owner and properties1596 * @example1597 * mintMultipleTokens(aliceKeyring, 10, [{1598 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1599 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1600 * },{1601 * owner: {Ethereum: "0x9F0583DbB855d..."},1602 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1603 * }]);1604 * @returns ```true``` if extrinsic success, otherwise ```false```1605 */1606 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1607 const creationResult = await this.helper.executeExtrinsic(1608 signer,1609 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1610 true,1611 );1612 const collection = this.getCollectionObject(collectionId);1613 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1614 }16151616 /**1617 * Mint multiple NFT tokens with one owner1618 * @param signer keyring of signer1619 * @param collectionId ID of collection1620 * @param owner tokens owner1621 * @param tokens array of tokens with owner and properties1622 * @example1623 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1624 * properties: [{1625 * key: "gender",1626 * value: "female",1627 * },{1628 * key: "age",1629 * value: "33",1630 * }],1631 * }]);1632 * @returns array of newly created tokens1633 */1634 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1635 const rawTokens = [];1636 for (const token of tokens) {1637 const raw = {NFT: {properties: token.properties}};1638 rawTokens.push(raw);1639 }1640 const creationResult = await this.helper.executeExtrinsic(1641 signer,1642 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1643 true,1644 );1645 const collection = this.getCollectionObject(collectionId);1646 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1647 }16481649 /**1650 * Set, change, or remove approved address to transfer the ownership of the NFT.1651 *1652 * @param signer keyring of signer1653 * @param collectionId ID of collection1654 * @param tokenId ID of token1655 * @param toAddressObj address to approve1656 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1657 * @returns ```true``` if extrinsic success, otherwise ```false```1658 */1659 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1660 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1661 }1662}166316641665class RFTGroup extends NFTnRFT {1666 /**1667 * Get collection object1668 * @param collectionId ID of collection1669 * @example getCollectionObject(2);1670 * @returns instance of UniqueRFTCollection1671 */1672 getCollectionObject(collectionId: number): UniqueRFTCollection {1673 return new UniqueRFTCollection(collectionId, this.helper);1674 }16751676 /**1677 * Get token object1678 * @param collectionId ID of collection1679 * @param tokenId ID of token1680 * @example getTokenObject(10, 5);1681 * @returns instance of UniqueNFTToken1682 */1683 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1684 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1685 }16861687 /**1688 * Get top 10 token owners with the largest number of pieces1689 * @param collectionId ID of collection1690 * @param tokenId ID of token1691 * @example getTokenTop10Owners(10, 5);1692 * @returns array of top 10 owners1693 */1694 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1695 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1696 }16971698 /**1699 * Get number of pieces owned by address1700 * @param collectionId ID of collection1701 * @param tokenId ID of token1702 * @param addressObj address token owner1703 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1704 * @returns number of pieces ownerd by address1705 */1706 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1707 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1708 }17091710 /**1711 * Transfer pieces of token to another address1712 * @param signer keyring of signer1713 * @param collectionId ID of collection1714 * @param tokenId ID of token1715 * @param addressObj address of a new owner1716 * @param amount number of pieces to be transfered1717 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1718 * @returns ```true``` if extrinsic success, otherwise ```false```1719 */1720 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1721 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1722 }17231724 /**1725 * Change ownership of some pieces of RFT on behalf of the owner.1726 * @param signer keyring of signer1727 * @param collectionId ID of collection1728 * @param tokenId ID of token1729 * @param fromAddressObj address on behalf of which the token will be sent1730 * @param toAddressObj new token owner1731 * @param amount number of pieces to be transfered1732 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1733 * @returns ```true``` if extrinsic success, otherwise ```false```1734 */1735 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1736 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1737 }17381739 /**1740 * Mint new collection1741 * @param signer keyring of signer1742 * @param collectionOptions Collection options1743 * @example1744 * mintCollection(aliceKeyring, {1745 * name: 'New',1746 * description: 'New collection',1747 * tokenPrefix: 'NEW',1748 * })1749 * @returns object of the created collection1750 */1751 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1752 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1753 }17541755 /**1756 * Mint new token1757 * @param signer keyring of signer1758 * @param data token data1759 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1760 * @returns created token object1761 */1762 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1763 const creationResult = await this.helper.executeExtrinsic(1764 signer,1765 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1766 refungible: {1767 pieces: data.pieces,1768 properties: data.properties,1769 },1770 }],1771 true,1772 );1773 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1774 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1775 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1776 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1777 }17781779 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1780 throw Error('Not implemented');1781 const creationResult = await this.helper.executeExtrinsic(1782 signer,1783 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1784 true, // `Unable to mint RFT tokens for ${label}`,1785 );1786 const collection = this.getCollectionObject(collectionId);1787 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1788 }17891790 /**1791 * Mint multiple RFT tokens with one owner1792 * @param signer keyring of signer1793 * @param collectionId ID of collection1794 * @param owner tokens owner1795 * @param tokens array of tokens with properties and pieces1796 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1797 * @returns array of newly created RFT tokens1798 */1799 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1800 const rawTokens = [];1801 for (const token of tokens) {1802 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1803 rawTokens.push(raw);1804 }1805 const creationResult = await this.helper.executeExtrinsic(1806 signer,1807 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1808 true,1809 );1810 const collection = this.getCollectionObject(collectionId);1811 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1812 }18131814 /**1815 * Destroys a concrete instance of RFT.1816 * @param signer keyring of signer1817 * @param collectionId ID of collection1818 * @param tokenId ID of token1819 * @param amount number of pieces to be burnt1820 * @example burnToken(aliceKeyring, 10, 5);1821 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1822 */1823 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1824 return await super.burnToken(signer, collectionId, tokenId, amount);1825 }18261827 /**1828 * Destroys a concrete instance of RFT on behalf of the owner.1829 * @param signer keyring of signer1830 * @param collectionId ID of collection1831 * @param tokenId ID of token1832 * @param fromAddressObj address on behalf of which the token will be burnt1833 * @param amount number of pieces to be burnt1834 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1835 * @returns ```true``` if extrinsic success, otherwise ```false```1836 */1837 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1838 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1839 }18401841 /**1842 * Set, change, or remove approved address to transfer the ownership of the RFT.1843 *1844 * @param signer keyring of signer1845 * @param collectionId ID of collection1846 * @param tokenId ID of token1847 * @param toAddressObj address to approve1848 * @param amount number of pieces to be approved1849 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1850 * @returns true if the token success, otherwise false1851 */1852 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1853 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1854 }18551856 /**1857 * Get total number of pieces1858 * @param collectionId ID of collection1859 * @param tokenId ID of token1860 * @example getTokenTotalPieces(10, 5);1861 * @returns number of pieces1862 */1863 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1864 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1865 }18661867 /**1868 * Change number of token pieces. Signer must be the owner of all token pieces.1869 * @param signer keyring of signer1870 * @param collectionId ID of collection1871 * @param tokenId ID of token1872 * @param amount new number of pieces1873 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1874 * @returns true if the repartion was success, otherwise false1875 */1876 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1877 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1878 const repartitionResult = await this.helper.executeExtrinsic(1879 signer,1880 'api.tx.unique.repartition', [collectionId, tokenId, amount],1881 true,1882 );1883 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1884 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1885 }1886}188718881889class FTGroup extends CollectionGroup {1890 /**1891 * Get collection object1892 * @param collectionId ID of collection1893 * @example getCollectionObject(2);1894 * @returns instance of UniqueFTCollection1895 */1896 getCollectionObject(collectionId: number): UniqueFTCollection {1897 return new UniqueFTCollection(collectionId, this.helper);1898 }18991900 /**1901 * Mint new fungible collection1902 * @param signer keyring of signer1903 * @param collectionOptions Collection options1904 * @param decimalPoints number of token decimals1905 * @example1906 * mintCollection(aliceKeyring, {1907 * name: 'New',1908 * description: 'New collection',1909 * tokenPrefix: 'NEW',1910 * }, 18)1911 * @returns newly created fungible collection1912 */1913 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1914 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1915 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1916 collectionOptions.mode = {fungible: decimalPoints};1917 for (const key of ['name', 'description', 'tokenPrefix']) {1918 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);1919 }1920 const creationResult = await this.helper.executeExtrinsic(1921 signer,1922 'api.tx.unique.createCollectionEx', [collectionOptions],1923 true,1924 );1925 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1926 }19271928 /**1929 * Mint tokens1930 * @param signer keyring of signer1931 * @param collectionId ID of collection1932 * @param owner address owner of new tokens1933 * @param amount amount of tokens to be meanted1934 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1935 * @returns ```true``` if extrinsic success, otherwise ```false```1936 */1937 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1938 const creationResult = await this.helper.executeExtrinsic(1939 signer,1940 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1941 fungible: {1942 value: amount,1943 },1944 }],1945 true, // `Unable to mint fungible tokens for ${label}`,1946 );1947 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1948 }19491950 /**1951 * Mint multiple Fungible tokens with one owner1952 * @param signer keyring of signer1953 * @param collectionId ID of collection1954 * @param owner tokens owner1955 * @param tokens array of tokens with properties and pieces1956 * @returns ```true``` if extrinsic success, otherwise ```false```1957 */1958 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1959 const rawTokens = [];1960 for (const token of tokens) {1961 const raw = {Fungible: {Value: token.value}};1962 rawTokens.push(raw);1963 }1964 const creationResult = await this.helper.executeExtrinsic(1965 signer,1966 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1967 true,1968 );1969 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1970 }19711972 /**1973 * Get the top 10 owners with the largest balance for the Fungible collection1974 * @param collectionId ID of collection1975 * @example getTop10Owners(10);1976 * @returns array of ```ICrossAccountId```1977 */1978 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1979 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1980 }19811982 /**1983 * Get account balance1984 * @param collectionId ID of collection1985 * @param addressObj address of owner1986 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1987 * @returns amount of fungible tokens owned by address1988 */1989 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1990 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1991 }19921993 /**1994 * Transfer tokens to address1995 * @param signer keyring of signer1996 * @param collectionId ID of collection1997 * @param toAddressObj address recipient1998 * @param amount amount of tokens to be sent1999 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2000 * @returns ```true``` if extrinsic success, otherwise ```false```2001 */2002 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2003 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2004 }20052006 /**2007 * Transfer some tokens on behalf of the owner.2008 * @param signer keyring of signer2009 * @param collectionId ID of collection2010 * @param fromAddressObj address on behalf of which tokens will be sent2011 * @param toAddressObj address where token to be sent2012 * @param amount number of tokens to be sent2013 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2014 * @returns ```true``` if extrinsic success, otherwise ```false```2015 */2016 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2017 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2018 }20192020 /**2021 * Destroy some amount of tokens2022 * @param signer keyring of signer2023 * @param collectionId ID of collection2024 * @param amount amount of tokens to be destroyed2025 * @example burnTokens(aliceKeyring, 10, 1000n);2026 * @returns ```true``` if extrinsic success, otherwise ```false```2027 */2028 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2029 return await super.burnToken(signer, collectionId, 0, amount);2030 }20312032 /**2033 * Burn some tokens on behalf of the owner.2034 * @param signer keyring of signer2035 * @param collectionId ID of collection2036 * @param fromAddressObj address on behalf of which tokens will be burnt2037 * @param amount amount of tokens to be burnt2038 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2039 * @returns ```true``` if extrinsic success, otherwise ```false```2040 */2041 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2042 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2043 }20442045 /**2046 * Get total collection supply2047 * @param collectionId2048 * @returns2049 */2050 async getTotalPieces(collectionId: number): Promise<bigint> {2051 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2052 }20532054 /**2055 * Set, change, or remove approved address to transfer tokens.2056 *2057 * @param signer keyring of signer2058 * @param collectionId ID of collection2059 * @param toAddressObj address to be approved2060 * @param amount amount of tokens to be approved2061 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2062 * @returns ```true``` if extrinsic success, otherwise ```false```2063 */2064 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2065 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2066 }20672068 /**2069 * Get amount of fungible tokens approved to transfer2070 * @param collectionId ID of collection2071 * @param fromAddressObj owner of tokens2072 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2073 * @returns number of tokens approved for the transfer2074 */2075 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2076 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2077 }2078}207920802081class ChainGroup extends HelperGroup<ChainHelperBase> {2082 /**2083 * Get system properties of a chain2084 * @example getChainProperties();2085 * @returns ss58Format, token decimals, and token symbol2086 */2087 getChainProperties(): IChainProperties {2088 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2089 return {2090 ss58Format: properties.ss58Format.toJSON(),2091 tokenDecimals: properties.tokenDecimals.toJSON(),2092 tokenSymbol: properties.tokenSymbol.toJSON(),2093 };2094 }20952096 /**2097 * Get chain header2098 * @example getLatestBlockNumber();2099 * @returns the number of the last block2100 */2101 async getLatestBlockNumber(): Promise<number> {2102 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2103 }21042105 /**2106 * Get block hash by block number2107 * @param blockNumber number of block2108 * @example getBlockHashByNumber(12345);2109 * @returns hash of a block2110 */2111 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2112 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2113 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2114 return blockHash;2115 }21162117 // TODO add docs2118 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2119 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2120 if (!blockHash) return null;2121 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2122 }21232124 /**2125 * Get account nonce2126 * @param address substrate address2127 * @example getNonce("5GrwvaEF5zXb26Fz...");2128 * @returns number, account's nonce2129 */2130 async getNonce(address: TSubstrateAccount): Promise<number> {2131 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2132 }2133}21342135class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2136 /**2137 * Get substrate address balance2138 * @param address substrate address2139 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2140 * @returns amount of tokens on address2141 */2142 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2143 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2144 }21452146 /**2147 * Transfer tokens to substrate address2148 * @param signer keyring of signer2149 * @param address substrate address of a recipient2150 * @param amount amount of tokens to be transfered2151 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2152 * @returns ```true``` if extrinsic success, otherwise ```false```2153 */2154 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2155 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}`*/);21562157 let transfer = {from: null, to: null, amount: 0n} as any;2158 result.result.events.forEach(({event: {data, method, section}}) => {2159 if ((section === 'balances') && (method === 'Transfer')) {2160 transfer = {2161 from: this.helper.address.normalizeSubstrate(data[0]),2162 to: this.helper.address.normalizeSubstrate(data[1]),2163 amount: BigInt(data[2]),2164 };2165 }2166 });2167 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2168 && this.helper.address.normalizeSubstrate(address) === transfer.to 2169 && BigInt(amount) === transfer.amount;2170 return isSuccess;2171 }21722173 /**2174 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2175 * @param address substrate address2176 * @returns2177 */2178 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2179 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2180 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2181 }2182}21832184class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2185 /**2186 * Get ethereum address balance2187 * @param address ethereum address2188 * @example getEthereum("0x9F0583DbB855d...")2189 * @returns amount of tokens on address2190 */2191 async getEthereum(address: TEthereumAccount): Promise<bigint> {2192 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2193 }21942195 /**2196 * Transfer tokens to address2197 * @param signer keyring of signer2198 * @param address Ethereum address of a recipient2199 * @param amount amount of tokens to be transfered2200 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2201 * @returns ```true``` if extrinsic success, otherwise ```false```2202 */2203 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2204 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);22052206 let transfer = {from: null, to: null, amount: 0n} as any;2207 result.result.events.forEach(({event: {data, method, section}}) => {2208 if ((section === 'balances') && (method === 'Transfer')) {2209 transfer = {2210 from: data[0].toString(),2211 to: data[1].toString(),2212 amount: BigInt(data[2]),2213 };2214 }2215 });2216 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from 2217 && address === transfer.to 2218 && BigInt(amount) === transfer.amount;2219 return isSuccess;2220 }2221}22222223class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2224 subBalanceGroup: SubstrateBalanceGroup<T>;2225 ethBalanceGroup: EthereumBalanceGroup<T>;22262227 constructor(helper: T) {2228 super(helper);2229 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2230 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2231 }22322233 getCollectionCreationPrice(): bigint {2234 return 2n * this.getOneTokenNominal();2235 }2236 /**2237 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2238 * @example getOneTokenNominal()2239 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2240 */2241 getOneTokenNominal(): bigint {2242 const chainProperties = this.helper.chain.getChainProperties();2243 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2244 }22452246 /**2247 * Get substrate address balance2248 * @param address substrate address2249 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2250 * @returns amount of tokens on address2251 */2252 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2253 return this.subBalanceGroup.getSubstrate(address);2254 }22552256 /**2257 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2258 * @param address substrate address2259 * @returns2260 */2261 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2262 return this.subBalanceGroup.getSubstrateFull(address);2263 }22642265 /**2266 * Get ethereum address balance2267 * @param address ethereum address2268 * @example getEthereum("0x9F0583DbB855d...")2269 * @returns amount of tokens on address2270 */2271 async getEthereum(address: TEthereumAccount): Promise<bigint> {2272 return this.ethBalanceGroup.getEthereum(address);2273 }22742275 /**2276 * Transfer tokens to substrate address2277 * @param signer keyring of signer2278 * @param address substrate address of a recipient2279 * @param amount amount of tokens to be transfered2280 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2281 * @returns ```true``` if extrinsic success, otherwise ```false```2282 */2283 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2284 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2285 }2286}22872288class AddressGroup extends HelperGroup<ChainHelperBase> {2289 /**2290 * Normalizes the address to the specified ss58 format, by default ```42```.2291 * @param address substrate address2292 * @param ss58Format format for address conversion, by default ```42```2293 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2294 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2295 */2296 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2297 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2298 }22992300 /**2301 * Get address in the connected chain format2302 * @param address substrate address2303 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2304 * @returns address in chain format2305 */2306 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2307 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2308 }23092310 /**2311 * Get substrate mirror of an ethereum address2312 * @param ethAddress ethereum address2313 * @param toChainFormat false for normalized account2314 * @example ethToSubstrate('0x9F0583DbB855d...')2315 * @returns substrate mirror of a provided ethereum address2316 */2317 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2318 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2319 }23202321 /**2322 * Get ethereum mirror of a substrate address2323 * @param subAddress substrate account2324 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2325 * @returns ethereum mirror of a provided substrate address2326 */2327 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2328 return CrossAccountId.translateSubToEth(subAddress);2329 }23302331 paraSiblingSovereignAccount(paraid: number) {2332 // We are getting a *sibling* parachain sovereign account,2333 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2334 const siblingPrefix = '0x7369626c';23352336 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2337 const suffix = '000000000000000000000000000000000000000000000000';23382339 return siblingPrefix + encodedParaId + suffix;2340 }2341}23422343class StakingGroup extends HelperGroup<UniqueHelper> {2344 /**2345 * Stake tokens for App Promotion2346 * @param signer keyring of signer2347 * @param amountToStake amount of tokens to stake2348 * @param label extra label for log2349 * @returns2350 */2351 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2352 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2353 const _stakeResult = await this.helper.executeExtrinsic(2354 signer, 'api.tx.appPromotion.stake',2355 [amountToStake], true,2356 );2357 // TODO extract info from stakeResult2358 return true;2359 }23602361 /**2362 * Unstake tokens for App Promotion2363 * @param signer keyring of signer2364 * @param amountToUnstake amount of tokens to unstake2365 * @param label extra label for log2366 * @returns block number where balances will be unlocked2367 */2368 async unstake(signer: TSigner, label?: string): Promise<number> {2369 if(typeof label === 'undefined') label = `${signer.address}`;2370 const _unstakeResult = await this.helper.executeExtrinsic(2371 signer, 'api.tx.appPromotion.unstake',2372 [], true,2373 );2374 // TODO extract block number fron events2375 return 1;2376 }23772378 /**2379 * Get total staked amount for address2380 * @param address substrate or ethereum address2381 * @returns total staked amount2382 */2383 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2384 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2385 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2386 }23872388 /**2389 * Get total staked per block2390 * @param address substrate or ethereum address2391 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2392 */2393 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2394 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2395 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2396 return { 2397 block: block.toBigInt(),2398 amount: amount.toBigInt(),2399 };2400 });2401 }24022403 /**2404 * Get total pending unstake amount for address2405 * @param address substrate or ethereum address2406 * @returns total pending unstake amount2407 */2408 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2409 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2410 }24112412 /**2413 * Get pending unstake amount per block for address2414 * @param address substrate or ethereum address2415 * @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 block2416 */2417 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2418 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2419 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2420 return {2421 block: block.toBigInt(),2422 amount: amount.toBigInt(),2423 };2424 });2425 return result;2426 }2427}24282429class SchedulerGroup extends HelperGroup<UniqueHelper> {2430 constructor(helper: UniqueHelper) {2431 super(helper);2432 }24332434 async cancelScheduled(signer: TSigner, scheduledId: string) {2435 return this.helper.executeExtrinsic(2436 signer,2437 'api.tx.scheduler.cancelNamed',2438 [scheduledId],2439 true,2440 );2441 }24422443 async changePriority(signer: TSigner, scheduledId: string, priority: number) {2444 return this.helper.executeExtrinsic(2445 signer,2446 'api.tx.scheduler.changeNamedPriority',2447 [scheduledId, priority],2448 true,2449 );2450 }24512452 scheduleAt<T extends UniqueHelper>(2453 scheduledId: string,2454 executionBlockNumber: number,2455 options: ISchedulerOptions = {},2456 ) {2457 return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2458 }24592460 scheduleAfter<T extends UniqueHelper>(2461 scheduledId: string,2462 blocksBeforeExecution: number,2463 options: ISchedulerOptions = {},2464 ) {2465 return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2466 }24672468 schedule<T extends UniqueHelper>(2469 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2470 scheduledId: string,2471 blocksNum: number,2472 options: ISchedulerOptions = {},2473 ) {2474 // eslint-disable-next-line @typescript-eslint/naming-convention2475 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2476 return this.helper.clone(ScheduledHelperType, {2477 scheduleFn,2478 scheduledId,2479 blocksNum,2480 options,2481 }) as T;2482 }2483}24842485class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2486 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2487 await this.helper.executeExtrinsic(2488 signer,2489 'api.tx.foreignAssets.registerForeignAsset',2490 [ownerAddress, location, metadata],2491 true,2492 );2493 }24942495 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2496 await this.helper.executeExtrinsic(2497 signer,2498 'api.tx.foreignAssets.updateForeignAsset',2499 [foreignAssetId, location, metadata],2500 true,2501 );2502 }2503}25042505class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2506 palletName: string;25072508 constructor(helper: T, palletName: string) {2509 super(helper);25102511 this.palletName = palletName;2512 }25132514 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2515 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2516 }2517}25182519class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2520 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2521 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2522 }25232524 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2525 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2526 }25272528 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2529 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2530 }2531}25322533class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2534 async accounts(address: string, currencyId: any) {2535 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2536 return BigInt(free);2537 }2538}25392540class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2541 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2542 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2543 }25442545 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2546 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2547 }25482549 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2550 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2551 }25522553 async account(assetId: string | number, address: string) {2554 const accountAsset = (2555 await this.helper.callRpc('api.query.assets.account', [assetId, address])2556 ).toJSON()! as any;25572558 if (accountAsset !== null) {2559 return BigInt(accountAsset['balance']);2560 } else {2561 return null;2562 }2563 }2564}25652566class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2567 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2568 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2569 }2570}25712572class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2573 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2574 const apiPrefix = 'api.tx.assetManager.';25752576 const registerTx = this.helper.constructApiCall(2577 apiPrefix + 'registerForeignAsset',2578 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2579 );25802581 const setUnitsTx = this.helper.constructApiCall(2582 apiPrefix + 'setAssetUnitsPerSecond',2583 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2584 );25852586 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2587 const encodedProposal = batchCall?.method.toHex() || '';2588 return encodedProposal;2589 }25902591 async assetTypeId(location: any) {2592 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2593 }2594}25952596class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2597 async notePreimage(signer: TSigner, encodedProposal: string) {2598 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2599 }26002601 externalProposeMajority(proposalHash: string) {2602 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2603 }26042605 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2606 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2607 }26082609 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2610 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2611 }2612}26132614class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2615 collective: string;26162617 constructor(helper: MoonbeamHelper, collective: string) {2618 super(helper);26192620 this.collective = collective;2621 }26222623 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2624 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2625 }26262627 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2628 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2629 }26302631 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2632 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2633 }26342635 async proposalCount() {2636 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2637 }2638}26392640export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2641export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;26422643export class UniqueHelper extends ChainHelperBase {2644 balance: BalanceGroup<UniqueHelper>;2645 collection: CollectionGroup;2646 nft: NFTGroup;2647 rft: RFTGroup;2648 ft: FTGroup;2649 staking: StakingGroup;2650 scheduler: SchedulerGroup;2651 foreignAssets: ForeignAssetsGroup;2652 xcm: XcmGroup<UniqueHelper>;2653 xTokens: XTokensGroup<UniqueHelper>;2654 tokens: TokensGroup<UniqueHelper>;26552656 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2657 super(logger, options.helperBase ?? UniqueHelper);26582659 this.balance = new BalanceGroup(this);2660 this.collection = new CollectionGroup(this);2661 this.nft = new NFTGroup(this);2662 this.rft = new RFTGroup(this);2663 this.ft = new FTGroup(this);2664 this.staking = new StakingGroup(this);2665 this.scheduler = new SchedulerGroup(this);2666 this.foreignAssets = new ForeignAssetsGroup(this);2667 this.xcm = new XcmGroup(this, 'polkadotXcm');2668 this.xTokens = new XTokensGroup(this);2669 this.tokens = new TokensGroup(this);2670 }26712672 getSudo<T extends UniqueHelper>() {2673 // eslint-disable-next-line @typescript-eslint/naming-convention2674 const SudoHelperType = SudoHelper(this.helperBase);2675 return this.clone(SudoHelperType) as T;2676 }2677}26782679export class XcmChainHelper extends ChainHelperBase {2680 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2681 const wsProvider = new WsProvider(wsEndpoint);2682 this.api = new ApiPromise({2683 provider: wsProvider,2684 });2685 await this.api.isReadyOrError;2686 this.network = await UniqueHelper.detectNetwork(this.api);2687 }2688}26892690export class RelayHelper extends XcmChainHelper {2691 xcm: XcmGroup<RelayHelper>;26922693 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2694 super(logger, options.helperBase ?? RelayHelper);26952696 this.xcm = new XcmGroup(this, 'xcmPallet');2697 }2698}26992700export class WestmintHelper extends XcmChainHelper {2701 balance: SubstrateBalanceGroup<WestmintHelper>;2702 xcm: XcmGroup<WestmintHelper>;2703 assets: AssetsGroup<WestmintHelper>;2704 xTokens: XTokensGroup<WestmintHelper>;27052706 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2707 super(logger, options.helperBase ?? WestmintHelper);27082709 this.balance = new SubstrateBalanceGroup(this);2710 this.xcm = new XcmGroup(this, 'polkadotXcm');2711 this.assets = new AssetsGroup(this);2712 this.xTokens = new XTokensGroup(this);2713 }2714}27152716export class MoonbeamHelper extends XcmChainHelper {2717 balance: EthereumBalanceGroup<MoonbeamHelper>;2718 assetManager: MoonbeamAssetManagerGroup;2719 assets: AssetsGroup<MoonbeamHelper>;2720 xTokens: XTokensGroup<MoonbeamHelper>;2721 democracy: MoonbeamDemocracyGroup;2722 collective: {2723 council: MoonbeamCollectiveGroup,2724 techCommittee: MoonbeamCollectiveGroup,2725 };27262727 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2728 super(logger, options.helperBase ?? MoonbeamHelper);27292730 this.balance = new EthereumBalanceGroup(this);2731 this.assetManager = new MoonbeamAssetManagerGroup(this);2732 this.assets = new AssetsGroup(this);2733 this.xTokens = new XTokensGroup(this);2734 this.democracy = new MoonbeamDemocracyGroup(this);2735 this.collective = {2736 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2737 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2738 };2739 }2740}27412742export class AcalaHelper extends XcmChainHelper {2743 balance: SubstrateBalanceGroup<AcalaHelper>;2744 assetRegistry: AcalaAssetRegistryGroup;2745 xTokens: XTokensGroup<AcalaHelper>;2746 tokens: TokensGroup<AcalaHelper>;27472748 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2749 super(logger, options.helperBase ?? AcalaHelper);27502751 this.balance = new SubstrateBalanceGroup(this);2752 this.assetRegistry = new AcalaAssetRegistryGroup(this);2753 this.xTokens = new XTokensGroup(this);2754 this.tokens = new TokensGroup(this);2755 }27562757 getSudo<T extends AcalaHelper>() {2758 // eslint-disable-next-line @typescript-eslint/naming-convention2759 const SudoHelperType = SudoHelper(this.helperBase);2760 return this.clone(SudoHelperType) as T;2761 }2762}27632764// eslint-disable-next-line @typescript-eslint/naming-convention2765function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2766 return class extends Base {2767 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2768 scheduledId: string;2769 blocksNum: number;2770 options: ISchedulerOptions;27712772 constructor(...args: any[]) {2773 const logger = args[0] as ILogger;2774 const options = args[1] as {2775 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2776 scheduledId: string,2777 blocksNum: number,2778 options: ISchedulerOptions2779 };27802781 super(logger);27822783 this.scheduleFn = options.scheduleFn;2784 this.scheduledId = options.scheduledId;2785 this.blocksNum = options.blocksNum;2786 this.options = options.options;2787 }27882789 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2790 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2791 const extrinsic = 'api.tx.scheduler.' + this.scheduleFn;27922793 return super.executeExtrinsic(2794 sender,2795 extrinsic,2796 [2797 this.scheduledId,2798 this.blocksNum,2799 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2800 this.options.priority ?? null,2801 {Value: scheduledTx},2802 ],2803 expectSuccess,2804 );2805 }2806 };2807}28082809// eslint-disable-next-line @typescript-eslint/naming-convention2810function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2811 return class extends Base {2812 constructor(...args: any[]) {2813 super(...args);2814 }28152816 executeExtrinsic (2817 sender: IKeyringPair,2818 extrinsic: string,2819 params: any[],2820 expectSuccess?: boolean,2821 ): Promise<ITransactionResult> {2822 const call = this.constructApiCall(extrinsic, params);28232824 return super.executeExtrinsic(2825 sender,2826 'api.tx.sudo.sudo',2827 [call],2828 expectSuccess,2829 );2830 }2831 };2832}28332834export class UniqueBaseCollection {2835 helper: UniqueHelper;2836 collectionId: number;28372838 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2839 this.collectionId = collectionId;2840 this.helper = uniqueHelper;2841 }28422843 async getData() {2844 return await this.helper.collection.getData(this.collectionId);2845 }28462847 async getLastTokenId() {2848 return await this.helper.collection.getLastTokenId(this.collectionId);2849 }28502851 async doesTokenExist(tokenId: number) {2852 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2853 }28542855 async getAdmins() {2856 return await this.helper.collection.getAdmins(this.collectionId);2857 }28582859 async getAllowList() {2860 return await this.helper.collection.getAllowList(this.collectionId);2861 }28622863 async getEffectiveLimits() {2864 return await this.helper.collection.getEffectiveLimits(this.collectionId);2865 }28662867 async getProperties(propertyKeys?: string[] | null) {2868 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2869 }28702871 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2872 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2873 }28742875 async getOptions() {2876 return await this.helper.collection.getCollectionOptions(this.collectionId);2877 }28782879 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2880 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2881 }28822883 async confirmSponsorship(signer: TSigner) {2884 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2885 }28862887 async removeSponsor(signer: TSigner) {2888 return await this.helper.collection.removeSponsor(signer, this.collectionId);2889 }28902891 async setLimits(signer: TSigner, limits: ICollectionLimits) {2892 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2893 }28942895 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2896 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2897 }28982899 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2900 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2901 }29022903 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2904 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2905 }29062907 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2908 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2909 }29102911 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2912 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2913 }29142915 async setProperties(signer: TSigner, properties: IProperty[]) {2916 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2917 }29182919 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2920 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2921 }29222923 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2924 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2925 }29262927 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2928 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2929 }29302931 async disableNesting(signer: TSigner) {2932 return await this.helper.collection.disableNesting(signer, this.collectionId);2933 }29342935 async burn(signer: TSigner) {2936 return await this.helper.collection.burn(signer, this.collectionId);2937 }29382939 scheduleAt<T extends UniqueHelper>(2940 scheduledId: string,2941 executionBlockNumber: number,2942 options: ISchedulerOptions = {},2943 ) {2944 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2945 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2946 }29472948 scheduleAfter<T extends UniqueHelper>(2949 scheduledId: string,2950 blocksBeforeExecution: number,2951 options: ISchedulerOptions = {},2952 ) {2953 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2954 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2955 }29562957 getSudo<T extends UniqueHelper>() {2958 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2959 }2960}296129622963export class UniqueNFTCollection extends UniqueBaseCollection {2964 getTokenObject(tokenId: number) {2965 return new UniqueNFToken(tokenId, this);2966 }29672968 async getTokensByAddress(addressObj: ICrossAccountId) {2969 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2970 }29712972 async getToken(tokenId: number, blockHashAt?: string) {2973 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2974 }29752976 async getTokenOwner(tokenId: number, blockHashAt?: string) {2977 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2978 }29792980 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2981 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2982 }29832984 async getTokenChildren(tokenId: number, blockHashAt?: string) {2985 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2986 }29872988 async getPropertyPermissions(propertyKeys: string[] | null = null) {2989 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2990 }29912992 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2993 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2994 }29952996 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2997 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2998 }29993000 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3001 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3002 }30033004 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3005 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3006 }30073008 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3009 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3010 }30113012 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3013 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3014 }30153016 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3017 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3018 }30193020 async burnToken(signer: TSigner, tokenId: number) {3021 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3022 }30233024 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3025 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3026 }30273028 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3029 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3030 }30313032 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3033 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3034 }30353036 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3037 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3038 }30393040 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3041 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3042 }30433044 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3045 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3046 }30473048 scheduleAt<T extends UniqueHelper>(3049 scheduledId: string,3050 executionBlockNumber: number,3051 options: ISchedulerOptions = {},3052 ) {3053 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3054 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3055 }30563057 scheduleAfter<T extends UniqueHelper>(3058 scheduledId: string,3059 blocksBeforeExecution: number,3060 options: ISchedulerOptions = {},3061 ) {3062 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3063 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3064 }30653066 getSudo<T extends UniqueHelper>() {3067 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3068 }3069}307030713072export class UniqueRFTCollection extends UniqueBaseCollection {3073 getTokenObject(tokenId: number) {3074 return new UniqueRFToken(tokenId, this);3075 }30763077 async getToken(tokenId: number, blockHashAt?: string) {3078 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3079 }30803081 async getTokensByAddress(addressObj: ICrossAccountId) {3082 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3083 }30843085 async getTop10TokenOwners(tokenId: number) {3086 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3087 }30883089 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3090 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3091 }30923093 async getTokenTotalPieces(tokenId: number) {3094 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3095 }30963097 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3098 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3099 }31003101 async getPropertyPermissions(propertyKeys: string[] | null = null) {3102 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3103 }31043105 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3106 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3107 }31083109 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3110 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3111 }31123113 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3114 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3115 }31163117 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3118 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3119 }31203121 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3122 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3123 }31243125 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3126 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3127 }31283129 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3130 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3131 }31323133 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3134 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3135 }31363137 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3138 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3139 }31403141 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3142 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3143 }31443145 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3146 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3147 }31483149 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3150 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3151 }31523153 scheduleAt<T extends UniqueHelper>(3154 scheduledId: string,3155 executionBlockNumber: number,3156 options: ISchedulerOptions = {},3157 ) {3158 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3159 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3160 }31613162 scheduleAfter<T extends UniqueHelper>(3163 scheduledId: string,3164 blocksBeforeExecution: number,3165 options: ISchedulerOptions = {},3166 ) {3167 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3168 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3169 }31703171 getSudo<T extends UniqueHelper>() {3172 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3173 }3174}317531763177export class UniqueFTCollection extends UniqueBaseCollection {3178 async getBalance(addressObj: ICrossAccountId) {3179 return await this.helper.ft.getBalance(this.collectionId, addressObj);3180 }31813182 async getTotalPieces() {3183 return await this.helper.ft.getTotalPieces(this.collectionId);3184 }31853186 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3187 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3188 }31893190 async getTop10Owners() {3191 return await this.helper.ft.getTop10Owners(this.collectionId);3192 }31933194 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3195 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3196 }31973198 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3199 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3200 }32013202 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3203 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3204 }32053206 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3207 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3208 }32093210 async burnTokens(signer: TSigner, amount=1n) {3211 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3212 }32133214 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3215 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3216 }32173218 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3219 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3220 }32213222 scheduleAt<T extends UniqueHelper>(3223 scheduledId: string,3224 executionBlockNumber: number,3225 options: ISchedulerOptions = {},3226 ) {3227 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3228 return new UniqueFTCollection(this.collectionId, scheduledHelper);3229 }32303231 scheduleAfter<T extends UniqueHelper>(3232 scheduledId: string,3233 blocksBeforeExecution: number,3234 options: ISchedulerOptions = {},3235 ) {3236 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3237 return new UniqueFTCollection(this.collectionId, scheduledHelper);3238 }32393240 getSudo<T extends UniqueHelper>() {3241 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3242 }3243}324432453246export class UniqueBaseToken {3247 collection: UniqueNFTCollection | UniqueRFTCollection;3248 collectionId: number;3249 tokenId: number;32503251 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3252 this.collection = collection;3253 this.collectionId = collection.collectionId;3254 this.tokenId = tokenId;3255 }32563257 async getNextSponsored(addressObj: ICrossAccountId) {3258 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3259 }32603261 async getProperties(propertyKeys?: string[] | null) {3262 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3263 }32643265 async setProperties(signer: TSigner, properties: IProperty[]) {3266 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3267 }32683269 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3270 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3271 }32723273 async doesExist() {3274 return await this.collection.doesTokenExist(this.tokenId);3275 }32763277 nestingAccount() {3278 return this.collection.helper.util.getTokenAccount(this);3279 }32803281 scheduleAt<T extends UniqueHelper>(3282 scheduledId: string,3283 executionBlockNumber: number,3284 options: ISchedulerOptions = {},3285 ) {3286 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3287 return new UniqueBaseToken(this.tokenId, scheduledCollection);3288 }32893290 scheduleAfter<T extends UniqueHelper>(3291 scheduledId: string,3292 blocksBeforeExecution: number,3293 options: ISchedulerOptions = {},3294 ) {3295 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3296 return new UniqueBaseToken(this.tokenId, scheduledCollection);3297 }32983299 getSudo<T extends UniqueHelper>() {3300 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3301 }3302}330333043305export class UniqueNFToken extends UniqueBaseToken {3306 collection: UniqueNFTCollection;33073308 constructor(tokenId: number, collection: UniqueNFTCollection) {3309 super(tokenId, collection);3310 this.collection = collection;3311 }33123313 async getData(blockHashAt?: string) {3314 return await this.collection.getToken(this.tokenId, blockHashAt);3315 }33163317 async getOwner(blockHashAt?: string) {3318 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3319 }33203321 async getTopmostOwner(blockHashAt?: string) {3322 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3323 }33243325 async getChildren(blockHashAt?: string) {3326 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3327 }33283329 async nest(signer: TSigner, toTokenObj: IToken) {3330 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3331 }33323333 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3334 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3335 }33363337 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3338 return await this.collection.transferToken(signer, this.tokenId, addressObj);3339 }33403341 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3342 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3343 }33443345 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3346 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3347 }33483349 async isApproved(toAddressObj: ICrossAccountId) {3350 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3351 }33523353 async burn(signer: TSigner) {3354 return await this.collection.burnToken(signer, this.tokenId);3355 }33563357 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3358 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3359 }33603361 scheduleAt<T extends UniqueHelper>(3362 scheduledId: string,3363 executionBlockNumber: number,3364 options: ISchedulerOptions = {},3365 ) {3366 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3367 return new UniqueNFToken(this.tokenId, scheduledCollection);3368 }33693370 scheduleAfter<T extends UniqueHelper>(3371 scheduledId: string,3372 blocksBeforeExecution: number,3373 options: ISchedulerOptions = {},3374 ) {3375 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3376 return new UniqueNFToken(this.tokenId, scheduledCollection);3377 }33783379 getSudo<T extends UniqueHelper>() {3380 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3381 }3382}33833384export class UniqueRFToken extends UniqueBaseToken {3385 collection: UniqueRFTCollection;33863387 constructor(tokenId: number, collection: UniqueRFTCollection) {3388 super(tokenId, collection);3389 this.collection = collection;3390 }33913392 async getData(blockHashAt?: string) {3393 return await this.collection.getToken(this.tokenId, blockHashAt);3394 }33953396 async getTop10Owners() {3397 return await this.collection.getTop10TokenOwners(this.tokenId);3398 }33993400 async getBalance(addressObj: ICrossAccountId) {3401 return await this.collection.getTokenBalance(this.tokenId, addressObj);3402 }34033404 async getTotalPieces() {3405 return await this.collection.getTokenTotalPieces(this.tokenId);3406 }34073408 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3409 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3410 }34113412 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3413 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3414 }34153416 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3417 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3418 }34193420 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3421 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3422 }34233424 async repartition(signer: TSigner, amount: bigint) {3425 return await this.collection.repartitionToken(signer, this.tokenId, amount);3426 }34273428 async burn(signer: TSigner, amount=1n) {3429 return await this.collection.burnToken(signer, this.tokenId, amount);3430 }34313432 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3433 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3434 }34353436 scheduleAt<T extends UniqueHelper>(3437 scheduledId: string,3438 executionBlockNumber: number,3439 options: ISchedulerOptions = {},3440 ) {3441 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3442 return new UniqueRFToken(this.tokenId, scheduledCollection);3443 }34443445 scheduleAfter<T extends UniqueHelper>(3446 scheduledId: string,3447 blocksBeforeExecution: number,3448 options: ISchedulerOptions = {},3449 ) {3450 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3451 return new UniqueRFToken(this.tokenId, scheduledCollection);3452 }34533454 getSudo<T extends UniqueHelper>() {3455 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3456 }3457}