gwei-alert-bot/src/blockchain.ts
2023-04-18 13:35:09 -07:00

61 lines
1.6 KiB
TypeScript

import 'dotenv/config.js';
import Web3 from 'web3';
import { GasPrices } from '../types/gasPrices'
import redisClient from './redis';
const rpcUrl = process.env.RPC_URL || 'ws://localhost:8545';
// Create a new web3 instance
const web3 = new Web3(new Web3.providers.WebsocketProvider(rpcUrl, {
reconnect: {
auto: true,
delay: 5000,
maxAttempts: 5,
onTimeout: false
}
}));
export const subToBlockHeaders = (setDiscordStatus: () => Promise<void>) => {
web3.eth.subscribe('newBlockHeaders', (error, blockHeader) => {
if (error) console.error(error);
// Set status every 10 blocks
const shouldSetStatus = blockHeader.number % 10 === 0;
// Get the gas price for this block
web3.eth.getGasPrice((error, gasPrice) => {
if (error) console.error(error);
console.log('Gas price in wei:', gasPrice);
redisClient.set('gas-price', Math.round(Number(gasPrice)))
});
if (shouldSetStatus) setDiscordStatus()
});
}
const gweiFromWei = (priceInWei: number): number =>
Math.round(Number(web3.utils.fromWei(`${Math.round(priceInWei)}`, 'gwei')));
const getGasPrice = async (): Promise<number> => {
const gasPrice = await redisClient.get('gas-price');
return Number(gasPrice);
}
const getGasPricesInGwei = async (): Promise<GasPrices> => {
const gasPrice = await getGasPrice()
const fastPrice = gasPrice * 1.1;
const slowPrice = gasPrice * 0.9;
const gasPrices = {
fast: gweiFromWei(fastPrice),
average: gweiFromWei(gasPrice),
slow: gweiFromWei(slowPrice),
};
return gasPrices;
};
export { getGasPricesInGwei };