tornado-oracles/lib/feeOracle.js

374 lines
23 KiB
JavaScript

"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TornadoFeeOracle = void 0;
var ethers_1 = require("ethers");
var bignumber_js_1 = __importDefault(require("bignumber.js"));
var utils_1 = require("ethers/lib/utils");
var config_1 = require("./config");
var utils_2 = require("./utils");
var factories_1 = require("./contracts/factories");
var TornadoFeeOracle = /** @class */ (function () {
function TornadoFeeOracle(version, chainId, rpcUrl) {
this.version = version;
this.chainId = chainId;
this.provider = new ethers_1.ethers.providers.JsonRpcProvider(rpcUrl);
}
/**
* Because Optimism transaction published on Mainnet, for each OP transaction we need to calculate L1 security fee:
* https://community.optimism.io/docs/developers/build/transaction-fees/#priority-fee
* @param {TransactionData} [tx] Transaction data to estimate L1 additional fee
* @returns {Promise<HexadecimalStringifiedNumber>} Fee in WEI (MATIC), '0' if chain is not Optimism
*/
TornadoFeeOracle.prototype.fetchL1OptimismFee = function (tx) {
return __awaiter(this, void 0, void 0, function () {
var optimismL1FeeOracle, l1Fee;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (this.chainId != config_1.ChainId.OPTIMISM)
return [2 /*return*/, ethers_1.BigNumber.from(0).toHexString()];
optimismL1FeeOracle = (0, factories_1.getOptimismL1FeeOracle)(this.provider);
return [4 /*yield*/, optimismL1FeeOracle.getL1Fee((0, utils_2.serializeTx)(tx))];
case 1:
l1Fee = _a.sent();
return [2 /*return*/, l1Fee.toHexString()];
}
});
});
};
/**
* Estimate gas price, gas limit and l1Fee for sidechain (if exists)
* @param {GetGasParamsInput} [params] Function input arguments object
* @param {TransactionData} [params.tx] Transaction data in web3 / ethers format
* @param {TxType} [params.txType=other] Tornado transaction type: withdrawal by user, withdrawal by relayer or 'other'
* @param {number} [params.predefinedGasLimit] Predefined gas limit, if already calculated (no refetching)
* @param {number} [params.predefinedGasPrice] Predefined gas price, if already calculated (no refetching)
* @param {number} [params.bumpGasLimitPercent] Gas limit bump percent to prioritize transaction (if gas limit not predefined, recenlty used)
* @param {number} [params.bumpGasPricePercent] Gas price bump percent to prioritize transaction (if gas limit not predefined, rarely used)
* @param {LegacyGasPriceKey} [params.speed] Preferred transaction speed, if uses legacy gas (before EIP-1559)
* @param {boolean} [params.includeL1FeeToGasLimit=true] Include L1 additional fee on Optimism to gas limit (get fee and divide by gas price)
* @returns {Promise<GetGasParamsRes>} Object with fields 'gasPrice' and 'gasLimit', L1 fee, if exists, included in gasLimit
*/
TornadoFeeOracle.prototype.getGasParams = function (params) {
if (params === void 0) { params = {}; }
return __awaiter(this, void 0, void 0, function () {
var tx, _a, txType, bumpGasLimitPercent, bumpGasPricePercent, gasLimit, gasPrice, speed, _b, includeL1FeeToGasLimit, l1Fee;
var _c, _d;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
tx = params.tx, _a = params.txType, txType = _a === void 0 ? 'other' : _a, bumpGasLimitPercent = params.bumpGasLimitPercent, bumpGasPricePercent = params.bumpGasPricePercent, gasLimit = params.predefinedGasLimit, gasPrice = params.predefinedGasPrice, speed = params.speed, _b = params.includeL1FeeToGasLimit, includeL1FeeToGasLimit = _b === void 0 ? true : _b;
l1Fee = '0';
if (!(!gasLimit && !gasPrice)) return [3 /*break*/, 2];
return [4 /*yield*/, Promise.all([
this.getGasPrice(speed, bumpGasPricePercent),
this.getGasLimit(tx, txType, bumpGasLimitPercent),
this.fetchL1OptimismFee(tx),
])];
case 1:
_c = _e.sent(), gasPrice = _c[0], gasLimit = _c[1], l1Fee = _c[2];
_e.label = 2;
case 2:
if (!!gasLimit) return [3 /*break*/, 4];
return [4 /*yield*/, Promise.all([
this.getGasLimit(tx, txType, bumpGasLimitPercent),
this.fetchL1OptimismFee(tx),
])];
case 3:
_d = _e.sent(), gasLimit = _d[0], l1Fee = _d[1];
_e.label = 4;
case 4:
if (!!gasPrice) return [3 /*break*/, 6];
return [4 /*yield*/, this.getGasPrice(speed, bumpGasPricePercent)];
case 5:
gasPrice = _e.sent();
_e.label = 6;
case 6:
if (includeL1FeeToGasLimit)
// Include L1 fee in gas limit (divide by gas price before), if l1 fee is 0, gas limit wont change
gasLimit = (0, bignumber_js_1.default)(gasLimit)
.plus((0, bignumber_js_1.default)(l1Fee).div((0, bignumber_js_1.default)(gasPrice)))
.decimalPlaces(0, 1)
.toNumber();
return [2 /*return*/, { gasLimit: gasLimit, gasPrice: gasPrice }];
}
});
});
};
/**
* Estimates next block gas for signed, unsigned or incomplete Tornado transaction
* @param {GetGasInput} [params] Function input arguments object
* @param {TransactionData} [params.tx] Transaction data in web3 / ethers format
* @param {TxType} [params.txType] Tornado transaction type: withdrawal by user, withdrawal by relayer or 'other'
* @param {number} [params.predefinedGasLimit] Predefined gas limit, if already calculated (no refetching)
* @param {number} [params.predefinedGasPrice] Predefined gas price, if already calculated (no refetching)
* @param {number} [params.bumpGasLimitPercent] Gas limit bump percent to prioritize transaction (if gas limit not predefined, recenlty used)
* @param {number} [params.bumpGasPricePercent] Gas price bump percent to prioritize transaction (if gas price not predefined, rarely used)
* @param {LegacyGasPriceKey} [params.speed] Preferred transaction speed, if uses legacy gas (before EIP-1559)
* @returns {Promise<HexadecimalStringifiedNumber>} Gas value in WEI (hex-format)
*/
TornadoFeeOracle.prototype.getGas = function (params) {
if (params === void 0) { params = {}; }
return __awaiter(this, void 0, void 0, function () {
var _a, gasPrice, gasLimit;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, this.getGasParams(__assign(__assign({}, params), { includeL1FeeToGasLimit: true }))];
case 1:
_a = _b.sent(), gasPrice = _a.gasPrice, gasLimit = _a.gasLimit;
return [2 /*return*/, ethers_1.BigNumber.from(gasPrice).mul(gasLimit).toHexString()];
}
});
});
};
/**
* Estimate next block gas price
* @param {LegacyGasPriceKey} [speed] Preferred transaction speed, if uses legacy gas (before EIP-1559)
* @param {number} [bumpPercent=0] Gas bump percent to prioritize transaction
* @returns {Promise<GasPriceParams>} Estimated gas price info in WEI (hexed) - legacy object with gasPrice property or
* EIP-1559 object with maxFeePerGas and maxPriorityFeePerGas properties
* NOTICE: It is recommended to bump fees for EIP-1559 transactions, because they can bump 12.5% per block
*/
TornadoFeeOracle.prototype.getGasPriceParams = function (speed, bumpPercent) {
var _a;
if (bumpPercent === void 0) { bumpPercent = 0; }
return __awaiter(this, void 0, void 0, function () {
var _b, block, gasPrice, priorityFee, maxPriorityFeePerGas, maxFeePerGas, e_1;
var _this = this;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
// Use instant for BSC, because on this chain "fast" and "instant" differs more than third and "fast" transaction can take hours
if (!speed)
speed = this.chainId === config_1.ChainId.BSC ? 'instant' : 'fast';
_c.label = 1;
case 1:
_c.trys.push([1, 3, , 4]);
return [4 /*yield*/, Promise.all([
this.provider.getBlock('latest'),
this.provider.getGasPrice(),
(function () { return __awaiter(_this, void 0, void 0, function () {
var _a, _b, _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
_d.trys.push([0, 2, , 3]);
_b = (_a = ethers_1.BigNumber).from;
return [4 /*yield*/, this.provider.send('eth_maxPriorityFeePerGas', [])];
case 1: return [2 /*return*/, _b.apply(_a, [(_d.sent()) || (0, utils_1.parseUnits)('1.5', 'gwei')])];
case 2:
_c = _d.sent();
return [2 /*return*/, (0, utils_1.parseUnits)('1.5', 'gwei')];
case 3: return [2 /*return*/];
}
});
}); })(),
])];
case 2:
_b = _c.sent(), block = _b[0], gasPrice = _b[1], priorityFee = _b[2];
if ((_a = block === null || block === void 0 ? void 0 : block.baseFeePerGas) === null || _a === void 0 ? void 0 : _a.gt(0)) {
maxPriorityFeePerGas = priorityFee.toHexString();
maxFeePerGas = (0, utils_2.bump)(block.baseFeePerGas, bumpPercent)
.add(priorityFee)
.toHexString();
return [2 /*return*/, {
maxFeePerGas: maxFeePerGas,
maxPriorityFeePerGas: maxPriorityFeePerGas,
}];
}
return [2 /*return*/, {
gasPrice: (0, utils_2.bump)(gasPrice, bumpPercent).toHexString(),
}];
case 3:
e_1 = _c.sent();
return [2 /*return*/, { gasPrice: (0, utils_2.bump)((0, utils_2.fromGweiToWeiHex)(config_1.defaultGasPrices[this.chainId][speed]), bumpPercent).toHexString() }];
case 4: return [2 /*return*/];
}
});
});
};
/**
* Estimate next block gas price
* @param {LegacyGasPriceKey} [speed] Preferred transaction speed, if uses legacy gas (before EIP-1559)
* @param {number} [bumpPercent] Gas bump percent to prioritize transaction
* @returns {Promise<HexadecimalStringifiedNumber>} Gas price in WEI (hex string)
*/
TornadoFeeOracle.prototype.getGasPrice = function (speed, bumpPercent) {
return __awaiter(this, void 0, void 0, function () {
var gasPriceParams;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.getGasPriceParams(speed, bumpPercent)];
case 1:
gasPriceParams = _a.sent();
return [2 /*return*/, (0, utils_2.calculateGasPriceInWei)(gasPriceParams).toHexString()];
}
});
});
};
/**
* If user withdraw non-native tokens on ETH or Goerli, we need to calculate refund value:
* if the withdrawal is successful, this amount will be returned to the user after the transfer to the relayer,
* and if the relayer pays a commission and the transfer of tokens fails, this commission will remain to the relayer.
*
* Refund needed that recipient can use tokens after withdrawal (covers gas fee for send/swap)
* @param {BigNumberish} gasPrice Actual gas price
* @param {InstanceTokenSymbol} tokenSymbol Withdrawal token (currency) symbol - for example, 'dai'
* @returns {HexadecimalStringifiedNumber} Refund amount in WEI (in hex format)
*/
TornadoFeeOracle.prototype.calculateRefundInETH = function (gasPrice, tokenSymbol) {
// Refund only available for non-native tokens on Ethereum Mainnet and Goerli
if (![config_1.ChainId.MAINNET, config_1.ChainId.GOERLI].includes(this.chainId) || tokenSymbol === 'eth')
return '0';
// Notify user about error if incorrect token symbol provided
if (!Object.values(config_1.InstanceTokenSymbol).includes(tokenSymbol)) {
console.error("Invalid token symbol: ".concat(tokenSymbol, ", must be lowercase token from one of Tornado ETH Mainnet pools"));
return '0';
}
// In Tornado we need to calculate refund only on user side, relayer get refund value in proof
var gasLimit = config_1.defaultInstanceTokensGasLimit[tokenSymbol];
return ethers_1.BigNumber.from(gasPrice).mul(gasLimit).mul(2).toHexString();
};
/**
* Fetched actual gas price and calculates refund amount
* @param {InstanceTokenSymbol} tokenSymbol Withdrawal token (currency) symbol - for example, 'dai'
* @returns {Promise<HexadecimalStringifiedNumber>} Refund amount in WEI (in hex format)
*/
TornadoFeeOracle.prototype.fetchRefundInETH = function (tokenSymbol) {
return __awaiter(this, void 0, void 0, function () {
var gasPrice;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.getGasPrice()];
case 1:
gasPrice = _a.sent();
return [2 /*return*/, this.calculateRefundInETH(gasPrice, tokenSymbol)];
}
});
});
};
/**
* Get refund amount on ETH or Goerli in non-native token
* @param {BigNumberish} gasPrice Actual gas price in ETH
* @param {BigNumberish} tokenPriceInEth Token price in WEI in ETH
* @param {HexadecimalStringifiedNumber | number} tokenDecimals Token (currency) decimals
* @param {InstanceTokenSymbol} tokenSymbol Withdrawal token (currency) symbol - for example, 'dai'
* @returns {HexadecimalStringifiedNumber} Refund amount in WEI in selected token (hexed number)
*/
TornadoFeeOracle.prototype.calculateRefundInToken = function (gasPrice, tokenPriceInEth, tokenDecimals, tokenSymbol) {
var refundInEth = this.calculateRefundInETH(gasPrice, tokenSymbol);
return (0, utils_2.convertETHToToken)(refundInEth, tokenDecimals, tokenPriceInEth).toHexString();
};
/**
* Calculates relayer fee in selected currency (ETH, DAI, BNB etc) in WEI
* @param {number | string} relayerFeePercent Relayer percent (0.4 for ETH Mainnet, for example)
* @param {HexadecimalStringifiedNumber | number} amount Amount in selected currency (10 for 10 ETH, 1000 for 1000 DAI)
* @param {string | number} decimals Decimal places in selected token (currency)
* @returns {HexadecimalStringifiedNumber} Fee in WEI (hexed stingified number)
*/
TornadoFeeOracle.prototype.calculateRelayerFeeInWei = function (relayerFeePercent, amount, decimals) {
return (0, utils_1.parseUnits)(amount.toString(), decimals)
.mul("".concat(Math.floor(Number(relayerFeePercent) * 1e10)))
.div("".concat(100 * 1e10))
.toHexString();
};
/**
* Estimates fee for withdrawal via relayer depending on type: gas bump percent is bigger, if it calculates by user,
* so that the real commission from the relayer side is a little less,
* in order to the relayer can send a transaction without fear that he will go into the red
* @param {GetWithdrawalFeeViaRelayerInput} params Function input arguments object
* @param {TxType} params.txType Tornado transaction type: withdrawal costs calculation from user side or from relayer side
* @param {TransactionData} [params.tx] Transaction data (object in web3 / ethers format)
* @param {number} params.relayerFeePercent Relayer fee percent from the transaction amount (for example, 0.15 for BNB or 0.4 for ETH Mainnet)
* @param {AvailableTokenSymbols | Uppercase<AvailableTokenSymbols>} params.currency Currency symbol
* @param {number | HexadecimalStringifiedNumber } params.amount Withdrawal amount in selected currency
* @param {number | HexadecimalStringifiedNumber } params.decimals Token (currency) decimals
* @param {BigNumberish} [params.refundInEth] Refund in ETH, if withdrawed other tokens on Mainnet (not ETH). Can not be provided, if user-side calculation
* @param {BigNumberish} [params.tokenPriceInEth] If withdrawing other token on Mainnet or Goerli, need to provide token price in ETH (in WEI)
* @param {number} [params.gasLimit] Predefined gas limit, if already calculated (no refetching)
* @param {number} [params.gasPrice] Predefined gas price, if already calculated (no refetching)
*
* @returns {Promise<HexadecimalStringifiedNumber>} Fee in WEI (hexed string)
*/
TornadoFeeOracle.prototype.calculateWithdrawalFeeViaRelayer = function (_a) {
var tx = _a.tx, txType = _a.txType, relayerFeePercent = _a.relayerFeePercent, currency = _a.currency, amount = _a.amount, decimals = _a.decimals, refundInEth = _a.refundInEth, tokenPriceInEth = _a.tokenPriceInEth, predefinedGasLimit = _a.predefinedGasLimit, predefinedGasPrice = _a.predefinedGasPrice;
return __awaiter(this, void 0, void 0, function () {
var relayerFee, _b, gasPrice, gasLimit, gasCosts, hasTokenPrice, feeInEth;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
relayerFee = this.calculateRelayerFeeInWei(relayerFeePercent, amount, decimals);
return [4 /*yield*/, this.getGasParams({ tx: tx, txType: txType, predefinedGasLimit: predefinedGasLimit, predefinedGasPrice: predefinedGasPrice })];
case 1:
_b = _c.sent(), gasPrice = _b.gasPrice, gasLimit = _b.gasLimit;
gasCosts = ethers_1.BigNumber.from(gasPrice).mul(gasLimit);
hasTokenPrice = typeof tokenPriceInEth === 'object' && typeof (tokenPriceInEth === null || tokenPriceInEth === void 0 ? void 0 : tokenPriceInEth.gt) === 'function'
? Boolean(tokenPriceInEth.gt(0))
: Boolean(tokenPriceInEth);
if (hasTokenPrice) {
if (txType === 'user_withdrawal' && refundInEth === undefined)
refundInEth = this.calculateRefundInETH(gasPrice, currency.toLowerCase());
feeInEth = ethers_1.BigNumber.from(gasCosts).add(refundInEth || 0);
return [2 /*return*/, (0, utils_2.convertETHToToken)(feeInEth, decimals, tokenPriceInEth)
.add(relayerFee)
.toHexString()];
}
return [2 /*return*/, ethers_1.BigNumber.from(gasCosts).add(relayerFee).toHexString()];
}
});
});
};
return TornadoFeeOracle;
}());
exports.TornadoFeeOracle = TornadoFeeOracle;
//# sourceMappingURL=feeOracle.js.map