Consider the following Solidity function:
function testRequire(uint x) public pure returns (string memory) {
require(x > 10, "x must be greater than 10");
return "Passed require";
}What happens when testRequire(5) is called?
function testRequire(uint x) public pure returns (string memory) {
require(x > 10, "x must be greater than 10");
return "Passed require";
}Remember, require checks a condition and reverts if false.
The require statement checks if x > 10. If false, it reverts the transaction with the given error message. Since 5 is not greater than 10, it reverts with 'x must be greater than 10'.
Analyze this Solidity function:
function testAssert(uint x) public pure returns (string memory) {
assert(x != 0);
return "Passed assert";
}What happens when testAssert(0) is called?
function testAssert(uint x) public pure returns (string memory) {
assert(x != 0);
return "Passed assert";
}assert is used to check for conditions that should never be false.
The assert statement checks if x != 0. If false, it triggers a panic error and reverts the transaction without a custom message. Since x is 0, it reverts with an 'assertion failed' error.
Consider this Solidity function:
function testRevert(uint x) public pure returns (string memory) {
if (x < 5) {
revert("x must be at least 5");
}
return "Passed revert";
}What happens when testRevert(3) is called?
function testRevert(uint x) public pure returns (string memory) {
if (x < 5) {
revert("x must be at least 5");
}
return "Passed revert";
}revert immediately stops execution and reverts the transaction with a message.
The if condition is true because 3 is less than 5, so revert is called with the message 'x must be at least 5', reverting the transaction.
Look at this Solidity function:
function checkValue(uint x) public pure returns (string memory) {
require(x > 0, "x must be positive");
assert(x < 10);
if (x >= 10) {
revert("x is too large");
}
return "Value is valid";
}Why does calling checkValue(10) always revert?
function checkValue(uint x) public pure returns (string memory) {
require(x > 0, "x must be positive");
assert(x < 10);
if (x >= 10) {
revert("x is too large");
}
return "Value is valid";
}Check the order of assert and revert statements.
The assert(x < 10) fails when x is 10, causing an immediate revert with a panic error before the if and revert statements are reached.
Choose the correct statement about require, assert, and revert in Solidity:
Think about gas consumption and error messages for each statement.
require and revert refund remaining gas and can include error messages. assert is for internal errors and uses all remaining gas on failure.