0

Solidity: Events.

Events are mostly utilized to communicate back with whoever invoked the contract in the first place, this can be a client implemented in web3.js for example or it can also be another contract. Let’s say you want to invoke a function on a smart contract using a web3.js client and you want to obtain the value returned by the function to display it in the user interface, when the smart contract function is invoked by the client, it will not return the value calculated by the function, instead it will return the hash of the transaction.

This is where events come in handy, you can call the smart contract function and watch for an event on the client, once the event is emitted by the smart contract, the client will be notified and data passed in the event will be available at the client side. By the same token, you can also use events to asynchronically trigger an action on the client without the client initiating the request (which is different to the use case described in the example above).

Also, every time an event is emitted, the event and the data within the event is written into the blockchain logs (which live in the blockchain itself), this makes events useful for keeping logs of everything that happens within the contract, therefore, logging is another useful feature of events.

Bottom line, there are 3 main uses for events:

  1. To return values to an invoking client.
  2. To trigger actions on the invoking client.
  3. To log information.

Let’s take the following contract as example, here when fooFunction is invoked, on line 7 we can see the event sendValueBack is emitted, this returns the value of the addition back to the invoker and also logs both the address of the invoker and the value in the blockchain (data is logged in the blockchain itself).

contract fooContract {
    using SafeMath for uint256;
    event sendValueBack(address indexed addr, uint256 val);

    function fooFunction(uint256 val) returns (uint256) {
        uint256 result = val.add(10);
        emit sendValueBack(msg.sender, result);
        return result;
    }
}


<< Prev

Next >>