Ethereum – How to Determine Gas Usage When Calling a Contract

contract-invocationgastransactions

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?

Best Answer

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.