37 lines
1.1 KiB
TypeScript
37 lines
1.1 KiB
TypeScript
import 'dotenv/config.js';
|
|
import { GasPrices } from '../types/gasPrices'
|
|
const Web3 = require('web3');
|
|
|
|
const rpcUrl = process.env.RPC_URL || 'ws://localhost:8545';
|
|
|
|
// Create a new web3 instance
|
|
const web3 = new Web3(rpcUrl);
|
|
|
|
// Get the current gas price in gwei
|
|
const getGasPricesInGwei = async (): Promise<GasPrices> => {
|
|
const gweiFromWei = (priceInWei: string): number =>
|
|
Number(web3.utils.fromWei(priceInWei, 'gwei').toFixed(2));
|
|
|
|
try {
|
|
const [fastPrice, averagePrice, slowPrice] = await Promise.all([
|
|
web3.eth.getGasPrice(),
|
|
web3.eth.getGasPrice('average'),
|
|
web3.eth.getGasPrice('slow'),
|
|
]);
|
|
|
|
const gasPrices = {
|
|
fast: gweiFromWei(fastPrice),
|
|
average: gweiFromWei(averagePrice),
|
|
slow: gweiFromWei(slowPrice),
|
|
};
|
|
|
|
return Promise.resolve(gasPrices);
|
|
// await redisClient.set('gas-prices', JSON.stringify(gasPrices));
|
|
} catch (error) {
|
|
console.error(`Error fetching gas prices: ${error}`);
|
|
return Promise.reject(error);
|
|
}
|
|
};
|
|
|
|
// Export the getCurrentGasPrice function
|
|
export { getGasPricesInGwei }; |