Solidity View and Pure
A view function is a function that reads stored data and changes nothing. A pure function uses only its inputs and reads no stored data at all.
View reads state and changes nothing
readScore is marked view. It returns the stored score and leaves the stored value as it was.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract ScoreView {
uint256 public score;
function setScore(uint256 newScore) public {
score = newScore;
}
function readScore() public view returns (uint256) {
return score;
}
}
Pure uses only its inputs
add is marked pure. It works only with the two numbers sent in and touches no stored data.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract PureMath {
function add(uint256 first, uint256 second) public pure returns (uint256) {
return first + second;
}
}
A view function cannot change state
This code does not compile. setScore is marked view, but its body tries to change the stored score, so the compiler rejects it.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract BrokenView {
uint256 public score;
function setScore(uint256 newScore) public view {
score = newScore;
}
}
Example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract PriceBoard {
uint256 public price;
function setPrice(uint256 newPrice) public {
price = newPrice;
}
function half(uint256 amount) public pure returns (uint256) {
return amount / 2;
}
function halfPrice() public view returns (uint256) {
return half(price);
}
}
Key points
- View: a view function reads state variables and leaves them unchanged.
- Pure: a pure function uses only its parameters and its own local work.
- Promise: the view and pure words are promises the compiler checks.
- Compiler check: the compiler rejects a view function that tries to write state.
- No promise: a function with neither word is allowed to change state.
In this example, half is pure, so it halves only the number sent in. halfPrice is view, so it reads the stored price and hands it to half. Calling halfPrice leaves the stored price unchanged.
Note
calling a view or pure function from outside still returns its result like any other call.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Remix IDE
Exercise
Which function is allowed to read a state variable?