12345678import {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 {hexToU8a} from '@polkadot/util/hex';13import {u8aConcat} from '@polkadot/util/u8a';14import {15 IApiListeners,16 IBlock,17 IEvent,18 IChainProperties,19 ICollectionCreationOptions,20 ICollectionLimits,21 ICollectionPermissions,22 ICrossAccountId,23 ICrossAccountIdLower,24 ILogger,25 INestingPermissions,26 IProperty,27 IStakingInfo,28 ISchedulerOptions,29 ISubstrateBalance,30 IToken,31 ITokenPropertyPermission,32 ITransactionResult,33 IUniqueHelperLog,34 TApiAllowedListeners,35 TEthereumAccount,36 TSigner,37 TSubstrateAccount,38 TNetworks,39 IForeignAssetMetadata,40 AcalaAssetMetadata,41 MoonbeamAssetInfo,42 DemocracyStandardAccountVote,43 IEthCrossAccountId,44} from './types';45import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';46import type {Vec} from '@polkadot/types-codec';47import {FrameSystemEventRecord} from '@polkadot/types/lookup';48import {DevUniqueHelper} from './unique.dev';4950export class CrossAccountId implements ICrossAccountId {51 Substrate?: TSubstrateAccount;52 Ethereum?: TEthereumAccount;5354 constructor(account: ICrossAccountId) {55 if (account.Substrate) this.Substrate = account.Substrate;56 if (account.Ethereum) this.Ethereum = account.Ethereum;57 }5859 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {60 switch (domain) {61 case 'Substrate': return new CrossAccountId({Substrate: account.address});62 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();63 }64 }6566 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {67 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});68 }6970 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {71 return encodeAddress(decodeAddress(address), ss58Format);72 }7374 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {75 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});76 }7778 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {79 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);80 return this;81 }8283 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {84 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));85 }8687 toEthereum(): CrossAccountId {88 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});89 return this;90 }9192 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {93 return evmToAddress(address, ss58Format);94 }9596 toSubstrate(ss58Format?: number): CrossAccountId {97 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});98 return this;99 }100101 toLowerCase(): CrossAccountId {102 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();103 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();104 return this;105 }106}107108const nesting = {109 toChecksumAddress(address: string): string {110 if (typeof address === 'undefined') return '';111112 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);113114 address = address.toLowerCase().replace(/^0x/i,'');115 const addressHash = keccakAsHex(address).replace(/^0x/i,'');116 const checksumAddress = ['0x'];117118 for (let i = 0; i < address.length; i++) {119 120 if (parseInt(addressHash[i], 16) > 7) {121 checksumAddress.push(address[i].toUpperCase());122 } else {123 checksumAddress.push(address[i]);124 }125 }126 return checksumAddress.join('');127 },128 tokenIdToAddress(collectionId: number, tokenId: number) {129 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);130 },131};132133class UniqueUtil {134 static transactionStatus = {135 NOT_READY: 'NotReady',136 FAIL: 'Fail',137 SUCCESS: 'Success',138 };139140 static chainLogType = {141 EXTRINSIC: 'extrinsic',142 RPC: 'rpc',143 };144145 static getTokenAccount(token: IToken): CrossAccountId {146 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});147 }148149 static getTokenAddress(token: IToken): string {150 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);151 }152153 static getDefaultLogger(): ILogger {154 return {155 log(msg: any, level = 'INFO') {156 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));157 },158 level: {159 ERROR: 'ERROR',160 WARNING: 'WARNING',161 INFO: 'INFO',162 },163 };164 }165166 static vec2str(arr: string[] | number[]) {167 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');168 }169170 static str2vec(string: string) {171 if (typeof string !== 'string') return string;172 return Array.from(string).map(x => x.charCodeAt(0));173 }174175 static fromSeed(seed: string, ss58Format = 42) {176 const keyring = new Keyring({type: 'sr25519', ss58Format});177 return keyring.addFromUri(seed);178 }179180 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {181 if (creationResult.status !== this.transactionStatus.SUCCESS) {182 throw Error('Unable to create collection!');183 }184185 let collectionId = null;186 creationResult.result.events.forEach(({event: {data, method, section}}) => {187 if ((section === 'common') && (method === 'CollectionCreated')) {188 collectionId = parseInt(data[0].toString(), 10);189 }190 });191192 if (collectionId === null) {193 throw Error('No CollectionCreated event was found!');194 }195196 return collectionId;197 }198199 static extractTokensFromCreationResult(creationResult: ITransactionResult): {200 success: boolean,201 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],202 } {203 if (creationResult.status !== this.transactionStatus.SUCCESS) {204 throw Error('Unable to create tokens!');205 }206 let success = false;207 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];208 creationResult.result.events.forEach(({event: {data, method, section}}) => {209 if (method === 'ExtrinsicSuccess') {210 success = true;211 } else if ((section === 'common') && (method === 'ItemCreated')) {212 tokens.push({213 collectionId: parseInt(data[0].toString(), 10),214 tokenId: parseInt(data[1].toString(), 10),215 owner: data[2].toHuman(),216 amount: data[3].toBigInt(),217 });218 }219 });220 return {success, tokens};221 }222223 static extractTokensFromBurnResult(burnResult: ITransactionResult): {224 success: boolean,225 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],226 } {227 if (burnResult.status !== this.transactionStatus.SUCCESS) {228 throw Error('Unable to burn tokens!');229 }230 let success = false;231 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];232 burnResult.result.events.forEach(({event: {data, method, section}}) => {233 if (method === 'ExtrinsicSuccess') {234 success = true;235 } else if ((section === 'common') && (method === 'ItemDestroyed')) {236 tokens.push({237 collectionId: parseInt(data[0].toString(), 10),238 tokenId: parseInt(data[1].toString(), 10),239 owner: data[2].toHuman(),240 amount: data[3].toBigInt(),241 });242 }243 });244 return {success, tokens};245 }246247 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {248 let eventId = null;249 events.forEach(({event: {data, method, section}}) => {250 if ((section === expectedSection) && (method === expectedMethod)) {251 eventId = parseInt(data[0].toString(), 10);252 }253 });254255 if (eventId === null) {256 throw Error(`No ${expectedMethod} event was found!`);257 }258 return eventId === collectionId;259 }260261 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {262 const normalizeAddress = (address: string | ICrossAccountId) => {263 if(typeof address === 'string') return address;264 const obj = {} as any;265 Object.keys(address).forEach(k => {266 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];267 });268 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);269 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();270 return address;271 };272 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;273 events.forEach(({event: {data, method, section}}) => {274 if ((section === 'common') && (method === 'Transfer')) {275 const hData = (data as any).toJSON();276 transfer = {277 collectionId: hData[0],278 tokenId: hData[1],279 from: normalizeAddress(hData[2]),280 to: normalizeAddress(hData[3]),281 amount: BigInt(hData[4]),282 };283 }284 });285 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;286 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);287 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);288 isSuccess = isSuccess && amount === transfer.amount;289 return isSuccess;290 }291292 static bigIntToDecimals(number: bigint, decimals = 18) {293 const numberStr = number.toString();294 const dotPos = numberStr.length - decimals;295296 if (dotPos <= 0) {297 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;298 } else {299 const intPart = numberStr.substring(0, dotPos);300 const fractPart = numberStr.substring(dotPos);301 return intPart + '.' + fractPart;302 }303 }304}305306class UniqueEventHelper {307 private static extractIndex(index: any): [number, number] | string {308 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];309 return index.toJSON();310 }311312 private static extractSub(data: any, subTypes: any): {[key: string]: any} {313 let obj: any = {};314 let index = 0;315316 if (data.entries) {317 for(const [key, value] of data.entries()) {318 obj[key] = this.extractData(value, subTypes[index]);319 index++;320 }321 } else obj = data.toJSON();322323 return obj;324 }325326 private static toHuman(data: any) {327 return data && data.toHuman ? data.toHuman() : `${data}`;328 }329330 private static extractData(data: any, type: any): any {331 if(!type) return this.toHuman(data);332 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();333 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();334 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);335 return this.toHuman(data);336 }337338 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {339 const parsedEvents: IEvent[] = [];340341 events.forEach((record) => {342 const {event, phase} = record;343 const types = event.typeDef;344345 const eventData: IEvent = {346 section: event.section.toString(),347 method: event.method.toString(),348 index: this.extractIndex(event.index),349 data: [],350 phase: phase.toJSON(),351 };352353 event.data.forEach((val: any, index: number) => {354 eventData.data.push(this.extractData(val, types[index]));355 });356357 parsedEvents.push(eventData);358 });359360 return parsedEvents;361 }362}363364export class ChainHelperBase {365 helperBase: any;366367 transactionStatus = UniqueUtil.transactionStatus;368 chainLogType = UniqueUtil.chainLogType;369 util: typeof UniqueUtil;370 eventHelper: typeof UniqueEventHelper;371 logger: ILogger;372 api: ApiPromise | null;373 forcedNetwork: TNetworks | null;374 network: TNetworks | null;375 chainLog: IUniqueHelperLog[];376 children: ChainHelperBase[];377 address: AddressGroup;378 chain: ChainGroup;379 session: SessionGroup;380381 constructor(logger?: ILogger, helperBase?: any) {382 this.helperBase = helperBase;383384 this.util = UniqueUtil;385 this.eventHelper = UniqueEventHelper;386 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();387 this.logger = logger;388 this.api = null;389 this.forcedNetwork = null;390 this.network = null;391 this.chainLog = [];392 this.children = [];393 this.address = new AddressGroup(this);394 this.chain = new ChainGroup(this);395 this.session = new SessionGroup(this);396 }397398 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {399 Object.setPrototypeOf(helperCls.prototype, this);400 const newHelper = new helperCls(this.logger, options);401402 newHelper.api = this.api;403 newHelper.network = this.network;404 newHelper.forceNetwork = this.forceNetwork;405406 this.children.push(newHelper);407408 return newHelper;409 }410411 getApi(): ApiPromise {412 if(this.api === null) throw Error('API not initialized');413 return this.api;414 }415416 async subscribeEvents(expectedEvents: {section: string, names: string[]}[]) {417 const collectedEvents: IEvent[] = [];418 const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {419 const ievents = this.eventHelper.extractEvents(events);420 ievents.forEach((event) => {421 expectedEvents.forEach((e => {422 if (event.section === e.section && e.names.includes(event.method)) {423 collectedEvents.push(event);424 }425 }));426 });427 });428 return {unsubscribe: unsubscribe as any, collectedEvents};429 }430431 clearChainLog(): void {432 this.chainLog = [];433 }434435 forceNetwork(value: TNetworks): void {436 this.forcedNetwork = value;437 }438439 async connect(wsEndpoint: string, listeners?: IApiListeners) {440 if (this.api !== null) throw Error('Already connected');441 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);442 this.api = api;443 this.network = network;444 }445446 async disconnect() {447 for (const child of this.children) {448 child.clearApi();449 }450451 if (this.api === null) return;452 await this.api.disconnect();453 this.clearApi();454 }455456 clearApi() {457 this.api = null;458 this.network = null;459 }460461 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {462 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;463 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];464465 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;466467 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;468 return 'opal';469 }470471 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {472 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});473 await api.isReady;474475 const network = await this.detectNetwork(api);476477 await api.disconnect();478479 return network;480 }481482 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{483 api: ApiPromise;484 network: TNetworks;485 }> {486 if(typeof network === 'undefined' || network === null) network = 'opal';487 const supportedRPC = {488 opal: {489 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,490 },491 quartz: {492 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,493 },494 unique: {495 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,496 },497 rococo: {},498 westend: {},499 moonbeam: {},500 moonriver: {},501 acala: {},502 karura: {},503 westmint: {},504 };505 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);506 const rpc = supportedRPC[network];507508 509 510511 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});512513 await api.isReadyOrError;514515 if (typeof listeners === 'undefined') listeners = {};516 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {517 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;518 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);519 }520521 return {api, network};522 }523524 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {525 const {events, status} = data;526 if (status.isReady) {527 return this.transactionStatus.NOT_READY;528 }529 if (status.isBroadcast) {530 return this.transactionStatus.NOT_READY;531 }532 if (status.isInBlock || status.isFinalized) {533 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');534 if (errors.length > 0) {535 return this.transactionStatus.FAIL;536 }537 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {538 return this.transactionStatus.SUCCESS;539 }540 }541542 return this.transactionStatus.FAIL;543 }544545 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {546 const sign = (callback: any) => {547 if(options !== null) return transaction.signAndSend(sender, options, callback);548 return transaction.signAndSend(sender, callback);549 };550 551 return new Promise(async (resolve, reject) => {552 try {553 const unsub = await sign((result: any) => {554 const status = this.getTransactionStatus(result);555556 if (status === this.transactionStatus.SUCCESS) {557 this.logger.log(`${label} successful`);558 unsub();559 resolve({result, status});560 } else if (status === this.transactionStatus.FAIL) {561 let moduleError = null;562563 if (result.hasOwnProperty('dispatchError')) {564 const dispatchError = result['dispatchError'];565566 if (dispatchError) {567 if (dispatchError.isModule) {568 const modErr = dispatchError.asModule;569 const errorMeta = dispatchError.registry.findMetaError(modErr);570571 moduleError = `${errorMeta.section}.${errorMeta.name}`;572 } else {573 moduleError = dispatchError.toHuman();574 }575 } else {576 this.logger.log(result, this.logger.level.ERROR);577 }578 }579580 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);581 unsub();582 reject({status, moduleError, result});583 }584 });585 } catch (e) {586 this.logger.log(e, this.logger.level.ERROR);587 reject(e);588 }589 });590 }591592 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {593 const api = this.getApi();594 const signingInfo = await api.derive.tx.signingInfo(signer.address);595596 597 598 tx.sign(signer, {599 blockHash: api.genesisHash,600 genesisHash: api.genesisHash,601 runtimeVersion: api.runtimeVersion,602 nonce: signingInfo.nonce,603 });604605 if (len === null) {606 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;607 } else {608 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;609 }610 }611612 constructApiCall(apiCall: string, params: any[]) {613 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);614 let call = this.getApi() as any;615 for(const part of apiCall.slice(4).split('.')) {616 call = call[part];617 }618 return call(...params);619 }620621 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null) {622 if(this.api === null) throw Error('API not initialized');623 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);624625 const startTime = (new Date()).getTime();626 let result: ITransactionResult;627 let events: IEvent[] = [];628 try {629 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;630 events = this.eventHelper.extractEvents(result.result.events);631 }632 catch(e) {633 if(!(e as object).hasOwnProperty('status')) throw e;634 result = e as ITransactionResult;635 }636637 const endTime = (new Date()).getTime();638639 const log = {640 executedAt: endTime,641 executionTime: endTime - startTime,642 type: this.chainLogType.EXTRINSIC,643 status: result.status,644 call: extrinsic,645 signer: this.getSignerAddress(sender),646 params,647 } as IUniqueHelperLog;648649 if(result.status !== this.transactionStatus.SUCCESS) {650 if (result.moduleError) log.moduleError = result.moduleError;651 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;652 }653 if(events.length > 0) log.events = events;654655 this.chainLog.push(log);656657 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {658 if (result.moduleError) throw Error(`${result.moduleError}`);659 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));660 }661 return result;662 }663664 async callRpc(rpc: string, params?: any[]) {665 if(typeof params === 'undefined') params = [];666 if(this.api === null) throw Error('API not initialized');667 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);668669 const startTime = (new Date()).getTime();670 let result;671 let error = null;672 const log = {673 type: this.chainLogType.RPC,674 call: rpc,675 params,676 } as IUniqueHelperLog;677678 try {679 result = await this.constructApiCall(rpc, params);680 }681 catch(e) {682 error = e;683 }684685 const endTime = (new Date()).getTime();686687 log.executedAt = endTime;688 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';689 log.executionTime = endTime - startTime;690691 this.chainLog.push(log);692693 if(error !== null) throw error;694695 return result;696 }697698 getSignerAddress(signer: IKeyringPair | string): string {699 if(typeof signer === 'string') return signer;700 return signer.address;701 }702703 fetchAllPalletNames(): string[] {704 if(this.api === null) throw Error('API not initialized');705 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());706 }707708 fetchMissingPalletNames(requiredPallets: string[]): string[] {709 const palletNames = this.fetchAllPalletNames();710 return requiredPallets.filter(p => !palletNames.includes(p));711 }712}713714715class HelperGroup<T extends ChainHelperBase> {716 helper: T;717718 constructor(uniqueHelper: T) {719 this.helper = uniqueHelper;720 }721}722723724class CollectionGroup extends HelperGroup<UniqueHelper> {725 726727728729730731732733734 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {735 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();736 }737738 739740741742743 async getTotalCount(): Promise<number> {744 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();745 }746747 748749750751752753754755756 async getData(collectionId: number): Promise<{757 id: number;758 name: string;759 description: string;760 tokensCount: number;761 admins: CrossAccountId[];762 normalizedOwner: TSubstrateAccount;763 raw: any764 } | null> {765 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);766 const humanCollection = collection.toHuman(), collectionData = {767 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],768 raw: humanCollection,769 } as any, jsonCollection = collection.toJSON();770 if (humanCollection === null) return null;771 collectionData.raw.limits = jsonCollection.limits;772 collectionData.raw.permissions = jsonCollection.permissions;773 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);774 for (const key of ['name', 'description']) {775 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);776 }777778 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))779 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)780 : 0;781 collectionData.admins = await this.getAdmins(collectionId);782783 return collectionData;784 }785786 787788789790791792793794 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {795 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();796797 return normalize798 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())799 : admins;800 }801802 803804805806807808809 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {810 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();811 return normalize812 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())813 : allowListed;814 }815816 817818819820821822823 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {824 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();825 }826827 828829830831832833834835 async burn(signer: TSigner, collectionId: number): Promise<boolean> {836 const result = await this.helper.executeExtrinsic(837 signer,838 'api.tx.unique.destroyCollection', [collectionId],839 true,840 );841842 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');843 }844845 846847848849850851852853854 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {855 const result = await this.helper.executeExtrinsic(856 signer,857 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],858 true,859 );860861 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');862 }863864 865866867868869870871872 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {873 const result = await this.helper.executeExtrinsic(874 signer,875 'api.tx.unique.confirmSponsorship', [collectionId],876 true,877 );878879 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');880 }881882 883884885886887888889890 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {891 const result = await this.helper.executeExtrinsic(892 signer,893 'api.tx.unique.removeCollectionSponsor', [collectionId],894 true,895 );896897 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');898 }899900 901902903904905906907908909910911912913914915916917 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {918 const result = await this.helper.executeExtrinsic(919 signer,920 'api.tx.unique.setCollectionLimits', [collectionId, limits],921 true,922 );923924 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');925 }926927 928929930931932933934935936 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {937 const result = await this.helper.executeExtrinsic(938 signer,939 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],940 true,941 );942943 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');944 }945946 947948949950951952953954955 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {956 const result = await this.helper.executeExtrinsic(957 signer,958 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],959 true,960 );961962 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');963 }964965 966967968969970971972973974 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {975 const result = await this.helper.executeExtrinsic(976 signer,977 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],978 true,979 );980981 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');982 }983984 985986987988989990991992 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {993 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();994 }995996 9979989991000100110021003 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1004 const result = await this.helper.executeExtrinsic(1005 signer,1006 'api.tx.unique.addToAllowList', [collectionId, addressObj],1007 true,1008 );10091010 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1011 }10121013 10141015101610171018101910201021 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1022 const result = await this.helper.executeExtrinsic(1023 signer,1024 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1025 true,1026 );10271028 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1029 }10301031 103210331034103510361037103810391040 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1041 const result = await this.helper.executeExtrinsic(1042 signer,1043 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1044 true,1045 );10461047 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1048 }10491050 105110521053105410551056105710581059 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1060 return await this.setPermissions(signer, collectionId, {nesting: permissions});1061 }10621063 10641065106610671068106910701071 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1072 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1073 }10741075 107610771078107910801081108210831084 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1085 const result = await this.helper.executeExtrinsic(1086 signer,1087 'api.tx.unique.setCollectionProperties', [collectionId, properties],1088 true,1089 );10901091 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1092 }10931094 10951096109710981099110011011102 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1103 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1104 }11051106 async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1107 const api = this.helper.getApi();1108 const props = (await api.query.common.collectionProperties(collectionId)).toJSON();1109 1110 return (props! as any).consumedSpace;1111 }11121113 async getCollectionOptions(collectionId: number) {1114 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1115 }11161117 111811191120112111221123112411251126 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1127 const result = await this.helper.executeExtrinsic(1128 signer,1129 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1130 true,1131 );11321133 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1134 }11351136 11371138113911401141114211431144114511461147 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1148 const result = await this.helper.executeExtrinsic(1149 signer,1150 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1151 true, 1152 );11531154 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1155 }11561157 1158115911601161116211631164116511661167116811691170 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1171 const result = await this.helper.executeExtrinsic(1172 signer,1173 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1174 true, 1175 );1176 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1177 }11781179 11801181118211831184118511861187118811891190 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1191 const burnResult = await this.helper.executeExtrinsic(1192 signer,1193 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1194 true, 1195 );1196 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1197 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1198 return burnedTokens.success;1199 }12001201 12021203120412051206120712081209121012111212 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1213 const burnResult = await this.helper.executeExtrinsic(1214 signer,1215 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1216 true, 1217 );1218 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1219 return burnedTokens.success && burnedTokens.tokens.length > 0;1220 }12211222 1223122412251226122712281229123012311232 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1233 const approveResult = await this.helper.executeExtrinsic(1234 signer,1235 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1236 true, 1237 );12381239 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1240 }12411242 1243124412451246124712481249125012511252 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1253 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1254 }12551256 1257125812591260126112621263 async getLastTokenId(collectionId: number): Promise<number> {1264 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1265 }12661267 12681269127012711272127312741275 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1276 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1277 }1278}12791280class NFTnRFT extends CollectionGroup {1281 12821283128412851286128712881289 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1290 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1291 }12921293 1294129512961297129812991300130113021303 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1304 properties: IProperty[];1305 owner: CrossAccountId;1306 normalizedOwner: CrossAccountId;1307 }| null> {1308 let tokenData;1309 if(typeof blockHashAt === 'undefined') {1310 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1311 }1312 else {1313 if(propertyKeys.length == 0) {1314 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1315 if(!collection) return null;1316 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1317 }1318 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1319 }1320 tokenData = tokenData.toHuman();1321 if (tokenData === null || tokenData.owner === null) return null;1322 const owner = {} as any;1323 for (const key of Object.keys(tokenData.owner)) {1324 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1325 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1326 : tokenData.owner[key];1327 }1328 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1329 return tokenData;1330 }13311332 13331334133513361337133813391340134113421343 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1344 const result = await this.helper.executeExtrinsic(1345 signer,1346 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1347 true,1348 );13491350 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1351 }13521353 13541355135613571358135913601361 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1362 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1363 }13641365 1366136713681369137013711372137313741375 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1376 const result = await this.helper.executeExtrinsic(1377 signer,1378 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1379 true,1380 );13811382 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1383 }13841385 138613871388138913901391139213931394 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1395 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1396 }13971398 139914001401140214031404140514061407 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1408 const result = await this.helper.executeExtrinsic(1409 signer,1410 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1411 true,1412 );14131414 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1415 }14161417 141814191420142114221423142414251426 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1427 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1428 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1429 for (const key of ['name', 'description', 'tokenPrefix']) {1430 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);1431 }1432 const creationResult = await this.helper.executeExtrinsic(1433 signer,1434 'api.tx.unique.createCollectionEx', [collectionOptions],1435 true, 1436 );1437 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1438 }14391440 getCollectionObject(_collectionId: number): any {1441 return null;1442 }14431444 getTokenObject(_collectionId: number, _tokenId: number): any {1445 return null;1446 }14471448 1449145014511452145314541455 async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1456 return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1457 }14581459 146014611462146314641465 async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1466 const result = await this.helper.executeExtrinsic(1467 signer,1468 'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1469 true,1470 );1471 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1472 }1473}147414751476class NFTGroup extends NFTnRFT {1477 147814791480148114821483 getCollectionObject(collectionId: number): UniqueNFTCollection {1484 return new UniqueNFTCollection(collectionId, this.helper);1485 }14861487 1488148914901491149214931494 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1495 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1496 }14971498 14991500150115021503150415051506 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1507 let owner;1508 if (typeof blockHashAt === 'undefined') {1509 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1510 } else {1511 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1512 }1513 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1514 }15151516 1517151815191520152115221523 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1524 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1525 }15261527 1528152915301531153215331534153515361537 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1538 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1539 }15401541 154215431544154515461547154815491550155115521553 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1554 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1555 }15561557 15581559156015611562156315641565 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1566 let owner;1567 if (typeof blockHashAt === 'undefined') {1568 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1569 } else {1570 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1571 }15721573 if (owner === null) return null;15741575 return owner.toHuman();1576 }15771578 15791580158115821583158415851586 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1587 let children;1588 if(typeof blockHashAt === 'undefined') {1589 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1590 } else {1591 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1592 }15931594 return children.toJSON().map((x: any) => {1595 return {collectionId: x.collection, tokenId: x.token};1596 });1597 }15981599 16001601160216031604160516061607 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1608 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1609 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1610 if(!result) {1611 throw Error('Unable to nest token!');1612 }1613 return result;1614 }16151616 161716181619162016211622162316241625 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1626 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1627 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1628 if(!result) {1629 throw Error('Unable to unnest token!');1630 }1631 return result;1632 }16331634 163516361637163816391640164116421643164416451646 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1647 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1648 }16491650 165116521653165416551656 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1657 const creationResult = await this.helper.executeExtrinsic(1658 signer,1659 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1660 nft: {1661 properties: data.properties,1662 },1663 }],1664 true,1665 );1666 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1667 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1668 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1669 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1670 }16711672 167316741675167616771678167916801681168216831684168516861687 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1688 const creationResult = await this.helper.executeExtrinsic(1689 signer,1690 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1691 true,1692 );1693 const collection = this.getCollectionObject(collectionId);1694 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1695 }16961697 169816991700170117021703170417051706170717081709171017111712171317141715 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1716 const rawTokens = [];1717 for (const token of tokens) {1718 const raw = {NFT: {properties: token.properties}};1719 rawTokens.push(raw);1720 }1721 const creationResult = await this.helper.executeExtrinsic(1722 signer,1723 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1724 true,1725 );1726 const collection = this.getCollectionObject(collectionId);1727 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1728 }17291730 1731173217331734173517361737173817391740 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1741 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1742 }1743}174417451746class RFTGroup extends NFTnRFT {1747 174817491750175117521753 getCollectionObject(collectionId: number): UniqueRFTCollection {1754 return new UniqueRFTCollection(collectionId, this.helper);1755 }17561757 1758175917601761176217631764 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1765 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1766 }17671768 1769177017711772177317741775 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1776 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1777 }17781779 17801781178217831784178517861787 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1788 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1789 }17901791 1792179317941795179617971798179918001801 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1802 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1803 }18041805 18061807180818091810181118121813181418151816 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1817 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1818 }18191820 182118221823182418251826182718281829183018311832 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1833 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1834 }18351836 1837183818391840184118421843 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1844 const creationResult = await this.helper.executeExtrinsic(1845 signer,1846 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1847 refungible: {1848 pieces: data.pieces,1849 properties: data.properties,1850 },1851 }],1852 true,1853 );1854 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1855 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1856 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1857 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1858 }18591860 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1861 throw Error('Not implemented');1862 const creationResult = await this.helper.executeExtrinsic(1863 signer,1864 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1865 true, 1866 );1867 const collection = this.getCollectionObject(collectionId);1868 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1869 }18701871 187218731874187518761877187818791880 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1881 const rawTokens = [];1882 for (const token of tokens) {1883 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1884 rawTokens.push(raw);1885 }1886 const creationResult = await this.helper.executeExtrinsic(1887 signer,1888 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1889 true,1890 );1891 const collection = this.getCollectionObject(collectionId);1892 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1893 }18941895 189618971898189919001901190219031904 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1905 return await super.burnToken(signer, collectionId, tokenId, amount);1906 }19071908 1909191019111912191319141915191619171918 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1919 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1920 }19211922 19231924192519261927192819291930193119321933 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1934 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1935 }19361937 1938193919401941194219431944 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1945 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1946 }19471948 194919501951195219531954195519561957 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1958 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1959 const repartitionResult = await this.helper.executeExtrinsic(1960 signer,1961 'api.tx.unique.repartition', [collectionId, tokenId, amount],1962 true,1963 );1964 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1965 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1966 }1967}196819691970class FTGroup extends CollectionGroup {1971 197219731974197519761977 getCollectionObject(collectionId: number): UniqueFTCollection {1978 return new UniqueFTCollection(collectionId, this.helper);1979 }19801981 1982198319841985198619871988198919901991199219931994 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1995 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1996 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1997 collectionOptions.mode = {fungible: decimalPoints};1998 for (const key of ['name', 'description', 'tokenPrefix']) {1999 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);2000 }2001 const creationResult = await this.helper.executeExtrinsic(2002 signer,2003 'api.tx.unique.createCollectionEx', [collectionOptions],2004 true,2005 );2006 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2007 }20082009 201020112012201320142015201620172018 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2019 const creationResult = await this.helper.executeExtrinsic(2020 signer,2021 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2022 fungible: {2023 value: amount,2024 },2025 }],2026 true, 2027 );2028 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2029 }20302031 20322033203420352036203720382039 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {2040 const rawTokens = [];2041 for (const token of tokens) {2042 const raw = {Fungible: {Value: token.value}};2043 rawTokens.push(raw);2044 }2045 const creationResult = await this.helper.executeExtrinsic(2046 signer,2047 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2048 true,2049 );2050 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2051 }20522053 205420552056205720582059 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2060 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2061 }20622063 2064206520662067206820692070 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2071 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2072 }20732074 207520762077207820792080208120822083 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2084 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2085 }20862087 2088208920902091209220932094209520962097 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2098 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2099 }21002101 21022103210421052106210721082109 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2110 return await super.burnToken(signer, collectionId, 0, amount);2111 }21122113 211421152116211721182119212021212122 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2123 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2124 }21252126 21272128212921302131 async getTotalPieces(collectionId: number): Promise<bigint> {2132 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2133 }21342135 2136213721382139214021412142214321442145 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2146 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2147 }21482149 2150215121522153215421552156 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2157 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2158 }2159}216021612162class ChainGroup extends HelperGroup<ChainHelperBase> {2163 21642165216621672168 getChainProperties(): IChainProperties {2169 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2170 return {2171 ss58Format: properties.ss58Format.toJSON(),2172 tokenDecimals: properties.tokenDecimals.toJSON(),2173 tokenSymbol: properties.tokenSymbol.toJSON(),2174 };2175 }21762177 21782179218021812182 async getLatestBlockNumber(): Promise<number> {2183 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2184 }21852186 218721882189219021912192 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2193 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2194 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2195 return blockHash;2196 }21972198 2199 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2200 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2201 if (!blockHash) return null;2202 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2203 }22042205 220622072208220922102211 async getNonce(address: TSubstrateAccount): Promise<number> {2212 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2213 }2214}22152216class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2217 221822192220222122222223 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2224 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2225 }22262227 22282229223022312232223322342235 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2236 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);22372238 let transfer = {from: null, to: null, amount: 0n} as any;2239 result.result.events.forEach(({event: {data, method, section}}) => {2240 if ((section === 'balances') && (method === 'Transfer')) {2241 transfer = {2242 from: this.helper.address.normalizeSubstrate(data[0]),2243 to: this.helper.address.normalizeSubstrate(data[1]),2244 amount: BigInt(data[2]),2245 };2246 }2247 });2248 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2249 && this.helper.address.normalizeSubstrate(address) === transfer.to2250 && BigInt(amount) === transfer.amount;2251 return isSuccess;2252 }22532254 22552256225722582259 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2260 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2261 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2262 }2263}22642265class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2266 226722682269227022712272 async getEthereum(address: TEthereumAccount): Promise<bigint> {2273 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2274 }22752276 22772278227922802281228222832284 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2285 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);22862287 let transfer = {from: null, to: null, amount: 0n} as any;2288 result.result.events.forEach(({event: {data, method, section}}) => {2289 if ((section === 'balances') && (method === 'Transfer')) {2290 transfer = {2291 from: data[0].toString(),2292 to: data[1].toString(),2293 amount: BigInt(data[2]),2294 };2295 }2296 });2297 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2298 && address === transfer.to2299 && BigInt(amount) === transfer.amount;2300 return isSuccess;2301 }2302}23032304class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2305 subBalanceGroup: SubstrateBalanceGroup<T>;2306 ethBalanceGroup: EthereumBalanceGroup<T>;23072308 constructor(helper: T) {2309 super(helper);2310 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2311 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2312 }23132314 getCollectionCreationPrice(): bigint {2315 return 2n * this.getOneTokenNominal();2316 }2317 23182319232023212322 getOneTokenNominal(): bigint {2323 const chainProperties = this.helper.chain.getChainProperties();2324 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2325 }23262327 232823292330233123322333 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2334 return this.subBalanceGroup.getSubstrate(address);2335 }23362337 23382339234023412342 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2343 return this.subBalanceGroup.getSubstrateFull(address);2344 }23452346 234723482349235023512352 getEthereum(address: TEthereumAccount): Promise<bigint> {2353 return this.ethBalanceGroup.getEthereum(address);2354 }23552356 23572358235923602361236223632364 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2365 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2366 }23672368 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2369 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);23702371 let transfer = {from: null, to: null, amount: 0n} as any;2372 result.result.events.forEach(({event: {data, method, section}}) => {2373 if ((section === 'balances') && (method === 'Transfer')) {2374 transfer = {2375 from: this.helper.address.normalizeSubstrate(data[0]),2376 to: this.helper.address.normalizeSubstrate(data[1]),2377 amount: BigInt(data[2]),2378 };2379 }2380 });2381 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2382 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2383 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2384 return isSuccess;2385 }2386}23872388class AddressGroup extends HelperGroup<ChainHelperBase> {2389 2390239123922393239423952396 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2397 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2398 }23992400 240124022403240424052406 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2407 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2408 }24092410 2411241224132414241524162417 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2418 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2419 }24202421 242224232424242524262427 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2428 return CrossAccountId.translateSubToEth(subAddress);2429 }24302431 243224332434243524362437 encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2438 const u8a :Uint8Array = typeof key === 'string'2439 ? hexToU8a(key)2440 : typeof key === 'bigint'2441 ? hexToU8a(key.toString(16))2442 : key;2443 2444 if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2445 throw new Error(`ss58Format is not valid, received ${typeof ss58Format} "${ss58Format}"`);2446 }2447 2448 const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2449 if (!allowedDecodedLengths.includes(u8a.length)) {2450 throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2451 }2452 2453 const u8aPrefix = ss58Format < 642454 ? new Uint8Array([ss58Format])2455 : new Uint8Array([2456 ((ss58Format & 0xfc) >> 2) | 0x40,2457 (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2458 ]);24592460 const input = u8aConcat(u8aPrefix, u8a);2461 2462 return base58Encode(u8aConcat(2463 input,2464 blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2465 ));2466 }24672468 24692470247124722473 restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2474 if (this.helper.api === null) {2475 throw 'Not connected';2476 }2477 const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2478 if (res === undefined || res === null) {2479 throw 'Restore address error';2480 }2481 return res.toString();2482 }24832484 24852486248724882489 convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2490 if (ethCrossAccount.sub === '0') {2491 return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2492 }2493 2494 const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2495 return {Substrate: ss58};2496 }24972498 paraSiblingSovereignAccount(paraid: number) {2499 2500 2501 const siblingPrefix = '0x7369626c';25022503 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2504 const suffix = '000000000000000000000000000000000000000000000000';25052506 return siblingPrefix + encodedParaId + suffix;2507 }2508}25092510class StakingGroup extends HelperGroup<UniqueHelper> {2511 2512251325142515251625172518 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2519 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2520 const _stakeResult = await this.helper.executeExtrinsic(2521 signer, 'api.tx.appPromotion.stake',2522 [amountToStake], true,2523 );2524 2525 return true;2526 }25272528 2529253025312532253325342535 async unstake(signer: TSigner, label?: string): Promise<number> {2536 if(typeof label === 'undefined') label = `${signer.address}`;2537 const _unstakeResult = await this.helper.executeExtrinsic(2538 signer, 'api.tx.appPromotion.unstake',2539 [], true,2540 );2541 2542 return 1;2543 }25442545 25462547254825492550 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2551 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2552 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2553 }25542555 25562557255825592560 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2561 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2562 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2563 return {2564 block: block.toBigInt(),2565 amount: amount.toBigInt(),2566 };2567 });2568 }25692570 25712572257325742575 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2576 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2577 }25782579 25802581258225832584 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2585 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2586 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2587 return {2588 block: block.toBigInt(),2589 amount: amount.toBigInt(),2590 };2591 });2592 return result;2593 }2594}25952596class SchedulerGroup extends HelperGroup<UniqueHelper> {2597 constructor(helper: UniqueHelper) {2598 super(helper);2599 }26002601 cancelScheduled(signer: TSigner, scheduledId: string) {2602 return this.helper.executeExtrinsic(2603 signer,2604 'api.tx.scheduler.cancelNamed',2605 [scheduledId],2606 true,2607 );2608 }26092610 changePriority(signer: TSigner, scheduledId: string, priority: number) {2611 return this.helper.executeExtrinsic(2612 signer,2613 'api.tx.scheduler.changeNamedPriority',2614 [scheduledId, priority],2615 true,2616 );2617 }26182619 scheduleAt<T extends UniqueHelper>(2620 executionBlockNumber: number,2621 options: ISchedulerOptions = {},2622 ) {2623 return this.schedule<T>('schedule', executionBlockNumber, options);2624 }26252626 scheduleAfter<T extends UniqueHelper>(2627 blocksBeforeExecution: number,2628 options: ISchedulerOptions = {},2629 ) {2630 return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2631 }26322633 schedule<T extends UniqueHelper>(2634 scheduleFn: 'schedule' | 'scheduleAfter',2635 blocksNum: number,2636 options: ISchedulerOptions = {},2637 ) {2638 2639 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2640 return this.helper.clone(ScheduledHelperType, {2641 scheduleFn,2642 blocksNum,2643 options,2644 }) as T;2645 }2646}26472648class SessionGroup extends HelperGroup<ChainHelperBase> {2649 2650 async getIndex(): Promise<number> {2651 return (await this.helper.callRpc('api.query.session.currentIndex')).toNumber();2652 }26532654 newSessions(sessionCount = 1, blockTimeout = 24000): Promise<void> {2655 return (this.helper as DevUniqueHelper).wait.newSessions(sessionCount, blockTimeout);2656 }26572658 setOwnKeys(signer: TSigner, key: string) {2659 return this.helper.executeExtrinsic(2660 signer,2661 'api.tx.session.setKeys', 2662 [key, '0x0'],2663 true,2664 );2665 }26662667 setOwnKeysFromAddress(signer: TSigner) {2668 return this.setOwnKeys(signer, '0x' + Buffer.from(signer.addressRaw).toString('hex'));2669 }2670}26712672class CollatorSelectionGroup extends HelperGroup<UniqueHelper> {2673 2674 addInvulnerable(signer: TSigner, address: string) {2675 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.addInvulnerable', [address]);2676 }26772678 removeInvulnerable(signer: TSigner, address: string) {2679 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.removeInvulnerable', [address]);2680 }26812682 async getInvulnerables(): Promise<string[]> {2683 return (await this.helper.callRpc('api.query.collatorSelection.invulnerables')).map((x: any) => x.toHuman());2684 }26852686 setLicenseBond(signer: TSigner, amount: bigint) {2687 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.setLicenseBond', [amount]);2688 }26892690 async getLicenseBond(): Promise<bigint> {2691 return (await this.helper.callRpc('api.query.collatorSelection.licenseBond')).toBigInt();2692 }26932694 obtainLicense(signer: TSigner) {2695 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.getLicense', []);2696 }26972698 releaseLicense(signer: TSigner) {2699 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.releaseLicense', []);2700 }27012702 forceRevokeLicense(signer: TSigner, released: string) {2703 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.forceRevokeLicense', [released]);2704 }27052706 async hasLicense(address: string): Promise<bigint> {2707 return (await this.helper.callRpc('api.query.collatorSelection.licenses', [address])).toBigInt();2708 }27092710 onboard(signer: TSigner) {2711 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.onboard', []);2712 }27132714 offboard(signer: TSigner) {2715 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.offboard', []);2716 }27172718 async getCandidates(): Promise<string[]> {2719 return (await this.helper.callRpc('api.query.collatorSelection.candidates')).map((x: any) => x.toHuman());2720 }2721}27222723class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2724 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2725 await this.helper.executeExtrinsic(2726 signer,2727 'api.tx.foreignAssets.registerForeignAsset',2728 [ownerAddress, location, metadata],2729 true,2730 );2731 }27322733 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2734 await this.helper.executeExtrinsic(2735 signer,2736 'api.tx.foreignAssets.updateForeignAsset',2737 [foreignAssetId, location, metadata],2738 true,2739 );2740 }2741}27422743class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2744 palletName: string;27452746 constructor(helper: T, palletName: string) {2747 super(helper);27482749 this.palletName = palletName;2750 }27512752 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2753 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2754 }2755}27562757class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2758 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2759 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2760 }27612762 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2763 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2764 }27652766 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2767 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2768 }2769}27702771class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2772 async accounts(address: string, currencyId: any) {2773 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2774 return BigInt(free);2775 }2776}27772778class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2779 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2780 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2781 }27822783 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2784 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2785 }27862787 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2788 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2789 }27902791 async account(assetId: string | number, address: string) {2792 const accountAsset = (2793 await this.helper.callRpc('api.query.assets.account', [assetId, address])2794 ).toJSON()! as any;27952796 if (accountAsset !== null) {2797 return BigInt(accountAsset['balance']);2798 } else {2799 return null;2800 }2801 }2802}28032804class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2805 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2806 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2807 }2808}28092810class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2811 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2812 const apiPrefix = 'api.tx.assetManager.';28132814 const registerTx = this.helper.constructApiCall(2815 apiPrefix + 'registerForeignAsset',2816 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2817 );28182819 const setUnitsTx = this.helper.constructApiCall(2820 apiPrefix + 'setAssetUnitsPerSecond',2821 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2822 );28232824 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2825 const encodedProposal = batchCall?.method.toHex() || '';2826 return encodedProposal;2827 }28282829 async assetTypeId(location: any) {2830 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2831 }2832}28332834class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2835 async notePreimage(signer: TSigner, encodedProposal: string) {2836 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2837 }28382839 externalProposeMajority(proposalHash: string) {2840 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2841 }28422843 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2844 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2845 }28462847 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2848 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2849 }2850}28512852class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2853 collective: string;28542855 constructor(helper: MoonbeamHelper, collective: string) {2856 super(helper);28572858 this.collective = collective;2859 }28602861 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2862 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2863 }28642865 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2866 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2867 }28682869 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2870 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2871 }28722873 async proposalCount() {2874 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2875 }2876}28772878export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2879export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;28802881export class UniqueHelper extends ChainHelperBase {2882 balance: BalanceGroup<UniqueHelper>;2883 collection: CollectionGroup;2884 nft: NFTGroup;2885 rft: RFTGroup;2886 ft: FTGroup;2887 staking: StakingGroup;2888 scheduler: SchedulerGroup;2889 collatorSelection: CollatorSelectionGroup;2890 foreignAssets: ForeignAssetsGroup;2891 xcm: XcmGroup<UniqueHelper>;2892 xTokens: XTokensGroup<UniqueHelper>;2893 tokens: TokensGroup<UniqueHelper>;28942895 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2896 super(logger, options.helperBase ?? UniqueHelper);28972898 this.balance = new BalanceGroup(this);2899 this.collection = new CollectionGroup(this);2900 this.nft = new NFTGroup(this);2901 this.rft = new RFTGroup(this);2902 this.ft = new FTGroup(this);2903 this.staking = new StakingGroup(this);2904 this.scheduler = new SchedulerGroup(this);2905 this.collatorSelection = new CollatorSelectionGroup(this);2906 this.foreignAssets = new ForeignAssetsGroup(this);2907 this.xcm = new XcmGroup(this, 'polkadotXcm');2908 this.xTokens = new XTokensGroup(this);2909 this.tokens = new TokensGroup(this);2910 }29112912 getSudo<T extends UniqueHelper>() {2913 2914 const SudoHelperType = SudoHelper(this.helperBase);2915 return this.clone(SudoHelperType) as T;2916 }2917}29182919export class XcmChainHelper extends ChainHelperBase {2920 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2921 const wsProvider = new WsProvider(wsEndpoint);2922 this.api = new ApiPromise({2923 provider: wsProvider,2924 });2925 await this.api.isReadyOrError;2926 this.network = await UniqueHelper.detectNetwork(this.api);2927 }2928}29292930export class RelayHelper extends XcmChainHelper {2931 xcm: XcmGroup<RelayHelper>;29322933 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2934 super(logger, options.helperBase ?? RelayHelper);29352936 this.xcm = new XcmGroup(this, 'xcmPallet');2937 }2938}29392940export class WestmintHelper extends XcmChainHelper {2941 balance: SubstrateBalanceGroup<WestmintHelper>;2942 xcm: XcmGroup<WestmintHelper>;2943 assets: AssetsGroup<WestmintHelper>;2944 xTokens: XTokensGroup<WestmintHelper>;29452946 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2947 super(logger, options.helperBase ?? WestmintHelper);29482949 this.balance = new SubstrateBalanceGroup(this);2950 this.xcm = new XcmGroup(this, 'polkadotXcm');2951 this.assets = new AssetsGroup(this);2952 this.xTokens = new XTokensGroup(this);2953 }2954}29552956export class MoonbeamHelper extends XcmChainHelper {2957 balance: EthereumBalanceGroup<MoonbeamHelper>;2958 assetManager: MoonbeamAssetManagerGroup;2959 assets: AssetsGroup<MoonbeamHelper>;2960 xTokens: XTokensGroup<MoonbeamHelper>;2961 democracy: MoonbeamDemocracyGroup;2962 collective: {2963 council: MoonbeamCollectiveGroup,2964 techCommittee: MoonbeamCollectiveGroup,2965 };29662967 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2968 super(logger, options.helperBase ?? MoonbeamHelper);29692970 this.balance = new EthereumBalanceGroup(this);2971 this.assetManager = new MoonbeamAssetManagerGroup(this);2972 this.assets = new AssetsGroup(this);2973 this.xTokens = new XTokensGroup(this);2974 this.democracy = new MoonbeamDemocracyGroup(this);2975 this.collective = {2976 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2977 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2978 };2979 }2980}29812982export class AcalaHelper extends XcmChainHelper {2983 balance: SubstrateBalanceGroup<AcalaHelper>;2984 assetRegistry: AcalaAssetRegistryGroup;2985 xTokens: XTokensGroup<AcalaHelper>;2986 tokens: TokensGroup<AcalaHelper>;29872988 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2989 super(logger, options.helperBase ?? AcalaHelper);29902991 this.balance = new SubstrateBalanceGroup(this);2992 this.assetRegistry = new AcalaAssetRegistryGroup(this);2993 this.xTokens = new XTokensGroup(this);2994 this.tokens = new TokensGroup(this);2995 }29962997 getSudo<T extends AcalaHelper>() {2998 2999 const SudoHelperType = SudoHelper(this.helperBase);3000 return this.clone(SudoHelperType) as T;3001 }3002}300330043005function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3006 return class extends Base {3007 scheduleFn: 'schedule' | 'scheduleAfter';3008 blocksNum: number;3009 options: ISchedulerOptions;30103011 constructor(...args: any[]) {3012 const logger = args[0] as ILogger;3013 const options = args[1] as {3014 scheduleFn: 'schedule' | 'scheduleAfter',3015 blocksNum: number,3016 options: ISchedulerOptions3017 };30183019 super(logger);30203021 this.scheduleFn = options.scheduleFn;3022 this.blocksNum = options.blocksNum;3023 this.options = options.options;3024 }30253026 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3027 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);3028 3029 const mandatorySchedArgs = [3030 this.blocksNum,3031 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3032 this.options.priority ?? null,3033 scheduledTx,3034 ];3035 3036 let schedArgs;3037 let scheduleFn;30383039 if (this.options.scheduledId) {3040 schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];30413042 if (this.scheduleFn == 'schedule') {3043 scheduleFn = 'scheduleNamed';3044 } else if (this.scheduleFn == 'scheduleAfter') {3045 scheduleFn = 'scheduleNamedAfter';3046 }3047 } else {3048 schedArgs = mandatorySchedArgs;3049 scheduleFn = this.scheduleFn;3050 }30513052 const extrinsic = 'api.tx.scheduler.' + scheduleFn;30533054 return super.executeExtrinsic(3055 sender,3056 extrinsic,3057 schedArgs,3058 expectSuccess,3059 );3060 }3061 };3062}306330643065function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3066 return class extends Base {3067 constructor(...args: any[]) {3068 super(...args);3069 }30703071 async executeExtrinsic(3072 sender: IKeyringPair,3073 extrinsic: string,3074 params: any[],3075 expectSuccess?: boolean,3076 options: Partial<SignerOptions>|null = null,3077 ): Promise<ITransactionResult> {3078 const call = this.constructApiCall(extrinsic, params);3079 const result = await super.executeExtrinsic(3080 sender,3081 'api.tx.sudo.sudo',3082 [call],3083 expectSuccess,3084 options,3085 );30863087 if (result.status === 'Fail') return result;30883089 const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;3090 if (data.isErr) {3091 if (data.asErr.isModule) {3092 const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;3093 const metaError = super.getApi()?.registry.findMetaError(error);3094 throw new Error(`${metaError.section}.${metaError.name}`);3095 } else {3096 throw new Error(data.asErr.toHuman());3097 }3098 }3099 return result;3100 }3101 };3102}31033104export class UniqueBaseCollection {3105 helper: UniqueHelper;3106 collectionId: number;31073108 constructor(collectionId: number, uniqueHelper: UniqueHelper) {3109 this.collectionId = collectionId;3110 this.helper = uniqueHelper;3111 }31123113 async getData() {3114 return await this.helper.collection.getData(this.collectionId);3115 }31163117 async getLastTokenId() {3118 return await this.helper.collection.getLastTokenId(this.collectionId);3119 }31203121 async doesTokenExist(tokenId: number) {3122 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3123 }31243125 async getAdmins() {3126 return await this.helper.collection.getAdmins(this.collectionId);3127 }31283129 async getAllowList() {3130 return await this.helper.collection.getAllowList(this.collectionId);3131 }31323133 async getEffectiveLimits() {3134 return await this.helper.collection.getEffectiveLimits(this.collectionId);3135 }31363137 async getProperties(propertyKeys?: string[] | null) {3138 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3139 }31403141 async getPropertiesConsumedSpace() {3142 return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3143 }31443145 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3146 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3147 }31483149 async getOptions() {3150 return await this.helper.collection.getCollectionOptions(this.collectionId);3151 }31523153 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3154 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3155 }31563157 async confirmSponsorship(signer: TSigner) {3158 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3159 }31603161 async removeSponsor(signer: TSigner) {3162 return await this.helper.collection.removeSponsor(signer, this.collectionId);3163 }31643165 async setLimits(signer: TSigner, limits: ICollectionLimits) {3166 return await this.helper.collection.setLimits(signer, this.collectionId, limits);3167 }31683169 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3170 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3171 }31723173 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3174 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3175 }31763177 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3178 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3179 }31803181 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3182 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3183 }31843185 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3186 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3187 }31883189 async setProperties(signer: TSigner, properties: IProperty[]) {3190 return await this.helper.collection.setProperties(signer, this.collectionId, properties);3191 }31923193 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3194 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3195 }31963197 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3198 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3199 }32003201 async enableNesting(signer: TSigner, permissions: INestingPermissions) {3202 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3203 }32043205 async disableNesting(signer: TSigner) {3206 return await this.helper.collection.disableNesting(signer, this.collectionId);3207 }32083209 async burn(signer: TSigner) {3210 return await this.helper.collection.burn(signer, this.collectionId);3211 }32123213 scheduleAt<T extends UniqueHelper>(3214 executionBlockNumber: number,3215 options: ISchedulerOptions = {},3216 ) {3217 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3218 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3219 }32203221 scheduleAfter<T extends UniqueHelper>(3222 blocksBeforeExecution: number,3223 options: ISchedulerOptions = {},3224 ) {3225 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3226 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3227 }32283229 getSudo<T extends UniqueHelper>() {3230 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3231 }3232}323332343235export class UniqueNFTCollection extends UniqueBaseCollection {3236 getTokenObject(tokenId: number) {3237 return new UniqueNFToken(tokenId, this);3238 }32393240 async getTokensByAddress(addressObj: ICrossAccountId) {3241 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3242 }32433244 async getToken(tokenId: number, blockHashAt?: string) {3245 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3246 }32473248 async getTokenOwner(tokenId: number, blockHashAt?: string) {3249 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3250 }32513252 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3253 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3254 }32553256 async getTokenChildren(tokenId: number, blockHashAt?: string) {3257 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3258 }32593260 async getPropertyPermissions(propertyKeys: string[] | null = null) {3261 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3262 }32633264 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3265 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3266 }32673268 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3269 const api = this.helper.getApi();3270 const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();3271 3272 return (props! as any).consumedSpace;3273 }32743275 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3276 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3277 }32783279 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3280 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3281 }32823283 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3284 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3285 }32863287 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3288 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3289 }32903291 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3292 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3293 }32943295 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3296 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3297 }32983299 async burnToken(signer: TSigner, tokenId: number) {3300 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3301 }33023303 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3304 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3305 }33063307 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3308 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3309 }33103311 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3312 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3313 }33143315 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3316 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3317 }33183319 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3320 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3321 }33223323 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3324 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3325 }33263327 scheduleAt<T extends UniqueHelper>(3328 executionBlockNumber: number,3329 options: ISchedulerOptions = {},3330 ) {3331 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3332 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3333 }33343335 scheduleAfter<T extends UniqueHelper>(3336 blocksBeforeExecution: number,3337 options: ISchedulerOptions = {},3338 ) {3339 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3340 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3341 }33423343 getSudo<T extends UniqueHelper>() {3344 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3345 }3346}334733483349export class UniqueRFTCollection extends UniqueBaseCollection {3350 getTokenObject(tokenId: number) {3351 return new UniqueRFToken(tokenId, this);3352 }33533354 async getToken(tokenId: number, blockHashAt?: string) {3355 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3356 }33573358 async getTokensByAddress(addressObj: ICrossAccountId) {3359 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3360 }33613362 async getTop10TokenOwners(tokenId: number) {3363 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3364 }33653366 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3367 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3368 }33693370 async getTokenTotalPieces(tokenId: number) {3371 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3372 }33733374 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3375 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3376 }33773378 async getPropertyPermissions(propertyKeys: string[] | null = null) {3379 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3380 }33813382 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3383 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3384 }33853386 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3387 const api = this.helper.getApi();3388 const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();3389 3390 return (props! as any).consumedSpace;3391 }33923393 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3394 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3395 }33963397 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3398 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3399 }34003401 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3402 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3403 }34043405 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3406 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3407 }34083409 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3410 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3411 }34123413 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3414 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3415 }34163417 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3418 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3419 }34203421 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3422 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3423 }34243425 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3426 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3427 }34283429 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3430 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3431 }34323433 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3434 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3435 }34363437 scheduleAt<T extends UniqueHelper>(3438 executionBlockNumber: number,3439 options: ISchedulerOptions = {},3440 ) {3441 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3442 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3443 }34443445 scheduleAfter<T extends UniqueHelper>(3446 blocksBeforeExecution: number,3447 options: ISchedulerOptions = {},3448 ) {3449 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3450 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3451 }34523453 getSudo<T extends UniqueHelper>() {3454 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3455 }3456}345734583459export class UniqueFTCollection extends UniqueBaseCollection {3460 async getBalance(addressObj: ICrossAccountId) {3461 return await this.helper.ft.getBalance(this.collectionId, addressObj);3462 }34633464 async getTotalPieces() {3465 return await this.helper.ft.getTotalPieces(this.collectionId);3466 }34673468 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3469 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3470 }34713472 async getTop10Owners() {3473 return await this.helper.ft.getTop10Owners(this.collectionId);3474 }34753476 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3477 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3478 }34793480 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3481 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3482 }34833484 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3485 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3486 }34873488 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3489 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3490 }34913492 async burnTokens(signer: TSigner, amount=1n) {3493 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3494 }34953496 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3497 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3498 }34993500 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3501 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3502 }35033504 scheduleAt<T extends UniqueHelper>(3505 executionBlockNumber: number,3506 options: ISchedulerOptions = {},3507 ) {3508 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3509 return new UniqueFTCollection(this.collectionId, scheduledHelper);3510 }35113512 scheduleAfter<T extends UniqueHelper>(3513 blocksBeforeExecution: number,3514 options: ISchedulerOptions = {},3515 ) {3516 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3517 return new UniqueFTCollection(this.collectionId, scheduledHelper);3518 }35193520 getSudo<T extends UniqueHelper>() {3521 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3522 }3523}352435253526export class UniqueBaseToken {3527 collection: UniqueNFTCollection | UniqueRFTCollection;3528 collectionId: number;3529 tokenId: number;35303531 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3532 this.collection = collection;3533 this.collectionId = collection.collectionId;3534 this.tokenId = tokenId;3535 }35363537 async getNextSponsored(addressObj: ICrossAccountId) {3538 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3539 }35403541 async getProperties(propertyKeys?: string[] | null) {3542 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3543 }35443545 async getTokenPropertiesConsumedSpace() {3546 return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3547 }35483549 async setProperties(signer: TSigner, properties: IProperty[]) {3550 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3551 }35523553 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3554 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3555 }35563557 async doesExist() {3558 return await this.collection.doesTokenExist(this.tokenId);3559 }35603561 nestingAccount() {3562 return this.collection.helper.util.getTokenAccount(this);3563 }35643565 scheduleAt<T extends UniqueHelper>(3566 executionBlockNumber: number,3567 options: ISchedulerOptions = {},3568 ) {3569 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3570 return new UniqueBaseToken(this.tokenId, scheduledCollection);3571 }35723573 scheduleAfter<T extends UniqueHelper>(3574 blocksBeforeExecution: number,3575 options: ISchedulerOptions = {},3576 ) {3577 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3578 return new UniqueBaseToken(this.tokenId, scheduledCollection);3579 }35803581 getSudo<T extends UniqueHelper>() {3582 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3583 }3584}358535863587export class UniqueNFToken extends UniqueBaseToken {3588 collection: UniqueNFTCollection;35893590 constructor(tokenId: number, collection: UniqueNFTCollection) {3591 super(tokenId, collection);3592 this.collection = collection;3593 }35943595 async getData(blockHashAt?: string) {3596 return await this.collection.getToken(this.tokenId, blockHashAt);3597 }35983599 async getOwner(blockHashAt?: string) {3600 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3601 }36023603 async getTopmostOwner(blockHashAt?: string) {3604 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3605 }36063607 async getChildren(blockHashAt?: string) {3608 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3609 }36103611 async nest(signer: TSigner, toTokenObj: IToken) {3612 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3613 }36143615 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3616 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3617 }36183619 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3620 return await this.collection.transferToken(signer, this.tokenId, addressObj);3621 }36223623 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3624 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3625 }36263627 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3628 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3629 }36303631 async isApproved(toAddressObj: ICrossAccountId) {3632 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3633 }36343635 async burn(signer: TSigner) {3636 return await this.collection.burnToken(signer, this.tokenId);3637 }36383639 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3640 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3641 }36423643 scheduleAt<T extends UniqueHelper>(3644 executionBlockNumber: number,3645 options: ISchedulerOptions = {},3646 ) {3647 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3648 return new UniqueNFToken(this.tokenId, scheduledCollection);3649 }36503651 scheduleAfter<T extends UniqueHelper>(3652 blocksBeforeExecution: number,3653 options: ISchedulerOptions = {},3654 ) {3655 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3656 return new UniqueNFToken(this.tokenId, scheduledCollection);3657 }36583659 getSudo<T extends UniqueHelper>() {3660 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3661 }3662}36633664export class UniqueRFToken extends UniqueBaseToken {3665 collection: UniqueRFTCollection;36663667 constructor(tokenId: number, collection: UniqueRFTCollection) {3668 super(tokenId, collection);3669 this.collection = collection;3670 }36713672 async getData(blockHashAt?: string) {3673 return await this.collection.getToken(this.tokenId, blockHashAt);3674 }36753676 async getTop10Owners() {3677 return await this.collection.getTop10TokenOwners(this.tokenId);3678 }36793680 async getBalance(addressObj: ICrossAccountId) {3681 return await this.collection.getTokenBalance(this.tokenId, addressObj);3682 }36833684 async getTotalPieces() {3685 return await this.collection.getTokenTotalPieces(this.tokenId);3686 }36873688 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3689 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3690 }36913692 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3693 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3694 }36953696 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3697 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3698 }36993700 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3701 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3702 }37033704 async repartition(signer: TSigner, amount: bigint) {3705 return await this.collection.repartitionToken(signer, this.tokenId, amount);3706 }37073708 async burn(signer: TSigner, amount=1n) {3709 return await this.collection.burnToken(signer, this.tokenId, amount);3710 }37113712 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3713 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3714 }37153716 scheduleAt<T extends UniqueHelper>(3717 executionBlockNumber: number,3718 options: ISchedulerOptions = {},3719 ) {3720 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3721 return new UniqueRFToken(this.tokenId, scheduledCollection);3722 }37233724 scheduleAfter<T extends UniqueHelper>(3725 blocksBeforeExecution: number,3726 options: ISchedulerOptions = {},3727 ) {3728 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3729 return new UniqueRFToken(this.tokenId, scheduledCollection);3730 }37313732 getSudo<T extends UniqueHelper>() {3733 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3734 }3735}