UNPKG

@broxus/js-core

Version:

MobX-based JavaScript Core library

567 lines (566 loc) 22.2 kB
"use strict"; 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); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.StakingVault = void 0; const js_utils_1 = require("@broxus/js-utils"); const mobx_1 = require("mobx"); const console_1 = require("../../console"); const core_1 = require("../../core"); const StakingVaultUtils_1 = require("../../models/staking-vault/StakingVaultUtils"); const utils_1 = require("../../utils"); class StakingVault extends core_1.SmartContractModel { _connection; options; _provider; static Utils = StakingVaultUtils_1.StakingVaultUtils; /** * @param {ProviderRpcClient} _connection * Standalone RPC client that doesn't require connection to the TVM wallet provider * @param {Address | string} address * StakingVault root address * @param {Readonly<StakingVaultCtorOptions>} [options] * (optional) StakingVault 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; this.setData(() => ({})); (0, mobx_1.makeObservable)(this); } /** * @param {ProviderRpcClient} connection * Standalone RPC client that doesn't require connection to the TVM wallet provider * @param {Address | string} address * StakingVault root address * @param {Readonly<StakingVaultCreateOptions>} [options] * (optional) StakingVault 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 voteEscrow = new StakingVault(connection, address, restOptions, provider); if (sync) { await voteEscrow.sync({ force: false }); } if (watch) { await voteEscrow.watch(watchCallback); } return voteEscrow; } 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 }); if (!this.isDeployed) { (0, js_utils_1.throwException)('StakingVault is not deployed'); } const [details,] = await Promise.all([ StakingVault.Utils.getDetails(this._connection, this.address, state), ]); this.setData({ ...details }); } catch (e) { if (process.env.NODE_ENV !== 'production') { const state = await this._connection.getProviderState(); (0, utils_1.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') { (0, utils_1.subscribeDebugMessage)(this.constructor.name, this.address); } return stream.on((0, js_utils_1.debounce)(async (event) => { if (process.env.NODE_ENV !== 'production') { const state = await this._connection.getProviderState(); (0, utils_1.contractStateChangeDebugMessage)(this.constructor.name, this.address, event, state.networkId.toString()); } if ((0, utils_1.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() { if (this.contractSubscriber === undefined) { return; } try { await this.contractSubscriber?.unsubscribe(); this.contractSubscriber = undefined; if (process.env.NODE_ENV !== 'production') { (0, utils_1.unsubscribeDebugMessage)(this.constructor.name, this.address); } } catch (e) { if (process.env.NODE_ENV !== 'production') { const state = await this._connection.getProviderState(); (0, utils_1.unsubscribeErrorMessage)(this.constructor.name, this.address, e, state.networkId.toString()); } } } async deposit(params, args) { if (!this._provider) { throw new utils_1.ProviderNotDefinedError(this.constructor.name); } const callId = params.callId ?? (0, utils_1.getRandomInt)(); const subscriber = new this._connection.Subscriber(); let transaction; try { const message = await StakingVault.Utils.deposit(this._provider, this.address, { amount: params.amount, nonce: callId }, 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 (!(0, utils_1.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 === 'Deposit'); if (!event) { return undefined; } if (process.env.NODE_ENV !== 'production') { (0, js_utils_1.debug)(`%c${this.constructor.name}%c %cDeposit%c event was captured`, console_1.successLabelStyle, console_1.inheritTextStyle, console_1.successTextStyle, console_1.inheritTextStyle, event); } await params.onTransactionSuccess?.({ callId, input: { amount: event.data.depositAmount, stAmount: event.data.receivedStEvers, user: event.data.user, }, transaction: tx, }); return event; } catch (e) { (0, js_utils_1.error)('Deposit 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') { (0, js_utils_1.debug)(`%c${this.constructor.name}%c Unsubscribed from the depositing token [%c${(0, js_utils_1.sliceString)(this.stTokenRoot?.toString())}%c] stream`, console_1.warningLabelStyle, console_1.inheritTextStyle, console_1.successTextStyle, console_1.inheritTextStyle); } await subscriber?.unsubscribe(); } } async removePendingWithdraw(params, args) { if (!this._provider) { throw new utils_1.ProviderNotDefinedError(this.constructor.name); } const callId = params.callId ?? (0, utils_1.getRandomInt)(); const subscriber = new this._connection.Subscriber(); let transaction; try { const message = await StakingVault.Utils.removePendingWithdraw(this._provider, this.address, params.nonce, 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 (!(0, utils_1.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 === 'WithdrawRequestRemoved'); if (!event) { return undefined; } if (process.env.NODE_ENV !== 'production') { (0, js_utils_1.debug)(`%c${this.constructor.name}%c %cWithdrawRequestRemoved%c event was captured`, console_1.successLabelStyle, console_1.inheritTextStyle, console_1.successTextStyle, console_1.inheritTextStyle, event); } await params.onTransactionSuccess?.({ callId, input: { nonce: event.data.nonce, user: event.data.user, }, transaction: tx, }); return event; } catch (e) { (0, js_utils_1.error)('Withdraw request removed 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') { (0, js_utils_1.debug)(`%c${this.constructor.name}%c Unsubscribed from the withdraw removing request stream`, console_1.warningLabelStyle, console_1.inheritTextStyle, console_1.successTextStyle, console_1.inheritTextStyle); } await subscriber?.unsubscribe(); } } async encodeDepositPayload(nonce) { return StakingVault.Utils.encodeDepositPayload(this._connection, this.address, nonce, this.contractState); } async getAccountAddress(userAddress) { return StakingVault.Utils.getAccountAddress(this._connection, this.address, userAddress, this.contractState); } async getDepositExpectedAmount(amount) { return StakingVault.Utils.getDepositExpectedAmount(this._connection, this.address, amount, this.contractState); } async getWithdrawExpectedAmount(amount) { return StakingVault.Utils.getWithdrawExpectedAmount(this._connection, this.address, amount, this.contractState); } get nonce() { return this._data.nonce; } get governance() { return this._data.governance; } get stEverSupply() { return this._data.stEverSupply; } get totalAssets() { return this._data.totalAssets; } get availableAssets() { return this._data.availableAssets; } get totalStEverFee() { return this._data.totalStEverFee; } get effectiveEverAssets() { return this._data.effectiveEverAssets; } get remainingLockedAssets() { return this._data.remainingLockedAssets; } get unlockPerSecond() { return this._data.unlockPerSecond; } get stEverWallet() { return this._data.stEverWallet; } get stTokenRoot() { return this._data.stTokenRoot; } get lastUnlockTime() { return this._data.lastUnlockTime; } get fullUnlockSeconds() { return this._data.fullUnlockSeconds; } get remainingSeconds() { return this._data.remainingSeconds; } get gainFee() { return this._data.gainFee; } get stEverFeePercent() { return this._data.stEverFeePercent; } get minStrategyDepositValue() { return this._data.minStrategyDepositValue; } get minStrategyWithdrawValue() { return this._data.minStrategyWithdrawValue; } get isPaused() { return this._data.isPaused; } get strategyFactory() { return this._data.strategyFactory; } get withdrawHoldTime() { return this._data.withdrawHoldTime; } get owner() { return this._data.owner; } get accountVersion() { return this._data.accountVersion; } get stEverVaultVersion() { return this._data.stEverVaultVersion; } get clusterVersion() { return this._data.clusterVersion; } get timeAfterEmergencyCanBeActivated() { return this._data.timeAfterEmergencyCanBeActivated; } decodeEvent(args) { return StakingVault.Utils.decodeEvent(this._connection, this.address, args); } decodeTransaction(args) { return StakingVault.Utils.decodeTransaction(this._connection, this.address, args); } decodeTransactionEvents(transaction) { return StakingVault.Utils.decodeTransactionEvents(this._connection, this.address, transaction); } } exports.StakingVault = StakingVault; __decorate([ mobx_1.action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], StakingVault.prototype, "sync", null); __decorate([ mobx_1.action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Function]), __metadata("design:returntype", Promise) ], StakingVault.prototype, "watch", null); __decorate([ mobx_1.action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", Promise) ], StakingVault.prototype, "unwatch", null); __decorate([ mobx_1.action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", Promise) ], StakingVault.prototype, "deposit", null); __decorate([ mobx_1.action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", Promise) ], StakingVault.prototype, "removePendingWithdraw", null); __decorate([ mobx_1.action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], StakingVault.prototype, "encodeDepositPayload", null); __decorate([ mobx_1.action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], StakingVault.prototype, "getAccountAddress", null); __decorate([ mobx_1.action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], StakingVault.prototype, "getDepositExpectedAmount", null); __decorate([ mobx_1.action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], StakingVault.prototype, "getWithdrawExpectedAmount", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "nonce", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "governance", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "stEverSupply", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "totalAssets", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "availableAssets", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "totalStEverFee", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "effectiveEverAssets", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "remainingLockedAssets", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "unlockPerSecond", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "stEverWallet", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "stTokenRoot", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "lastUnlockTime", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "fullUnlockSeconds", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "remainingSeconds", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "gainFee", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "stEverFeePercent", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "minStrategyDepositValue", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "minStrategyWithdrawValue", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "isPaused", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "strategyFactory", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "withdrawHoldTime", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "owner", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "accountVersion", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "stEverVaultVersion", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "clusterVersion", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "timeAfterEmergencyCanBeActivated", null); __decorate([ mobx_1.action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], StakingVault.prototype, "decodeEvent", null); __decorate([ mobx_1.action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], StakingVault.prototype, "decodeTransaction", null); __decorate([ mobx_1.action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], StakingVault.prototype, "decodeTransactionEvents", null);