Reacting to Ethereum Events with JavaScript

Published by Mario Oettler on

Open the Remix IDE, compile, and deploy the following contract:

pragma solidity ^0.8.16;

contract myEventContract{
    uint256 public price = 100000000000000;  // In Wei = 0.00001 ETH
    string public name;

    event NameSet(
        address indexed _from,
        string indexed _name,
        uint _amount
    );
    
    function setName(string memory _name) payable public{
        require(msg.value >= price, "Nicht genug Ether");
        name = _name;
        emit NameSet(msg.sender, name, msg.value);
    }
}

In lines 7 to 11, the event is declared. Its name is NameSet and provides the parameters _from, _name, and _amount.

In line 17, the event is emitted by the statement emit. The parameters transport the values in the same order as in the event declaration.

Leave the Remix IDE open.

Now, open your editor and copy the following JavaScript code:

const Web3 = require("web3");
var web3   = new Web3("wss://goerli.infura.io/ws/v3/<ENTER YOUR API KEY HERE>");

contractAddress = "<ADD CONTRACT ADDRESS HERE";

abi = // paste ABI here.

var contract = new web3.eth.Contract(abi,contractAddress);
console.log("Waiting for event");

contract.events.NameSet().on('data', function(event){
    console.log(event); 
});

In order to work, we need an account with Infura. Go to the website https://infura.io/ and create an account.

Copy the WebSocket connection and API key for the Goerli testnet (or any other public testnet you prefer) to line 2.

Copy the address of the smart contract to line 4.

Copy the ABI of the smart contract to line 6.

In line 8, we create the contract object.

In line 11, we subscribe to the event NameSet with Infura. It returns an event handler, and if it is fulfilled, the data are displayed in the console.

In Order to test it, run the file dapps2_event_01.js with nodejs on the terminal. It should display “Waiting for event”. Then, go to the Remix IDE and click the button setName. Remember to add a name and a sufficient value. It is important that you are connected to MetaMask (choose injected web3 as environment).

After the transaction has been included in a block, the terminal should show you the log details.

Categories: