24 - Function Mutability
Function Mutability Specifiers: Functions can be specified as being pure
or view:
-
view
functions can read contract state but cannot modify it. This is enforced at runtime viaSTATICCALL
opcode. The following are considered state modifying:- Writing to state variables
- Emitting events
- Creating other contracts
- Using selfdestruct
- Sending Ether via calls
- Calling any function not marked
view
orpure
- Using low-level calls
- Using inline assembly that contains certain opcodes.
-
pure
functions can neither read contract state nor modify it. The following are considered reading from state:- Reading from state variables
- Accessing
address(this).balance
or<address>.balance
- Accessing any of the members of
block
,tx
,msg
(with the exception ofmsg.sig
andmsg.data
) - Calling any function not marked
pure
- Using inline assembly that contains certain opcodes.
-
It is not possible to prevent functions from reading the state at the level of the EVM. It is only possible to prevent them from writing to the state via
STATICCALL
. Therefore, onlyview
can be enforced at the EVM level, but notpure
.
- View or Pure
- View: Read State
- Not Modify ->
STATICCALL
- Not Modify ->
- Pure: Not Modify
- Not Read -> !EVM
- Mutability: Write/Read
- Security Implications
System Operations Solidity By Example - View and Pure Functions
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
contract ViewAndPure {
uint public x = 1;
// Promise not to modify the state.
function addToX(uint y) public view returns (uint) {
return x + y;
}
// Promise not to modify or read from the state.
function add(uint i, uint j) public pure returns (uint) {
return i + j;
}
}