UNPKG

@broxus/js-core

Version:

MobX-based JavaScript Core library

478 lines (477 loc) 19.8 kB
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; import { debounce, debug, error, throwException } from '@broxus/js-utils'; import { action, computed, makeObservable } from 'mobx'; import { inheritTextStyle, successLabelStyle, successTextStyle, warningLabelStyle } from '../../console'; import { SECONDS_IN_HOUR } from '../../constants'; import { SmartContractModel } from '../../core'; import { DexPair } from '../../models/dex-pair'; import { DexStablePool } from '../../models/dex-stable-pool'; import { DexUtils, } from '../../models/dex/DexUtils'; import { areAddressesEqual, contractStateChangeDebugMessage, getFullContractState, getRandomInt, ProviderNotDefinedError, subscribeDebugMessage, syncErrorMessage, unsubscribeDebugMessage, unsubscribeErrorMessage, } from '../../utils'; export class Dex extends SmartContractModel { _connection; options; _provider; static Utils = DexUtils; /** * @param {ProviderRpcClient} _connection * Standalone RPC client that doesn't require connection to the TVM wallet provider * @param {Address | string} address * DexRoot root address * @param {Readonly<DexCtorOptions>} [options] * (optional) DexRoot Smart Contract Model options * @param {ProviderRpcClient} [_provider] * (optional) RPC provider that require connection to the TVM wallet */ constructor(_connection, address, options, _provider) { super(_connection, address); this._connection = _connection; this.options = options; this._provider = _provider; makeObservable(this); } /** * @param {ProviderRpcClient} connection * Standalone RPC client that doesn't require connection to the TVM wallet provider * @param {Address | string} address * DexRoot root address * @param {Readonly<DexCreateOptions>} [options] * (optional) DexRoot Smart Contract Model options * @param {ProviderRpcClient} [provider] * (optional) RPC provider that require connection to the TVM wallet */ static async create(connection, address, options, provider) { const { sync = true, watch, watchCallback, ...restOptions } = { ...options }; const dex = new Dex(connection, address, restOptions, provider); if (sync) { await dex.sync({ force: false, ttl: options?.ttl }); } if (watch) { await dex.watch(watchCallback); } return dex; } async sync(options) { if (!options?.force && this.isSyncing) { return; } try { this.setState('isSyncing', !options?.silent); const state = await this.syncContractState({ force: options?.force || !this.contractState, ttl: options?.ttl || SECONDS_IN_HOUR * 1000, }); if (!this.isDeployed) { await this.syncComputedStorageData(); throwException('Dex is not deployed'); } const [manager, owner, vault] = await Promise.all([ Dex.Utils.getManager(this._connection, this.address, state), Dex.Utils.getOwner(this._connection, this.address, state), Dex.Utils.getVault(this._connection, this.address, state), ]); this.setData({ manager, owner, vault }); } catch (e) { if (process.env.NODE_ENV !== 'production') { const state = await this._connection.getProviderState(); syncErrorMessage(this.constructor.name, this.address, e, state.networkId.toString()); } } finally { this.setState('isSyncing', false); } } async watch(callback) { try { this.contractSubscriber = new this._connection.Subscriber(); await this.contractSubscriber.states(this.address).delayed(stream => { if (process.env.NODE_ENV !== 'production') { subscribeDebugMessage(this.constructor.name, this.address); } return stream.on(debounce(async (event) => { if (process.env.NODE_ENV !== 'production') { const state = await this._connection.getProviderState(); contractStateChangeDebugMessage(this.constructor.name, this.address, event, state.networkId.toString()); } if (areAddressesEqual(event.address, this.address)) { await this.sync({ force: !this.isSyncing, silent: true }); callback?.(...this.toJSON(true)); return; } await this.unwatch(); }, this.options?.watchDebounceDelay ?? 3000)); }); return this.contractSubscriber; } catch (e) { await this.unwatch(); throw e; } } async unwatch() { try { await this.contractSubscriber?.unsubscribe(); this.contractSubscriber = undefined; if (process.env.NODE_ENV !== 'production') { unsubscribeDebugMessage(this.constructor.name, this.address); } } catch (e) { if (process.env.NODE_ENV !== 'production') { const state = await this._connection.getProviderState(); unsubscribeErrorMessage(this.constructor.name, this.address, e, state.networkId.toString()); } } } async deployAccount(params, args) { if (!this._provider) { throw new ProviderNotDefinedError(this.constructor.name); } const callId = params.callId ?? getRandomInt(); const subscriber = new this._connection.Subscriber(); let transaction; try { const expectedAddress = await this.getExpectedAccountAddress({ ownerAddress: params.ownerAddress }); const message = await Dex.Utils.deployAccount(this._provider, this.address, params, args); await params.onSend?.(message, { callId }); transaction = await message.transaction; await params.onTransactionSent?.({ callId, transaction }); const stream = await subscriber .trace(transaction) .filterMap(async (tx) => { if (!areAddressesEqual(tx.account, expectedAddress)) { return undefined; } const state = await getFullContractState(this._connection, expectedAddress, { force: true }); if (!state?.isDeployed) { return undefined; } await params.onTransactionSuccess?.({ callId, input: { callId, dexAccountAddress: expectedAddress, }, transaction: tx, }); return tx.account; }) .delayed(s => s.first()); await stream(); return transaction; } catch (e) { params.onTransactionFailure?.({ callId, error: e, transaction, }); throw e; } finally { if (process.env.NODE_ENV !== 'production') { debug(`%c${this.constructor.name}%c Unsubscribe from DexAccount deploying stream`, warningLabelStyle, inheritTextStyle); } await subscriber?.unsubscribe(); } } /** * Stream-based **DexPair** deployment request * @param {DexDeployPairParams} params * @param {Partial<SendInternalParams>} args * @return {Promise<Transaction | undefined>} */ async deployPair(params, args) { if (!this._provider) { throw new ProviderNotDefinedError(this.constructor.name); } const callId = params.callId ?? getRandomInt(); const subscriber = new this._connection.Subscriber(); let transaction; try { const message = await Dex.Utils.deployPair(this._provider, this.address, { leftRootAddress: params.leftRootAddress, rightRootAddress: params.rightRootAddress, sendGasTo: params.sendGasTo, }, { bounce: true, ...args }); await params.onSend?.(message, { callId }); transaction = await message.transaction; await params.onTransactionSent?.({ callId, transaction }); const stream = await subscriber .trace(transaction) .filterMap(async (tx) => { if (!areAddressesEqual(tx.account, this.address)) { return undefined; } try { const events = await this.decodeTransactionEvents(tx); if (events.length === 0) { return undefined; } const event = events.find(e => e.event === 'NewPoolCreated'); if (!event) { return undefined; } const [leftRootAddress, rightRootAddress] = event.data.roots; const address = await this.getExpectedPairAddress({ leftRootAddress, rightRootAddress }); if (!areAddressesEqual(params.expectedAddress, address)) { return undefined; } const isActive = await DexPair.Utils.isActive(this._connection, address); if (isActive) { if (process.env.NODE_ENV !== 'production') { debug(`%c${this.constructor.name}%c %cNewPoolCreated%c event was captured`, successLabelStyle, inheritTextStyle, successTextStyle, inheritTextStyle, event); } await params.onTransactionSuccess?.({ callId, input: { leftRootAddress, pairAddress: address, poolType: event.data.poolType, rightRootAddress, }, transaction: tx, }); return event; } return undefined; } catch (e) { error('NewPoolCreated event captured with an error', e); await params.onTransactionFailure?.({ callId, error: e, transaction: tx, }); return null; } }) .delayed(s => s.first()); await stream(); return transaction; } catch (e) { params.onTransactionFailure?.({ callId, error: e, }); throw e; } finally { if (process.env.NODE_ENV !== 'production') { debug(`%c${this.constructor.name}%c Unsubscribe from DexPair creating stream`, warningLabelStyle, inheritTextStyle); } await subscriber?.unsubscribe(); } } /** * Stream-based **DexStablePool** deployment request * @param {DexDeployPoolParams} params * @param {Partial<SendInternalParams>} args * @return {Promise<Transaction | undefined>} */ async deployStablePool(params, args) { if (!this._provider) { throw new ProviderNotDefinedError(this.constructor.name); } const callId = params.callId ?? getRandomInt(); const subscriber = new this._connection.Subscriber(); let transaction; try { const message = await Dex.Utils.deployStablePool(this._provider, this.address, { roots: params.roots, sendGasTo: params.sendGasTo, }, { bounce: true, ...args }); await params.onSend?.(message, { callId }); transaction = await message.transaction; await params.onTransactionSent?.({ callId, transaction }); const stream = await subscriber .trace(transaction) .filterMap(async (tx) => { if (!areAddressesEqual(tx.account, this.address)) { return undefined; } try { const events = await this.decodeTransactionEvents(tx); if (events.length === 0) { return undefined; } const event = events.find(e => e.event === 'NewPoolCreated'); if (!event) { return undefined; } const address = await this.getExpectedPoolAddress({ roots: event.data.roots }); if (!areAddressesEqual(params.expectedAddress, address)) { return undefined; } const isActive = await DexStablePool.Utils.isActive(this._connection, address); if (isActive) { if (process.env.NODE_ENV !== 'production') { debug(`%c${this.constructor.name}%c %cNewPoolCreated%c event was captured`, successLabelStyle, inheritTextStyle, successTextStyle, inheritTextStyle, event); } await params.onTransactionSuccess?.({ callId, input: { poolAddress: address, poolType: event.data.poolType, roots: event.data.roots, }, transaction: tx, }); return event; } return undefined; } catch (e) { error('NewPoolCreated event captured with an error', e); await params.onTransactionFailure?.({ callId, error: e, transaction: tx, }); return null; } }) .delayed(s => s.first()); await stream(); return transaction; } catch (e) { params.onTransactionFailure?.({ callId, error: e, transaction, }); throw e; } finally { if (process.env.NODE_ENV !== 'production') { debug(`%c${this.constructor.name}%c Unsubscribe from StablePool creating stream`, warningLabelStyle, inheritTextStyle); } await subscriber?.unsubscribe(); } } getExpectedAccountAddress(params) { return Dex.Utils.getExpectedAccountAddress(this._connection, this.address, params, this.contractState); } getExpectedPairAddress(params) { return Dex.Utils.getExpectedPairAddress(this._connection, this.address, params, this.contractState); } getExpectedPoolAddress(params) { return Dex.Utils.getExpectedPoolAddress(this._connection, this.address, params, this.contractState); } get manager() { return this._data.manager; } get owner() { return this._data.owner; } get vault() { return this._data.vault; } decodeEvent(args) { return Dex.Utils.decodeEvent(this._connection, this.address, args); } decodeTransaction(args) { return Dex.Utils.decodeTransaction(this._connection, this.address, args); } decodeTransactionEvents(transaction) { return Dex.Utils.decodeTransactionEvents(this._connection, this.address, transaction); } } __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], Dex.prototype, "sync", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Function]), __metadata("design:returntype", Promise) ], Dex.prototype, "watch", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", Promise) ], Dex.prototype, "unwatch", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", Promise) ], Dex.prototype, "deployAccount", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", Promise) ], Dex.prototype, "deployPair", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", Promise) ], Dex.prototype, "deployStablePool", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], Dex.prototype, "getExpectedAccountAddress", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], Dex.prototype, "getExpectedPairAddress", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], Dex.prototype, "getExpectedPoolAddress", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], Dex.prototype, "manager", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], Dex.prototype, "owner", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], Dex.prototype, "vault", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], Dex.prototype, "decodeEvent", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], Dex.prototype, "decodeTransaction", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], Dex.prototype, "decodeTransactionEvents", null);