envoy1084
/
30-Days-of-Solidity
30 Days of Solidity step-by-step guide to learn Smart Contract Development.
WARNING: This repository is currently undergoing updates and revisions to incorporate the latest information and advancements in Solidity programming. Please be advised that the content may not be up-to-date or accurate during this time. We expect the updates to be completed within the next 30 days, and appreciate your patience during this process. Thank you for your understanding.
Contents
- Day 1 - Licenses and Pragma
- Day 2 - Comments
- Day 3 - Initializing Basic Contract
- Day 4 - Variables and Scopes
- Day 5 - Operators
- Day 6 - Types
- Day 7 - Functions
- Day 8 - Loops
- Day 9 - Decision Making
- Day 10 - Arrays
- Day 11 - Array Operations
- Day 12 - Enums
- Day 13 - Structs
- Day 14 - Mappings
- Day 15 - Units
- Day 16 - Require Statement
- Day 17 - Assert Statement
- Day 18 - Revert Statement
- Day 19 - Function Modifiers
- Day 20…
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)