Skip to content

Instantly share code, notes, and snippets.

@livingrock7
Created August 29, 2021 20:34
Show Gist options
  • Save livingrock7/9ec457c509ababa22cbd1e9b0f573dd7 to your computer and use it in GitHub Desktop.
Save livingrock7/9ec457c509ababa22cbd1e9b0f573dd7 to your computer and use it in GitHub Desktop.
pre flight checks for paying gas in ERC20 token
const appRoot = require("app-root-path");
var log = require(`${appRoot}/config/winston`).logger(module);
const config = require(`${appRoot}/config`);
const cache = require(`${appRoot}/src/services/caching`);
const ethers = require("ethers");
const {
getGasPriceKey,
} = require(`${appRoot}/src/controllers/utils/cache-utils`);
const TOKEN_GAS_PRICE_THRESHOLD_PERCENTAGE =
config.TOKEN_GAS_PRICE_THRESHOLD_PERCENTAGE;
const getPreFlightChecks = async (
networkId,
oracleAggregatorContract,
forwardRequest
) => {
let result = {};
result.readyToPayGasInTokens = false;
try {
let gasPriceFromCache = await cache.get(
getGasPriceKey(networkId, config.networksGasPriceType[networkId])
);
let tokenAddress = forwardRequest.token;
const tokenGasPriceFromRequest = ethers.BigNumber.from(
forwardRequest.tokenGasPrice
);
const tokenPriceCurrent = await oracleAggregatorContract.getTokenPrice(
tokenAddress
);
const tokenOracleDecimals = await oracleAggregatorContract.getTokenOracleDecimals(
tokenAddress
);
/* should probably assume use of high gas price and calculate from different sources on the go (upvest,gasstation,etherscan) and avergae out
same for the oracle vs token price fetch apis - coingecko etc
add robustness for calcs
//todo
*/
const gasPrice = ethers.BigNumber.from(
ethers.utils.parseUnits(gasPriceFromCache.toString(), "wei").toString()
);
const tokenGasPriceCurrent = ethers.BigNumber.from(gasPrice)
.mul(ethers.BigNumber.from(10).pow(tokenOracleDecimals))
.div(tokenPriceCurrent);
if (tokenGasPriceCurrent && tokenPriceCurrent && tokenOracleDecimals) {
log.info(`token price ${tokenPriceCurrent.toString()}`);
log.info(`token oracle decimals ${tokenOracleDecimals.toString()}`);
log.info(`token gas price ${tokenGasPriceCurrent.toString()}`);
var minimumTokenGasPriceAccepted = ethers.BigNumber.from(
TOKEN_GAS_PRICE_THRESHOLD_PERCENTAGE
)
.mul(ethers.BigNumber.from(tokenGasPriceCurrent))
.div(ethers.BigNumber.from(100));
if (tokenGasPriceFromRequest.lte(minimumTokenGasPriceAccepted)) {
log.info("Not favorable to process this transaction");
result.errorMessage =
"$token/ETH pair price has dropped beyond threshold";
} else {
result.readyToPayGasInTokens = true;
}
}
} catch (error) {
log.info("Error while getting data points for pre flight checks");
result.errorMessage = error.toString();
log.error(error);
}
log.info(`ready to pay in ERC20 tokens? ${result.readyToPayGasInTokens}`);
return result;
};
module.exports = { getPreFlightChecks };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment