How to Get the Gas Price and Gas Fee on Ethereum Blockchain?


ethereum-blockchain How to Get the Gas Price and Gas Fee on Ethereum Blockchain? blockchain Ethereum (ETH) javascript nodejs

Ethereum Blockchain

On Ethereum Blockchain, we need to pay the miner Gas Fee to perform some operations, for example, invoking Smart Contract, or simply transfering ETH. The Gas Fee equals to 21000 multiplied by the Gas Price, which is measured in unit of Gwei.

You can pay a higher gas fee to allow the operations be handled quicker on the ETH blockchain: How to Transfer or Send ETH to Another Wallet on Ethereum Blockchain?

The simpliest way to get the Gas Price is to use the following method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const Web3 = require('web3');
 
const getGasPrice = async() => {
    const MAIN_ENDPOINT = "https://mainnet.infura.io/v3/...";
    const web3 = new Web3(MAIN_ENDPOINT);
    
    const wei = await web3.eth.getGasPrice();
    const gwei = web3.utils.fromWei(wei.toString(), 'gwei');
 
    return {
        "wei": parseFloat(wei),
        "gwei": parseFloat(gwei),
    };
}
const Web3 = require('web3');

const getGasPrice = async() => {
    const MAIN_ENDPOINT = "https://mainnet.infura.io/v3/...";
    const web3 = new Web3(MAIN_ENDPOINT);
    
    const wei = await web3.eth.getGasPrice();
    const gwei = web3.utils.fromWei(wei.toString(), 'gwei');

    return {
        "wei": parseFloat(wei),
        "gwei": parseFloat(gwei),
    };
}

1 gwei is 10^9 wei.

Another method is to iterate over the latest 10 blocks (How to Get the Latest Block Number (Head Block) on Ethereum Blockchain?) or so, and average the gas fee used in all the transactions in those blocks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const Web3 = require('web3');
 
const INFURA_ENDPOINT = 'YOUR_INFURA_ENDPOINT';
const web3 = new Web3(INFURA_ENDPOINT);
 
const getAverageGasPrice = async () => {
    const latestBlockNumber = await web3.eth.getBlockNumber();
    let totalGasPrice = BigInt(0);
    let transactionCount = 0;
 
    for (let i = 0; i < 10; i++) {
        const block = await web3.eth.getBlock(latestBlockNumber - i, true);
 
        for (const transaction of block.transactions) {
            totalGasPrice += BigInt(transaction.gasPrice);
            transactionCount++;
        }
    }
 
    if (transactionCount === 0) return 0;
 
    return totalGasPrice / BigInt(transactionCount);
};
 
getAverageGasPrice().then(avgGasPrice => {
    console.log(`Average Gas Price (last 10 blocks): ${web3.utils.fromWei(avgGasPrice.toString(), 'gwei')} Gwei`);
});
const Web3 = require('web3');

const INFURA_ENDPOINT = 'YOUR_INFURA_ENDPOINT';
const web3 = new Web3(INFURA_ENDPOINT);

const getAverageGasPrice = async () => {
    const latestBlockNumber = await web3.eth.getBlockNumber();
    let totalGasPrice = BigInt(0);
    let transactionCount = 0;

    for (let i = 0; i < 10; i++) {
        const block = await web3.eth.getBlock(latestBlockNumber - i, true);

        for (const transaction of block.transactions) {
            totalGasPrice += BigInt(transaction.gasPrice);
            transactionCount++;
        }
    }

    if (transactionCount === 0) return 0;

    return totalGasPrice / BigInt(transactionCount);
};

getAverageGasPrice().then(avgGasPrice => {
    console.log(`Average Gas Price (last 10 blocks): ${web3.utils.fromWei(avgGasPrice.toString(), 'gwei')} Gwei`);
});

Another method by calling the POST API is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
const getGasPrice = async () => {
    const body = {
        jsonrpc: "2.0",
        method: "eth_gasPrice",
        params: [],
        id: 1
    };
 
    try {
        const response = await fetch(MAIN_ENDPOINT, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(body),
        });
 
        const data = await response.json();
        const wei = parseInt(data.result, 16); // Convert hex to decimal
        const gwei = wei / 1e9; // Convert wei to gwei
 
        return {
            wei: wei,
            gwei: gwei,
        };
    } catch (error) {
        console.error('Error fetching gas price:', error);
        return null;
    }
};
const getGasPrice = async () => {
    const body = {
        jsonrpc: "2.0",
        method: "eth_gasPrice",
        params: [],
        id: 1
    };

    try {
        const response = await fetch(MAIN_ENDPOINT, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(body),
        });

        const data = await response.json();
        const wei = parseInt(data.result, 16); // Convert hex to decimal
        const gwei = wei / 1e9; // Convert wei to gwei

        return {
            wei: wei,
            gwei: gwei,
        };
    } catch (error) {
        console.error('Error fetching gas price:', error);
        return null;
    }
};

Importance of Setting a “correct” Gas Fee

Setting the Gas Fee in very important, if you set a high Gas Fee, you are paying unnecessary high fees (but you can get the transaction to be confirmed quickly), but if you set a low Gas Fee, your transaction may take longer to be confirmed as it is low priority for miners. And sometimes, your transaction may be stuck, or even cancelled (and the gas fee is forfeited). However, you can bump your transaction by setting a higher fee later.

With the gwei (Gas Price), we can estimate the Transaction Fee in ETH:

1
2
3
4
function getPriceETH(gwei) {
    const gasLimit = 21000;
    return gwei * gasLimit * 0.000000001;
}
function getPriceETH(gwei) {
    const gasLimit = 21000;
    return gwei * gasLimit * 0.000000001;
}

What is Gwei?

In the Ethereum ecosystem, Ether (ETH), the native cryptocurrency, can be subdivided into smaller units, much like how a dollar can be subdivided into cents. “Gwei” is one of these subdivisions.

Here’s a breakdown:

  • Wei: This is the smallest unit of Ether. Everything on the Ethereum blockchain, at the machine level, operates in Wei. Gas prices, for instance, are usually specified in Wei.
  • Gwei (Giga-wei): This is a more human-readable representation, especially for gas prices. 1 Gwei is equivalent to 1,000,000,000 Wei. The term “Giga” is a metric prefix denoting a factor of a billion (10^9), which is why it’s Giga-wei or Gwei for short.

Here are some common units for context:

1 Ether = 1,000,000,000,000,000,000 Wei
1 Ether = 1,000,000,000 Gwei

When you’re dealing with transaction fees (gas prices) in Ethereum, the numbers in Wei can become quite large and difficult to read. As a result, Gwei is the preferred unit when discussing gas prices. For instance, as of my last update in January 2022, common gas prices might range from 30 Gwei to 100 Gwei or more, depending on network congestion. Stating these numbers in Wei would be cumbersome.

As a side note, the names for Ethereum units, like Wei, come from names of early pioneers or influential people in the cryptocurrency and blockchain space. “Wei” is named after Wei Dai, a computer engineer who created “b-money,” an anonymous, distributed electronic cash system.

Why set “gas” to 21000?

In Ethereum, the term “gas” represents the computational work required to execute operations, like making a transaction or running a smart contract. Every operation has an associated gas cost.

For a standard Ethereum transaction, meaning a simple transfer of ETH from one address to another without any extra data or contract interactions, the gas required is always 21,000. This is a constant defined by the Ethereum protocol. Hence, when you’re sending a plain Ether transaction, you set the gas to 21,000.

However, when you’re interacting with smart contracts or sending data along with your transactions, the gas requirement will be higher because these actions require more computational work. In such cases, the gas limit would need to be estimated or provided based on the specific operations being performed.

But for the basic ETH transfer:
gas = 21,000 is the standard and is why it’s frequently seen in basic transaction examples.

How to Quickly Check the Current Gas Fee of ETH Ethereum?

You can visit the etherscan.io/gastracker to check the current Ethereum blockchain. Higher Gas Fee means quicker handle time thus transactions are confirmed faster, and vice versa.

eth-gas-tracker How to Get the Gas Price and Gas Fee on Ethereum Blockchain? blockchain Ethereum (ETH) javascript nodejs

Ethereum Gas Price Tracker

Alternatively, you can visit the API that I made:

1
2
$ curl -s "https://steemyy.com/api/eth/gas/"
{"gas":7.4156933682,"block":18358803,"ts":"2023-10-15 22:37:33"}
$ curl -s "https://steemyy.com/api/eth/gas/"
{"gas":7.4156933682,"block":18358803,"ts":"2023-10-15 22:37:33"}

See Gas Fee is Fixed Regardless the Amount of ETH to Send

Why ETH Gas Price/Fee is High?

The ETH gas price is determined by supply and demand. When there is a high demand for gas, the price increases. This could be due to a surge in the number of transactions on the Ethereum network, or it could be caused by traders speculating on the future gas price. Additionally, when network congestion increases, it becomes more difficult for miners to process transactions quickly and efficiently, which also drives up the gas price.

Why the ETH Gas price is fluctuating?

The Ethereum gas price fluctuates due to the number of transactions that are being processed on the network. The more transactions that are being processed, the higher the gas price will be in order to incentivize miners to prioritize those transactions and process them more quickly. When there is less activity on the network, the gas price will decrease as there is no need for miners to prioritize certain transactions.

Ethereum Blockchain

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
1401 words
Last Post: How to Modify or Patch the Compiled Executable (inplace, reverse engineering)?
Next Post: How to Get the Latest Block Number (Head Block) on Ethereum Blockchain?

The Permanent URL is: How to Get the Gas Price and Gas Fee on Ethereum Blockchain?

Leave a Reply