Subscribe to get access to this video

and the whole library of videos, sample code, and tutorials.

Web3 and Events Over WebSockets

Now let’s connect to the app in our browser and listen for events.

I’m going to be using Remix for this video, but remember, you don’t have to. You can use the geth console, or any other method you want to deploy your contracts.

Right now, I have remixd and geth running in my terminal and I also have my accounts unlocked, and geth setup to mine.

We start by deploying our contract then grab the contract address and the ABI.

// Deploy contract
// Copy ABI
pbpaste > src/MillionEtherPage.abi.json
cat src/MillionEtherPage.abi.json | jq '.'
// import the ABI
const abi = require('./MillionEtherPage.abi.json');

const mepAddress =
  '0x95361244b0cc2410c52ecb3e2b90c96e9448834c';

let mep = new web3.eth.Contract(abi, mepAddress);

We don’t need the checkBalance function anymore, so let’s get rid of it.

Now that we have our contract instance, there are two methods we can use to read events.

The first one gets historic events and the second one subscribes to all new events.

We haven’t generated any events for this contract yet, so let’s start with subscribing to new events.

Subscribing to new events

The contract instance exposes events on the events key. Here’s how we can watch for all new PixelChanged events:

// src/steps/003-websockets-events.js
mep.events.PixelChanged(
  {
    fromBlock: 0
  },
  function(error, event) {
    console.log('new event : ', event);
  }
);

Now let’s send an event that changes a pixel.

 

Subscribe to get the full text of this lesson

and the entire library of videos, sample code, and tutorials.