[Ethereum] How Ethereum estimate the gas for running a contract

blockchaincontract-developmentgasgas-limitgo-ethereum

I am new to Ethereum. I know gas limit and gas price well. but still confused in

  1. when sending a transaction to run a deployed contract, does Ethereum suggest an estimation of how much gas limit is needed to complete the transaction?

  2. if so, How accurate is that estimation? In other words, will it always be completed successfully if only the estimation gas is being paid?

  3. if no, How can i know/predict the gas needed?

  4. For miners when they got a transaction to run a contract, are they able to know how much will it take to finish the execution (know how much gas limit (computational steps) this transaction costs) or they just know how much is the gas price?.

  5. How validators verify that miners executed a contract correctly? will they re-execute it again or just validate the block without running contracts?

I tried to figure these out, but still not be able.

Thanks

Best Answer

Geth does estimate the gas cost of a transaction, but theoretically no one--not geth, not the miners, nor anyone else--can know the gas cost of a transaction before it executed while creating a block. This is because something else could happen in a block before the transaction is executed (or even in the same block), thus changing the result that geth got when it made the estimate. It's even possible that geth made the estimate on a block that didn't even make it into the canonical blockchain.

Which brings the second point. geth gets its estimate by simulating the transaction itself, based on the latest block. There is essentially no other way to do so. This is called the Halting Problem, if you want to look it up, and it's why gas exists in the first place.

However, in most situations, sending the estimate is sufficient. It's even possible, in (IMHO) the majority of situations, to determine how much gas a transaction could ever possibly consume, and then use that.

Related Topic