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:
- 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.
- 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.
- 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.