[Ethereum] Estimate Gas Price (not Gas) using Web3

contract-deploymentcontract-developmentgasjavascriptweb3js

Using Web3, we are able to estimate the amount of gas needed for a transaction

let estimatedGas = web3.eth.estimateGas({
    to: "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe",
    data: "0xc6888fa10000000000000000000000000000000000000000000000000000000000000003"
})

contractObject.deploy().send({gas:estimatedGas, gasPrice: 2e9, ...})

Question: How can we estimate the gasPrice to use, instead of defining a static value like 2 Gwei?

Best Answer

Average gas price can be calculated (as a median for the last several blocks) by using the following code:

web3.eth.getGasPrice().then((result) => {
console.log(web3.utils.fromWei(result, 'ether'))
})
Related Topic