Lesson 4: Outline

Lesson 4 Introduction and outline.

Lesson 4: Error Handling and Events in Solidity

Objective: Understand how to handle errors and emit events in Solidity, which are critical for smart contract reliability and interaction with the front end.

Part 1: Error Handling in Solidity

  • Error Handling Mechanisms:

    • require: Used to check for conditions and revert the transaction if the condition is not met. It reverts all changes made to the state.

    • revert: Provides a way to trigger an exception and revert the transaction, often with a custom error message.

    • assert: Used for internal checks as a way to prevent conditions that should never be possible. It consumes all gas when failed.

  • When to Use Each:

    • Use require for input validation or to enforce proper conditions before execution.

    • Use revert for more complex condition checks, especially where a specific error message is helpful.

    • Use assert for invariants and to check for conditions that indicate a bug.

  • Example: Error Handling

    pragma solidity ^0.8.0;
    contract ErrorHandling { mapping(address => uint) public balance;
    
    function deposit() public payable {
        require(msg.value > 0, "Deposit amount must be greater than 0");
        balance[msg.sender] += msg.value;
    }
    
    function withdraw(uint amount) public {
        require(amount <= balance[msg.sender], "Insufficient balance");
        balance[msg.sender] -= amount;
        payable(msg.sender).transfer(amount);
    }

    }

Part 2: Events in Solidity

  • Understanding Events:

    • Events allow logging to the Ethereum blockchain.

    • Useful for tracking contract activity and interacting with the contract's front-end.

  • Declaring and Emitting Events:

    • How to declare an event and emit it in functions.

  • Example: Using Events

    pragma solidity ^0.8.0;
    contract EventExample { 
        event Deposit(address indexed sender, uint amount); 
        event Withdrawal(address indexed receiver, uint amount);
    
        mapping(address => uint) public balance;
        
        function deposit() public payable {
            emit Deposit(msg.sender, msg.value);
            balance[msg.sender] += msg.value;
        }
        
        function withdraw(uint amount) public {
            require(amount <= balance[msg.sender], "Insufficient balance");
            emit Withdrawal(msg.sender, amount);
            balance[msg.sender] -= amount;
            payable(msg.sender).transfer(amount);
        }
    }

Last updated