Solidity Require Statements
A require statement checks a condition before a function changes anything. If the check fails, the call reverts and nothing changes.
Require demands a positive amount
Adding points must add something. Require stops a zero amount before any points change.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract PointsLedger {
uint256 public points;
function addPoints(uint256 amount) public {
require(amount > 0, "Amount must be positive");
points += amount;
}
}
Require guards spending too
Spending needs enough points first. Require checks the balance before any points are removed.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract SpendLedger {
uint256 public points;
function addPoints(uint256 amount) public {
require(amount > 0, "Amount must be positive");
points += amount;
}
function spendPoints(uint256 amount) public {
require(amount <= points, "Not enough points");
points -= amount;
}
}
Two requires can guard a range
A level must sit between 1 and 10. Each require checks one end of the range.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract LevelBoard {
uint256 public level;
function setLevel(uint256 newLevel) public {
require(newLevel >= 1, "Level must be at least 1");
require(newLevel <= 10, "Level must be at most 10");
level = newLevel;
}
}
Example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract GuardedPoints {
uint256 public points;
function addPoints(uint256 amount) public {
require(amount > 0, "Amount must be positive");
points += amount;
}
function spendPoints(uint256 amount) public {
require(amount > 0, "Amount must be positive");
require(amount <= points, "Not enough points");
points -= amount;
}
}
Key points
- Require: a check that stops a call when its condition is false.
- Revert: a failed call that undoes every change from that call.
- Use require at the start of a function to guard its inputs.
- The text in quotes is the message shown when the check fails.
- Code after a failed require does not run.
In this example, addPoints starts with a require that the amount is positive. The spendPoints function checks that the amount is positive and that the balance covers it. A call that fails either check reverts. The stored points stay exactly as they were before the failed call.
Note
a revert also undoes changes made earlier in the same call.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Remix IDE
Exercise
What happens when a require condition is false?