web3.js Guide – Estimate Gas Required for a Transaction Using estimateGas() Method in web3.js

web3js

I was wondering how the web3.js package estimates gas required for a transaction using the estimateGas() method, before it actually gets mined and executed on chain.

I have a solidity smart contract function failing on remix and/or metamask/web3 because it fails a require statement. so does web3.js actually check the require statements before even sending the tx?

If not, how else does it do it?
any help would be appreciated, thank you.

Best Answer

It basically issues a local static call to the contract, with the same inputs as in the real transaction. The call is only processed by your own node (or which ever node provider's node you use) and is not broadcast to rest of the blockchain at all. For this reason the call is fast and free.

The local static call can't make permanent state changes, but does its best to emulate state changes during the call. After the call has finished, it is guaranteed that there are no state changes in the contract. So if that call reverts, most likely the real transaction would revert as well, and you probably shouldn't send the real transaction.

Under the hood, there is a eth_estimateGas for this. https://www.quicknode.com/docs/ethereum/eth_estimateGas