3

I have read multiple times that everything costs gas on ethereum. But when I write and use a function that does not change the state of a contract (i.e sum up two parameters and return the sum) that does not cost any gas.

So, where does the statement "everything costs gas on ethereum" mean now actually?

4

Functions that do not change the state can be explicitly written as read-only functions using the modifiers view and pure (previously constant).

  • view: Will read the state but will not change it.
  • pure: Does not need access to the state and will not change it.

A client can also invoke any function using the Web3 .call() method.

In all three cases the following apply:

  1. The contract will run on local CPU using local copy of the blockchain (if needed at all) and there will be no network verification of anything.
  2. The EVM gas accounting applies and will be tracked. That is, if the contract function includes gas accounting (how much is left?) then it will work as normal in a "dry run" mode, using call(), for example. Same applies to "out of gas" situations. Sufficient gas must be supplied with the request.
  3. Since there is no network verification, there is no possibility of a state change. This includes the result that ether spent to supply gas is, effectively, returned. More precisely, it was never really sent because the network wasn't informed.

Each assembler-level OPCODE has a certain cost. It might be a slightly more precise generalization to say that all state-changing operations cost gas. I would like to say reads are free. In the end, they are, when implemented appropriately. Hopefully the details above provide some clarity about what's going on.

Hope it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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