Skip to content

Add A Solidity Event

Now that you know why we need Events, let's add one and observe the output again!

Modify the contract code as follows:

//SPDX-License-Identifier: MIT
pragma solidity 0.8.13;

contract EventExample {

    mapping(address => uint) public tokenBalance;

    event TokensSent(address _from, address _to, uint _amount);

    constructor() {
        tokenBalance[msg.sender] = 100;
    }

    function sendToken(address _to, uint _amount) public returns(bool) {
        require(tokenBalance[msg.sender] >= _amount, "Not enough tokens");
        assert(tokenBalance[_to] + _amount >= tokenBalance[_to]);
        assert(tokenBalance[msg.sender] - _amount <= tokenBalance[msg.sender]);
        tokenBalance[msg.sender] -= _amount;
        tokenBalance[_to] += _amount;

        emit TokensSent(msg.sender, _to, _amount);

        return true;
    }
}

Re-Deploy with MetaMask

Let's re-deploy our contract with MetaMask and run the exact same Transaction. Here's what we can observe in the Transaction Details:

Suddenly we have "logs". These are in-sequence emitted events from the Smart Contract execution!

You will later see how you can listen to these events, query the blockchain for events and many more things.


Last update: May 4, 2022