1. Home
  2. Docs
  3. APIs
  4. How to obtain the current gas?

How to obtain the current gas?

To obtain the current gas price, you can use Ethereum’s Web3.js or other Ethereum-related development libraries to query the Ethereum network’s gas price information.

Here’s an example code using Web3.js:
1
2
3
4
5
6
7
8
9
10
11
const { Web3 } = require('web3');
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID'); // Replace with your own Infura project ID

web3.eth.getGasPrice()
.then((gasPrice) => {
console.log('Current gas price (in Wei):', gasPrice);
console.log('Current gas price (in Gwei):', web3.utils.fromWei(gasPrice, 'gwei'));
})
.catch((error) => {
console.error('Error while fetching gas price:', error);
});
In the code above, we are using an Ethereum node provided by Infura to connect to the Ethereum network. You’ll need to replace ‘YOUR_INFURA_PROJECT_ID’ with your own Infura project ID. Then, use the web3.eth.getGasPrice() method to retrieve the current gas price, which is returned in Wei. You can use web3.utils.fromWei() to convert it into Gwei, as Gwei is commonly used to represent gas prices.

Please note that gas prices can vary based on network congestion, so obtaining gas prices is a dynamic process.
Tags