The assert statement in Solidity is used to check for conditions that should never be false. It is a way to enforce invariants in your contract's logic. If the condition specified in the assert statement evaluates to false, the transaction is reverted, and all changes made during that transaction are undone. Unlike require, which is used for input validation, assert is used to catch programming errors.

Purpose of the Assert Statement

  • Invariants Checking: To ensure that certain conditions always hold true during the execution of the contract.
  • Internal Errors: To catch internal errors and bugs in the code that should never happen if the contract is correctly implemented.
  • Debugging: To help developers identify logical errors during development.

Syntax

assert(condition);

Sample Code for Assert Statement


// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract AssertExample {
uint256 public totalSupply;

constructor(uint256 initialSupply) {
totalSupply = initialSupply;
assert(totalSupply > 0); // Ensure that totalSupply is greater than 0
}

function mint(uint256 amount) public {
require(amount > 0, "Amount must be greater than 0");
totalSupply += amount;
assert(totalSupply >= amount); // Check that totalSupply is correctly updated
}

function burn(uint256 amount) public {
require(amount > 0, "Amount must be greater than 0");
require(amount <= totalSupply, "Amount exceeds total supply");
totalSupply -= amount;
assert(totalSupply + amount == totalSupply); // Ensure totalSupply is correctly updated
}
}

How It Works

In the above example, the AssertExample contract uses the assert statement in two places:

  • In the constructor, it checks that totalSupply is greater than 0 when the contract is deployed.
  • In the assert0 function, it checks that totalSupply is updated correctly after adding the new amount.
  • In the assert2 function, it verifies that the total supply remains consistent after burning tokens.

Key Points to Remember

  • The assert statement is used for checking conditions that should never be false if the code is correct.
  • When an assert fails, it consumes all remaining gas and reverts the transaction.
  • It is not intended for user input validation; use require for that purpose.
  • Use assert primarily for internal error checking and to catch bugs during development.

Conclusion

The assert statement is a powerful tool in Solidity for enforcing invariants and catching programming errors. By using assert effectively, developers can ensure that their contracts behave as intended and that any internal errors are detected early in the development process.