In Solidity, require and assert are two statements commonly used for error handling, ensuring that code meets specific conditions before proceeding. The primary distinction between them lies in their intended purposes and the consequences when conditions are not satisfied.
require statement
The require function is typically employed for input validation or checking preconditions. It requires a condition and an optional error message parameter. If the condition evaluates to false, the current function call is immediately terminated, state changes are rolled back, but not all provided gas is consumed. The gas used is refunded, reducing the loss for malicious calls.
Example:
solidityfunction transfer(address to, uint amount) public { require(balance[msg.sender] >= amount, "Insufficient balance"); balance[msg.sender] -= amount; balance[to] += amount; }
In this example, require ensures the caller has sufficient balance to complete the transfer. If the balance is insufficient, the transaction is reverted and the error message "Insufficient balance" is displayed.
assert statement
assert is used to verify internal invariants and ensure no state errors (e.g., logical or numerical errors) occur. It accepts only a condition parameter. If the condition evaluates to false, it triggers a Panic error, consuming all provided gas and rolling back all state changes.
Example:
solidityfunction decrement(uint i) public { assert(i > 0); i--; }
Here, assert ensures the variable i does not become negative due to the decrement operation, which is an example of an internal consistency check.
Summary
Overall, require is used for validating external conditions (such as inputs and contract state), while assert is used for validating internal state to prevent major logical errors. require checks for external errors, whereas assert detects situations that should not occur in the code. When designing contracts, using these statements appropriately helps developers better manage and debug contract behavior, ensuring robustness and security.