Skip to main content

Command Palette

Search for a command to run...

Events in Solidity

Published
•2 min read•View as Markdown
Events in Solidity

Events

  1. In Solidity, events are a way for a contract to communicate with the outside world and notify external applications of certain actions or state changes that have occurred in the contract.

  2. An event is defined using the event keyword, and it can have one or more parameters, which define the data that will be emitted along with the event. Events are defined in the contract, but they can be emitted from anywhere in the contract.

Here's an example of how events can be used:

contract MyContract {
    event NewTransaction(address indexed from, address indexed to, uint amount);

    function transfer(address to, uint amount) public {
        require(balance[msg.sender] >= amount, "Insufficient balance");

        // update balances
        balance[msg.sender] -= amount;
        balance[to] += amount;

        // emit the event
        emit NewTransaction(msg.sender, to, amount);
    }
}
  1. In this example, the MyContract contract has an event named NewTransaction, which is emitted every time a transfer is made between two accounts. The event has three parameters: from, to, and amount.

  2. Inside the transfer function, the require statement ensures that the sender has enough balance to make the transfer. After the transfer is made, the NewTransaction event is emitted with the relevant parameters.

  3. When an event is emitted, the data is stored in the blockchain and can be accessed by external applications. Applications can subscribe to events and receive notifications when they are emitted, which allows them to track the state of the contract and respond to changes in real-time.

  4. It's important to note that emitting events can be a useful tool for debugging and monitoring the state of a contract, but it also has a gas cost. Therefore, events should be used judiciously and only when necessary.

More from this blog