Code has been added to clipboard!

Solidity View Functions

Solidity View Functions Main Tips

  • In Solidity view functions are functions, that are promised not to modify the state.
  • Getter methods are a perfect example of view functions, as they are only used to retrieve a value instead of modifying the element, and are actually marked view.

Solidity View Functions

Functions are declarable as view, making them promise not to modify the state, thus only being used for viewing the state.

Here's a list of conditions for a statement to be considered as modifying the state:

  1. State variables being written to.
  2. Events being emitted.
  3. Other contracts being created.
  4. selfdestruct being used.
  5. Ether being sent via calls.
  6. Calling functions that are not marked view or pure.
  7. Low-level calls being used.
  8. Inline assembly containing certain opcodes being used.
Example
pragma solidity ^0.4.16;

contract cont {
    function func(uint x, uint y) view returns (uint) {
        return x * (y + 42) + now;
    }
}

Find Coding Exercises

Note: constant is actually an alias to the keyword view.

 

Warning: enforcing view method not to modify the state has not been implemented yet.