0
0
BlockchainConceptBeginner · 3 min read

What is Event in Solidity: Explanation and Example

In Solidity, an event is a way for smart contracts to log information that external applications can listen to and react upon. Events act like messages that the contract sends out, which are stored on the blockchain and can be accessed by user interfaces or other off-chain tools.
⚙️

How It Works

Think of an event in Solidity as a notification system inside a smart contract. When something important happens, the contract "announces" it by emitting an event. This announcement is recorded on the blockchain, but it doesn't change the contract's state.

External programs, like websites or apps connected to the blockchain, can "listen" for these events. When they detect an event, they can respond, such as updating the user interface or triggering other actions. This is similar to how your phone receives notifications when a message arrives.

Events help keep the contract efficient because they store data in a special log that is cheaper to access than contract storage. They are mainly used for communication between the blockchain and the outside world.

💻

Example

This example shows a simple contract that emits an event when a value is stored.

solidity
pragma solidity ^0.8.0;

contract SimpleStorage {
    uint256 private data;

    // Declare an event
    event DataStored(uint256 indexed newValue);

    // Function to store a new value and emit the event
    function store(uint256 _value) public {
        data = _value;
        emit DataStored(_value);
    }

    // Function to read the stored value
    function retrieve() public view returns (uint256) {
        return data;
    }
}
Output
No direct output; event DataStored is logged with the new value when store() is called.
🎯

When to Use

Use events when you want to inform external applications about important actions inside your contract without storing extra data on-chain. For example:

  • Logging token transfers in a cryptocurrency contract.
  • Notifying when a user places a bid in an auction.
  • Tracking changes in contract ownership.

Events are essential for building interactive decentralized apps (dApps) because they allow the app to react quickly to blockchain changes.

Key Points

  • Events are logs stored on the blockchain that external apps can listen to.
  • They help communicate contract actions without changing contract storage.
  • Events are cheaper to store than regular contract data.
  • Use emit keyword to trigger an event.
  • Indexed parameters in events make it easier to filter and search logs.

Key Takeaways

Events in Solidity let contracts send messages that external apps can listen to.
They are used to log important actions without using expensive contract storage.
Use the emit keyword to trigger events inside functions.
Indexed event parameters help filter logs efficiently.
Events are crucial for building responsive decentralized applications.