What is assert in Solidity: Usage and Examples
assert in Solidity is used to check for conditions that should never be false during contract execution. If the condition inside assert fails, the transaction is immediately stopped and all changes are reverted, signaling a serious error in the code.How It Works
Think of assert as a safety net in your Solidity code. It checks if something that must always be true actually is true. If it isn’t, the program stops right away and undoes everything done so far, like hitting an emergency stop button.
This is useful because it helps catch bugs or unexpected states that should never happen if the code is correct. Unlike other checks, assert is meant for internal errors, not for user input or expected failures.
Example
This example shows how assert can be used to ensure a number never becomes negative after subtraction.
pragma solidity ^0.8.0; contract AssertExample { int public count = 10; function subtract(uint value) public { count -= int(value); assert(count >= 0); // count should never be negative } }
When to Use
Use assert to check for conditions that should never happen if your code is correct, such as internal logic errors or impossible states. It is not for checking user input or expected errors.
For example, use assert to verify that a variable never goes out of a valid range or that an invariant holds true after a function runs. If assert fails, it means there is a bug that needs fixing.
Key Points
assertstops execution and reverts all changes if its condition is false.- It is used to catch serious bugs and internal errors.
- Failing
assertconsumes all remaining gas. - Do not use
assertfor input validation; userequireinstead.
Key Takeaways
assert checks for conditions that should never be false in your code.assert fails, the transaction stops and all changes are undone.assert to catch bugs and internal errors, not user mistakes.assert consumes all remaining gas, signaling a serious problem.