• The state of the contract prior to execution is restored (reverted).

    Because gas is paid by the user who initiates the transaction, users are discouraged from calling functions that have a high gas cost. It is thus in the programmer’s best interest to minimize the gas cost of a contract’s functions. To this end, there are certain practices that are recommended when constructing smart contracts, so as to minimize the gas cost of a function call.

    Avoid Dynamically Sized Arrays

    Avoid Calls to Other Contracts

    Calling other contracts, especially when the gas cost of their functions is not known, introduces the risk of running out of gas. Avoid using libraries that are not well tested and broadly used. The less scrutiny a library has received from other programmers, the greater the risk of using it.

    Estimating Gas Cost

    If you need to estimate the gas necessary to execute a certain method of a contract considering its arguments, you could use the following procedure:

    gasEstimate will tell you the number of gas units needed for its execution. It is an estimate because of the Turing completeness of the EVM—it is relatively trivial to create a function that will take vastly different amounts of gas to execute different calls. Even production code can change execution paths in subtle ways, resulting in hugely different gas costs from one call to the next. However, most functions are sensible and estimateGas will give a good estimate most of the time.

    To obtain the gas price from the network you can use:

    Let’s apply our gas estimation functions to estimating the gas cost of our Faucet example, using the code from the book’s repository.

    Start Truffle in development mode and execute the JavaScript file in , gas_estimates.js.

    Example 5. gas_estimates.js: Using the estimateGas function

    Here’s how that looks in the Truffle development console: