Subscribing to Events

You can subscribe to the logs of the events from contracts deployed on your SKALE Chain.

Using Web3.js

For more reference, please see the Web3 Documentation: https://web3js.readthedocs.io/en/v1.5.2/web3-eth-subscribe.html#subscribe

Web3.js requires a websocket connection to subscribe to events/logs. For http/https connection for event subscriptions, see Ethers.js

Install the NPM Package

npm install --save web3

Subscribing to Event logs

import Web3 from "web3";

let web3 = new Web3("wss://your.skale.endpoint")

const imaAbis = require("./dir/to/contract-abi.json");
const address = imaAbis.contract_address;
);

var eventName = "EVENT_TO_TRACK";
var topic = web3.eth.abi.encodeEventSignature(eventName);

var filter = {
  address: address,
  topics: [topic],
  fromBlock: 0
};

web3.eth
  .subscribe("logs", filter, function (error, result) {
    if (!error) console.log(result);
  })
  .on("connected", function (subscriptionId) {
    console.log(subscriptionId);
  })
  .on("data", function (log) {
    console.log("Printing array of events:");
    console.log(log);
    document.getElementById("output").innerHTML += JSON.stringify(
      log,
      undefined,
      2
    );
  });

Using Ethers.js

For more reference, please see the Ethers.js documentation: https://docs.ethers.io/v5/api/providers/provider/#Provider-getLogs

Ethers.js doesn’t require a websocket connection to subscribe to events/logs. You can use http/https or ws/wss.

Install the NPM Package

npm install --save ethers

Subscribing to Event Logs

Any contract that emits events, can be subscribed. A generic example is provided below:

import { ethers } from "ethers";


let provider = new ethers.providers.JsonRpcProvider(
  "https://your.skale.chain.endpoint"

const imaAbis = require("./dir/to/contract-abi.json");
const address = imaAbis.contract_address;
);

var abi = ["event EventToTrack(bool result)"];
var iface = new ethers.utils.Interface(abi);

var filter = {
  address: address,
  topics: [iface.getEventTopic("EventToTrack")],
  fromBlock: 0
};

var callPromise = provider.getLogs(filter);

callPromise
  .then(function (events) {
    console.log("Printing array of events:");
    console.log(events);
    var parsedEvents = events.map(function (log) {
      return iface.parseLog(log);
    });
    document.getElementById("output").innerHTML = JSON.stringify(
      parsedEvents,
      undefined,
      2
    );
    console.log(parsedEvents);
  })
  .catch(function (err) {
    console.log(err);
  });