Envoy-VC / 30-Days-of-Solidity
30 Days of Solidity step-by-step guide to learn Smart Contract Development.
This is Day 17
of 30
in Solidity Series
Today I Learned About Assert Statement in Solidity.
Assert Statement
Its syntax is similar to the require statement. It returns a boolean value after the evaluation of the condition. Based on the return value either the program will continue its execution or it will throw an exception. Instead of returning the unused gas, the assert statement consumes the entire gas supply and the state is then reversed to the original state. Assert is used to check the current state and function conditions before the execution of the contract. Below are some cases with assert type exceptions :
- When an assert is called with a condition that results in false.
- When a zero-initialized variable of a function is called.
- When a large or a negative value is converted to an enum.
- When a value is divided or modulo by zero.
- When accessing an array in an index which is too big or negative.
Syntax:
assert(condition);
Example:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
contract ErrorsAndChecks {
bool result;
function assertStatement(uint256 _num1, uint256 _num2) public {
uint256 sum = _num1 + _num2;
assert(sum <= 255);
result = true;
}
function checkAssert() public view returns (string memory) {
if (result == true) {
return "No Overflow";
} else {
return "Overflow exist";
}
}
}
Output:
when we pass input as 78 and 84 and then run the checkAssert function we get the output as
0 : string: No Overflow
as sum = 78 + 84 = 162 is less than or equal to 255.
when we pass input as 198 and 84 and then run the checkAssert function we get the output as
0 : string: No Overflow
as sum = 198 + 84 = 282 is greater than 255.
Top comments (0)