When a function in a contract is called, if the gas limit is not enough, the out-of-gas exception occurs and the sender loses his gas. How to know in advance how much gas enough for any arguments values passed to the function?
2 Answers
You can get a rough estimate using mix (and the future release remix).
It's very difficult to know in advance how much gas will be used for each contract (contracts have branches that dictate the flow of execution as a function of input parameters. This leads to an exponentially increasing number of states the contract can switch to).
-
In fact I'm investigating the way to do this thing based on abstract interpretation. However, the gas cost for EVM instructions is complicated (e.g., it involves cost of memory, storage access and the instruction type itself with the form of polynomial, logarithm). For example, we do something with functional languages here raml.co and people do with imperative programs in C/C++ arxiv.org/abs/1401.5842– Chan NgoCommented Aug 20, 2016 at 0:32
You can run a simulation of your call with myContract.myFunction.call(arguments, { from: account, gas: TEST_VALUE })
. If it fails because of gas here then it will likely fail when you send it as part of a transaction.
I say likely because other transactions may have modified the state between your .myFunction.call()
and .myFunction()
.
-
thanks Xavier. However you cannot run any contract bytecode to estimate the gas consumed. Assume that in your contract code, you call some external contract's functions. However, which function to call and which arguments depend on the business logic of your contract code. In its turn, the business logic depends on the inputs. Thus, somehow you cannot determine manually which functions, which arguments.– Chan NgoCommented Aug 20, 2016 at 0:26
-
True, which is why doing a test run with
.call
can help. Commented Aug 22, 2016 at 11:23
estimateGas(...)
call in ethereum.stackexchange.com/questions/7557/…