UNPKG

@broxus/js-core

Version:

MobX-based JavaScript Core library

563 lines (562 loc) 21.6 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, sliceString, throwException } from '@broxus/js-utils'; import { action, computed, makeObservable } from 'mobx'; import { inheritTextStyle, successLabelStyle, successTextStyle, warningLabelStyle } from '../../console'; import { SmartContractModel } from '../../core'; import { StakingVaultUtils } from '../../models/staking-vault/StakingVaultUtils'; import { areAddressesEqual, contractStateChangeDebugMessage, getRandomInt, ProviderNotDefinedError, subscribeDebugMessage, syncErrorMessage, unsubscribeDebugMessage, unsubscribeErrorMessage, } from '../../utils'; export class StakingVault extends SmartContractModel { _connection; options; _provider; static Utils = 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(() => ({})); 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) { 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(); 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() { if (this.contractSubscriber === undefined) { return; } 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 deposit(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 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 (!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') { debug(`%c${this.constructor.name}%c %cDeposit%c event was captured`, successLabelStyle, inheritTextStyle, successTextStyle, 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) { 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') { debug(`%c${this.constructor.name}%c Unsubscribed from the depositing token [%c${sliceString(this.stTokenRoot?.toString())}%c] stream`, warningLabelStyle, inheritTextStyle, successTextStyle, inheritTextStyle); } await subscriber?.unsubscribe(); } } async removePendingWithdraw(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 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 (!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') { debug(`%c${this.constructor.name}%c %cWithdrawRequestRemoved%c event was captured`, successLabelStyle, inheritTextStyle, successTextStyle, inheritTextStyle, event); } await params.onTransactionSuccess?.({ callId, input: { nonce: event.data.nonce, user: event.data.user, }, transaction: tx, }); return event; } catch (e) { 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') { debug(`%c${this.constructor.name}%c Unsubscribed from the withdraw removing request stream`, warningLabelStyle, inheritTextStyle, successTextStyle, 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); } } __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], StakingVault.prototype, "sync", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Function]), __metadata("design:returntype", Promise) ], StakingVault.prototype, "watch", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", Promise) ], StakingVault.prototype, "unwatch", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", Promise) ], StakingVault.prototype, "deposit", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", Promise) ], StakingVault.prototype, "removePendingWithdraw", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], StakingVault.prototype, "encodeDepositPayload", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], StakingVault.prototype, "getAccountAddress", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], StakingVault.prototype, "getDepositExpectedAmount", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], StakingVault.prototype, "getWithdrawExpectedAmount", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "nonce", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "governance", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "stEverSupply", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "totalAssets", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "availableAssets", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "totalStEverFee", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "effectiveEverAssets", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "remainingLockedAssets", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "unlockPerSecond", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "stEverWallet", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "stTokenRoot", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "lastUnlockTime", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "fullUnlockSeconds", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "remainingSeconds", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "gainFee", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "stEverFeePercent", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "minStrategyDepositValue", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "minStrategyWithdrawValue", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "isPaused", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "strategyFactory", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "withdrawHoldTime", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "owner", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "accountVersion", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "stEverVaultVersion", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "clusterVersion", null); __decorate([ computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], StakingVault.prototype, "timeAfterEmergencyCanBeActivated", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], StakingVault.prototype, "decodeEvent", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], StakingVault.prototype, "decodeTransaction", null); __decorate([ action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], StakingVault.prototype, "decodeTransactionEvents", null);