UNPKG

@dydxfoundation/governance

Version:
77 lines (76 loc) 3.42 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const ethers_1 = require("ethers"); const config_1 = require("../config"); const types_1 = require("../types"); const gasStation_1 = require("../utils/gasStation"); class BaseService { constructor(config, contractFactory) { this.getContractInstance = (address) => { if (!this.contractInstances[address]) { const { provider } = this.config; this.contractInstances[address] = this.contractFactory.connect(address, provider); } return this.contractInstances[address]; }; this.timeLatest = async () => { const { provider } = this.config; const block = await provider.getBlock('latest'); return block.timestamp; }; this.generateTxCallback = ({ rawTxMethod, from, value, gasSurplus, action, gasLimit, }) => async () => { var _a, _b; const txRaw = await rawTxMethod(); const tx = { ...txRaw, gasLimit: (_a = txRaw.gasLimit) === null || _a === void 0 ? void 0 : _a.toNumber(), gasPrice: (_b = txRaw.gasPrice) === null || _b === void 0 ? void 0 : _b.toNumber(), from, value: value || config_1.DEFAULT_NULL_VALUE_ON_TX, }; if (gasLimit) { tx.gasLimit = gasLimit; } else { tx.gasLimit = (await (0, gasStation_1.estimateGas)(tx, this.config, gasSurplus)).toNumber(); } if (action && config_1.gasLimitRecommendations[action] && ethers_1.BigNumber.from(tx.gasLimit).lte(config_1.gasLimitRecommendations[action].limit)) { tx.gasLimit = parseInt(config_1.gasLimitRecommendations[action].recommended); } return tx; }; this.generateTxPriceEstimation = (txs, txCallback, action = types_1.ProtocolAction.default) => async (force = false) => { try { const gasPrice = await (0, gasStation_1.getGasPrice)(this.config); const hasPendingApprovals = txs.find((tx) => tx.txType === types_1.eEthereumTxType.ERC20_APPROVAL); if (!hasPendingApprovals || force) { const { gasLimit, gasPrice: gasPriceProv, } = await txCallback(); if (!gasLimit) { // If we don't recieve the correct gas we throw a error throw new Error('Transaction calculation error'); } return { gasLimit: gasLimit.toString(), gasPrice: gasPriceProv ? gasPriceProv.toString() : gasPrice.toString(), }; } return { gasLimit: config_1.gasLimitRecommendations[action].recommended, gasPrice: gasPrice.toString(), }; } catch (error) { console.error('Calculate error on calculate estimation gas price.', error); return null; } }; this.config = config; this.contractFactory = contractFactory; this.contractInstances = {}; } } exports.default = BaseService;