▫️Lesson 2.4: Events and Inheritance in Solidity

Module 2: Developing Smart Contracts with Solidity

Objective

This lesson explores two advanced concepts in Solidity: events and inheritance. Events allow smart contracts to communicate with external consumers, while inheritance enables contracts to extend and reuse code. Understanding these concepts is crucial for efficient smart contract development.


Events in Solidity

Definition: Events are a way for smart contracts to log activity that external applications can listen for and act upon. They are crucial for tracking contract activity and changes in state variables without much gas expenditure.

Usage:

  • Events are declared using the event keyword.

  • They are emitted using the emit keyword followed by the event name and parameters.

Example:

pragma solidity ^0.8.0;

contract EventsExample {
    // Event declaration
    event ValueChanged(uint oldValue, uint newValue);

    uint public value;

    // Function to change value and emit an event
    function setValue(uint _value) public {
        emit ValueChanged(value, _value); // Emitting an event
        value = _value;
    }
}

Inheritance in Solidity

Definition: Inheritance allows a contract to acquire properties and behavior (functions and variables) from another contract. This promotes code reusability and extension in smart contract development.

Usage:

  • Inheritance is declared using the is keyword.

  • Derived contracts can override inherited functions with the override keyword.

Example:

pragma solidity ^0.8.0;

// Base contract
contract Base {
    function getValue() public pure returns (uint) {
        return 100;
    }
}

// Derived contract
contract Derived is Base {
    // Overriding getValue function from Base contract
    function getValue() public pure override returns (uint) {
        return 200;
    }
}

Activity: Implementing Events and Inheritance

  1. Create a base contract: Use Remix IDE to define a base contract with a few functions and an event.

  2. Implement a derived contract: Create a derived contract that inherits from the base contract. Override one of the base contract's functions and emit an event.

  3. Test functionality: Deploy both contracts in Remix and test the overridden function and event emission to ensure they work as expected.


Exercise

Hands-On Practice:

  • Extend the EventsExample contract by adding a new event that logs when the value is set to the same number twice in a row. Implement logic in the setValue function to emit this new event under the specified condition.


This lesson has covered events and inheritance in Solidity, two powerful features that enhance the functionality and efficiency of smart contracts. Events provide a way to log and react to contract activities, while inheritance promotes code reuse and organization.

Last updated