gwei-alert-bot/src/blockchain.ts

47 lines
1.2 KiB
TypeScript
Raw Normal View History

2023-04-18 01:49:20 +00:00
import 'dotenv/config.js';
import { GasPrices } from '../types/gasPrices'
2023-04-18 04:15:10 +00:00
import Web3 from 'web3';
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
// Get the current gas price in gwei
2023-04-18 04:15:10 +00:00
async function getGasPrice() {
const gasPrice = await web3.eth.getGasPrice();
return Number(gasPrice);
}
2023-04-18 01:49:20 +00:00
const getGasPricesInGwei = async (): Promise<GasPrices> => {
2023-04-18 04:15:10 +00:00
const gweiFromWei = (priceInWei: number): number =>
Number(web3.utils.fromWei(`${Math.round(priceInWei)}`, 'gwei'));
2023-04-18 01:49:20 +00:00
try {
2023-04-18 04:15:10 +00:00
const gasPrice = await getGasPrice()
const fastPrice = gasPrice * 1.2;
const slowPrice = gasPrice * 0.8;
2023-04-18 01:49:20 +00:00
const gasPrices = {
fast: gweiFromWei(fastPrice),
2023-04-18 04:15:10 +00:00
average: gweiFromWei(gasPrice),
2023-04-18 01:49:20 +00:00
slow: gweiFromWei(slowPrice),
};
return Promise.resolve(gasPrices);
// await redisClient.set('gas-prices', JSON.stringify(gasPrices));
} catch (error) {
2023-04-18 04:15:10 +00:00
console.log(error);
2023-04-18 01:49:20 +00:00
return Promise.reject(error);
}
};
// Export the getCurrentGasPrice function
export { getGasPricesInGwei };