4. Error Handling, Events, and Security Basics
Since smart contracts cannot be modified once deployed, robust error handling and built-in security are essential from the start.
4.1. Error Handling (require, revert, assert)
- require(condition, "message"): Checks the validity of user input or state variables. Most frequently used. If the condition is not met, it reverts the transaction and refunds the remaining gas to the user.
- revert("message"): Similar to
require, it reverts the transaction but is used explicitly for more complex conditions. - assert(condition): Used to check for internal errors or bugs. (Generally,
requireis recommended for user/external condition errors).
4.2. Events
Events log data onto the blockchain in log form, allowing the front-end of a DApp to subscribe to state changes in the contract. This is a gas-efficient method.
event ValueChanged(address indexed user, uint256 newValue);
function updateValue(uint256 x) public {
// ... logic ...
emit ValueChanged(msg.sender, x);
}
4.3. Basic Security Pattern: Preventing Reentrancy
One of the most dangerous vulnerabilities related to external calls is the Reentrancy Attack. To prevent this, you must use the 'Checks-Effects-Interactions' pattern.
- Checks: Execute all
requirestatements. - Effects: Update state variables (most crucial).
- Interactions: Make external calls (last step).