Go-Ethereum Gas Estimate – How to Properly Estimate Gas Costs of Function Calls with Go-Ethereum and Golang

gasgas-estimategas-limitgo-ethereumgolang

I'm attempting to build out a program in golang to model ethereum gas costs of function calls for the smart contracts I write. I've successfully been able to estimate them using ethclient.EstimateGas however the reported gas costs seem incredibly underpriced, anywhere from 22K->24K gas to send tokens, and alter some boolean variables in storage? There is no way that's the correct gas cost. I'm unable to find out how websites like ethgasstation can reliably estimate gas costs, if the costs reported back by go-ethereum library barely even match real world costs?

Best Answer

I can't tell you why the ethclient.EstimateGas underreports the consumed gas. I remember facing the same problem once and my lazy solution was to multiply whatever it reported by 3.

In order to calculate the correct gas price for a method call, you need the binary EVM code of the contract. Once you have that, you can look up the price of each instruction in the Yellow Paper in Appendix G and H. The hard part of this calculation is, however, that the precise gas cost will depend upon the state of the virtual machine executing the code (the EVM). In order to calculate that correctly, you probably need to simulate the whole virtual machine. And in the general case, the whole Ethereum blockchain, i.e., you need an Ethereum blockchain node.

If you for example call the ERC20 function transfer, you will end up paying at least 21,000 gas just to make the function call and between 10,000 and 40,000 to update the balances and 400 to read the balances plus additional gas to pay for the jump table logic at the beginning of the contract. The amount paid to update each balance (sender and receiver) will depend on whether the address has a balance or not (5,000 gas vs. 20,000 gas for each update) so you need to know the whole state of the virtual machine. In other cases, you would need to know the state of other Ethereum accounts such as balances or deployed smart contracts.