UNPKG

@broxus/js-core

Version:

MobX-based JavaScript Core library

457 lines (456 loc) 19 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.DexStablePair = void 0; const js_utils_1 = require("@broxus/js-utils"); const mobx_1 = require("mobx"); const console_1 = require("../../console"); const constants_1 = require("../../constants"); const core_1 = require("../../core"); const DexStablePairUtils_1 = require("../../models/dex-stable-pair/DexStablePairUtils"); const tvm_token_1 = require("../../models/tvm-token"); const wallet_1 = require("../../models/wallet"); const utils_1 = require("../../utils"); class DexStablePair extends core_1.SmartContractModel { _connection; dex; options; _provider; static Utils = DexStablePairUtils_1.DexStablePairUtils; /** * @param {ProviderRpcClient} _connection * Standalone RPC client that doesn't require connection to the TVM wallet provider * @param {Address | string} address * DexStablePair root address * @param {Dex} dex * Dex Smart Contract Model instance * @param {Readonly<DexStablePairCtorOptions>} [options] * (optional) DexStablePair Smart Contract Model options * @param {ProviderRpcClient} [_provider] * (optional) RPC provider that require connection to the TVM wallet */ constructor(_connection, address, dex, options, _provider) { super(_connection, address); this._connection = _connection; this.dex = dex; this.options = options; this._provider = _provider; this.setData(() => ({ feeParams: {}, })); (0, mobx_1.makeObservable)(this); } /** * @param {ProviderRpcClient} connection * Standalone RPC client that doesn't require connection to the TVM wallet provider * @param {Readonly<DexStablePairCreateConfig>} config * DexStablePair Smart Contract Model config * @param {Readonly<DexStablePairCreateOptions>} [options] * (optional) DexStablePair Smart Contract Model options * @param {ProviderRpcClient} [provider] * (optional) RPC provider that require connection to the TVM wallet */ static async create(connection, config, options, provider) { const { sync = true, watch, watchCallback, ...restOptions } = { ...options }; let address; if ('address' in config) { address = config.address; } else { address = await config.dex.getExpectedPairAddress({ leftRootAddress: config.leftRootAddress, rightRootAddress: config.rightRootAddress, }); } const dexPair = new DexStablePair(connection, address, config.dex, restOptions, provider); if (sync) { await dexPair.sync({ force: false }); } if (watch) { await dexPair.watch(watchCallback); } return dexPair; } 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)('DexStablePair is not deployed'); } const [details, feeParams, dexRootAddress, dexVaultAddress] = await Promise.all([ DexStablePair.Utils.getDetails(this._connection, this.address, state), DexStablePair.Utils.getFeeParams(this._connection, this.address, state), DexStablePair.Utils.getRoot(this._connection, this.address, state), DexStablePair.Utils.getVault(this._connection, this.address, state), ]); this.setData({ ...details, dexRootAddress, dexVaultAddress, feeParams }); } 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() { 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 check(options) { if (options?.force || !this.contractState) { await this.syncContractState({ force: options?.force ?? true }); } if (!this.isDeployed) { if (process.env.NODE_ENV !== 'production') { (0, js_utils_1.debug)(`%c${this.constructor.name}%c Check for %c${(0, js_utils_1.sliceString)(this.address?.toString())}%c =>%c not deployed`, console_1.warningLabelStyle, console_1.inheritTextStyle, console_1.successTextStyle, console_1.inheritTextStyle, console_1.warningTextStyle); } return false; } const isActive = await DexStablePair.Utils.isActive(this._connection, this.address, this.contractState); if (!isActive) { if (process.env.NODE_ENV !== 'production') { (0, js_utils_1.debug)(`%c${this.constructor.name}%c Check for %c${(0, js_utils_1.sliceString)(this.address?.toString())}%c =>%c inactive`, console_1.warningLabelStyle, console_1.inheritTextStyle, console_1.successTextStyle, console_1.inheritTextStyle, console_1.warningTextStyle); } return false; } if (process.env.NODE_ENV !== 'production') { (0, js_utils_1.debug)(`%c${this.constructor.name}%c Check for %c${(0, js_utils_1.sliceString)(this.address?.toString())}%c =>%c deployed`, console_1.successLabelStyle, console_1.inheritTextStyle, console_1.successTextStyle, console_1.inheritTextStyle, console_1.successTextStyle); } return true; } async syncBalances(options) { if (!this.lpToken || !this.leftToken || !this.rightToken) { await this.sync({ force: true }); return DexStablePair.Utils.getBalances(this._connection, this.address, this.contractState); } await this.syncContractState({ force: options?.force ?? true }); const balances = await DexStablePair.Utils.getBalances(this._connection, this.address, this.contractState); this.setData('balances', balances); return balances; } async deployPair(params, args) { if (await this.check({ force: true })) { throw new Error('DexStablePair already deployed'); } return this.dex.deployPair({ ...params, expectedAddress: this.address, leftRootAddress: this.leftToken.address, rightRootAddress: this.rightToken.address, }, args); } async withdrawLiquidity(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 { await this.sync({ force: true }); let { ownerLpWalletAddress, payload } = params; if (!ownerLpWalletAddress) { ownerLpWalletAddress = await tvm_token_1.TvmToken.Utils.walletOf(this._connection, { ownerAddress: params.ownerAddress, tokenAddress: this.lpToken.address, }, this.lpToken.contractState); } const lpUserWallet = await tvm_token_1.TvmToken.Wallet.create(this._connection, { address: ownerLpWalletAddress }, { sync: true }, this._provider); if (!this.lpWallet?.isDeployed || !lpUserWallet?.isDeployed) { (0, js_utils_1.throwException)('LP wallets do not exist'); } if (!payload) { payload = await DexStablePair.Utils.buildWithdrawLiquidityPayload(this._connection, this.address, { callId, deployWalletGrams: params.deployWalletGrams ?? (0, utils_1.toInt)(0.1, constants_1.DEFAULT_NATIVE_CURRENCY_DECIMALS), }, this.contractState); } const message = await lpUserWallet.transferToWallet({ amount: params.amount, notify: params.notify ?? true, payload, recipientTokenWallet: this.lpWallet.address, remainingGasTo: params.remainingGasTo ?? params.ownerAddress, }, { amount: (0, utils_1.toInt)(2.7, constants_1.DEFAULT_NATIVE_CURRENCY_DECIMALS), // => 2.7 EVER as minimum value bounce: true, from: (0, utils_1.resolveTvmAddress)(params.ownerAddress), ...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, params.ownerAddress)) { return undefined; } const wallet = (0, wallet_1.walletContract)(this._connection, params.ownerAddress); const decodedTx = await wallet.decodeTransaction({ methods: ['dexPairOperationCancelled', 'dexPairWithdrawSuccess'], transaction: tx, }); if (decodedTx?.method === 'dexPairWithdrawSuccess') { const result = { callId, input: { amounts: [decodedTx.input.result.left, decodedTx.input.result.right], id: decodedTx.input.id, lpAmount: decodedTx.input.result.lp, viaAccount: decodedTx.input.via_account, }, transaction: tx, }; (0, js_utils_1.debug)('dexPairWithdrawSuccess', result); await params.onTransactionSuccess?.(result); return result; } if (decodedTx?.method === 'dexPairOperationCancelled') { const reason = { callId, input: { id: decodedTx.input.id }, transaction: tx, }; (0, js_utils_1.debug)('dexPairOperationCancelled', reason); await params.onTransactionFailure?.(reason); return reason; } return undefined; }) .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 withdrawal liquidity stream`, console_1.warningLabelStyle, console_1.inheritTextStyle); } await subscriber?.unsubscribe(); } } get balances() { return this._data.balances; } get dexRootAddress() { return this._data.dexRootAddress; } get dexVaultAddress() { return this._data.dexVaultAddress; } get feeParams() { return this._data.feeParams; } get isActive() { return this._data.isActive; } get leftToken() { return this._data.tokens?.[0]; } get leftTokenWallet() { return this._data.wallets?.[0]; } get lpToken() { return this._data.lpToken; } get lpWallet() { return this._data.lpWallet; } get rightToken() { return this._data.tokens?.[1]; } get rightTokenWallet() { return this._data.wallets?.[1]; } get tokens() { return this._data.tokens; } get type() { return this._data.type; } get virtualPrice() { return this._data.virtualPrice; } get wallets() { return this._data.wallets; } } exports.DexStablePair = DexStablePair; __decorate([ mobx_1.action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], DexStablePair.prototype, "sync", null); __decorate([ mobx_1.action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Function]), __metadata("design:returntype", Promise) ], DexStablePair.prototype, "watch", null); __decorate([ mobx_1.action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", Promise) ], DexStablePair.prototype, "unwatch", null); __decorate([ mobx_1.action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], DexStablePair.prototype, "check", null); __decorate([ mobx_1.action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], DexStablePair.prototype, "syncBalances", null); __decorate([ mobx_1.action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", Promise) ], DexStablePair.prototype, "deployPair", null); __decorate([ mobx_1.action.bound, __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", Promise) ], DexStablePair.prototype, "withdrawLiquidity", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], DexStablePair.prototype, "balances", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], DexStablePair.prototype, "dexRootAddress", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], DexStablePair.prototype, "dexVaultAddress", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], DexStablePair.prototype, "feeParams", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], DexStablePair.prototype, "isActive", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], DexStablePair.prototype, "leftToken", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], DexStablePair.prototype, "leftTokenWallet", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], DexStablePair.prototype, "lpToken", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], DexStablePair.prototype, "lpWallet", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], DexStablePair.prototype, "rightToken", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], DexStablePair.prototype, "rightTokenWallet", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], DexStablePair.prototype, "tokens", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], DexStablePair.prototype, "type", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], DexStablePair.prototype, "virtualPrice", null); __decorate([ mobx_1.computed, __metadata("design:type", Object), __metadata("design:paramtypes", []) ], DexStablePair.prototype, "wallets", null);