Reading and Writing State
Part of the Fundamentals section of Coddy's Solidity journey. Lesson 27 of 53.
A view function may read contract state but may not change it. A function that writes state cannot be marked view or pure. Separate a getter that reads a value from a setter that changes it to make each function purpose clear.
Declare this at contract scope:
uint256 stored;
function setValue(uint256 n) internal {
stored = n;
}
function readValue() internal view returns (uint256) {
return stored;
}Use it inside the provided main function:
setValue(18);
console.log(readValue());setValue writes the shared stored variable. readValue is view because it returns that variable without changing it. main also writes indirectly by calling setValue, so its header has no view or pure modifier.
A function that writes contract state cannot be marked view.
Challenge
EasyDeclare state level, a setter setLevel and a view getter getLevel. main must set level to the supplied nextLevel, then print the getter result.
The tests pass arguments to main in this order: uint256 nextLevel. Each test starts with fresh contract state.
Use console.log for the requested output. Print only the requested values, one per line, with no extra labels unless the task specifies them.
Try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import "forge-std/console.sol";
contract Main {
function main(uint256 nextLevel) external {
// Write your solution here.
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
Practice on your own: Solidity playground