gwei-alert-bot/src/blockchain.ts

61 lines
1.6 KiB
TypeScript
Raw Normal View History

2023-04-18 01:49:20 +00:00
import 'dotenv/config.js';
2023-04-18 04:15:10 +00:00
import Web3 from 'web3';
2023-04-18 01:49:20 +00:00
2023-04-18 20:35:09 +00:00
import { GasPrices } from '../types/gasPrices'
import redisClient from './redis';
2023-04-18 01:49:20 +00:00
const rpcUrl = process.env.RPC_URL || 'ws://localhost:8545';
// Create a new web3 instance
2023-04-18 05:51:24 +00:00
const web3 = new Web3(new Web3.providers.WebsocketProvider(rpcUrl, {
reconnect: {
auto: true,
delay: 5000,
maxAttempts: 5,
onTimeout: false
}
}));
2023-04-18 01:49:20 +00:00
2023-04-18 20:35:09 +00:00
export const subToBlockHeaders = (setDiscordStatus: () => Promise<void>) => {
web3.eth.subscribe('newBlockHeaders', (error, blockHeader) => {
if (error) console.error(error);
const shouldLogWei = blockHeader.number % 10 === 0;
2023-04-18 20:35:09 +00:00
// Get the gas price for this block
web3.eth.getGasPrice((error, gasPrice) => {
if (error) console.error(error);
if (shouldLogWei) console.log('Gas price in wei:', gasPrice);
2023-04-18 20:35:09 +00:00
redisClient.set('gas-price', Math.round(Number(gasPrice)))
});
// Set status every block
setDiscordStatus()
2023-04-18 20:35:09 +00:00
});
}
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');
2023-04-18 04:15:10 +00:00
return Number(gasPrice);
}
2023-04-18 01:49:20 +00:00
const getGasPricesInGwei = async (): Promise<GasPrices> => {
2023-04-18 20:35:09 +00:00
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;
2023-04-18 01:49:20 +00:00
};
export { getGasPricesInGwei };