When I am calling (sending a transaction to) a contract how do I determine how much gas to use? Is there a way to calculate this upfront & what happens if I send too much / too few gas?

  • The last part of your question, about sending too much/little gas, is answered here. The first part of the question is a good one to add, though. Upvoted! – Jeff Coleman Jan 21 '16 at 7:58
up vote 18 down vote accepted

There are estimateGas APIs in both the JSON-RPC and Javascript.

They are estimates and for developers that want further precision, testing is required, possibly on a private chain.

If too much gas is provided, the excess gas is converted to ether and refunded. If too few gas is specified, all the specified gas is forfeited to the miner and the transaction is reverted: just like the contract was never called.

Users will generally have to trust the DApp they are using, and DApps that have good UI and UX, may indicate some estimated costs to the user, or possibly even hide such details by sending the user's account some ether, or giving a new user an account that has some ether.

This is feasible because most transactions require a very small amount of ether; 1 ether is 10^18 wei and can run many transactions. As an example, if one were simply using Ethereum to transfer wei/ether around, at the current gas price of 5 Gigawei, a user can do around 9523 transfers with 1 ether. This is because a value transfer transaction costs 21000 gas, and thus the computation is 1e18 / (21000 * 5e9) = 9523.80.

  • For those reading this in June 2017, that's now 40 US cents ($.40) per transaction. When it was written, ETH was $1.53 thus it was about .16 US Cents ($.0016) cents per transaction. Since Ether has gone up so dramatically, efficient contract programming is going to be key. If I wanted to transfer money right now, the minimum gas is .0024 ETH, which is 91 US Cents. Transaction prices are getting up there because the currency is valued so high right now. – Hans Jun 14 '17 at 19:08
  • I've updated the answer to reflect that gas prices are now around 5 Gwei instead of 50 Gwei. If ether is $300, that is a transaction fee of 3.15 cents (21000*5e9 / 1e18 * 300 = 0.0315) ethgasstation.info also suggests a current safe low gas price of 2 Gwei which leads to a fee of 1.26 cents. – eth Jun 23 '17 at 6:06

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.