Developer Fundamentals

-- I. Events

Learn to subscribe to smart contract events on VeChainThor using WebSockets, with filters for addresses, blocks, and emitters.

Listening to Events

In this lesson, you'll learn how to receive streams of contract-emitted events, allowing your apps to react to specific occurrences on the blockchain. ​We'll cover all the information required to understand how to listen, filter, and decode events.

To listen to events, you must connect to a VeChain node. Once the connection has been established, you'll learn:

  1. How to Filter Specific Events

  • Event parameters: We'll review the basic parameters you can use to filter events.

    • To and From parameters

  • Blockchain parameters: The parameters available to filter events from a specific contract

    • Emitter and Blocks parameters

  1. How to Decode Events

Before setting yourself up to listen to event changes, you'll need to establish a connection with a node.

This connection is managed using WebSockets, which connect directly to a VeChain node. A simple connection can be established with this snippet:

import { subscriptions } from '@vechain/sdk-network';
import WebSocket from 'ws';

const wsUrl = subscriptions.getNewTransactionsSubscriptionUrl(
  'https://mainnet.vechain.org'
);

const ws = new WebSocket(wsUrl);

ws.onmessage = (message) => {
  const eventLog = JSON.parse(message.data);
  console.log('Received data', eventLog);
}

This will receive all events on the blockchain as JSON-encoded strings.

The VeChain SDK assists in constructing filters to retrieve only the desired data by creating a subscription URL with the specified parameters. Using the subscriptions helper, a custom subscription URL can be built that listens only to the specified event:

const wsUrl = subscriptions.getEventSubscriptionUrl(
  'https://mainnet.vechain.org',
  "event Transfer(address indexed from, address indexed to, uint256 value)",
  contractInterface.getEvent('Transfer')
);

Filters can be adjusted to show only events that meet specific criteria. These parameters must be indexed and are given as a list.

The transfer event uses two indexed parameters:

  • from – sender address

  • to – recipient address

To filter all transfers originating from a specific address, supply that address as the first parameter:

const wsUrl = subscriptions.getEventSubscriptionUrl(
  'https://mainnet.vechain.org',
  contractInterface.getEvent('Transfer'),
  ['0x0000000000000000000000000000456e65726779']
);

To filter all transfers to a specific address, provide only the second value in the list:

const wsUrl = subscriptions.getEventSubscriptionUrl(
  'https://mainnet.vechain.org',
  contractInterface.getEvent('Transfer'),
  [null, '0x0000000000000000000000000000456e65726779']
);

When using filters, all provided values must match for the filters to apply.

Emitter

Many contracts emit similar events, which sometimes require restricting listening to a specific contract.

An optional argument can be used to filter for a particular contract address.

For example, to listen exclusively for VTHO transfers from the VTHO contract at 0x0000000000000000000000000000456e65726779 it would be defined as follows:

const wsUrl = subscriptions.getEventSubscriptionUrl(
  'https://mainnet.vechain.org',
  contractInterface.getEvent('Transfer'),
  [],
  { address: '0x0000000000000000000000000000456e65726779' }
);

Blocks

To resume listening from a specific block position, the options can define a blockID to continue from where a previous listener may have disconnected.

The events are received as JSON-encoded strings. These strings must be parsed and decoded into usable objects. Using the contract interface defined earlier, you can decode these events with the parseLog() function.

ws.onmessage = (message) => {
  // data is received as text and needs to be converted into an object first
  console.log('Received data', message.data);
  const eventLog = JSON.parse(message.data);

  const decoded = contractInterface.parseLog(eventLog);
  if (!decoded || decoded?.name !== 'Transfer') {
    throw new Error('Unknown Event');
  }

  // decoded.args will have the following attributes:
  // decoded.args.from, decoded.args.to, decoded.args.value
  // and
  // decoded.args[0], decoded.args[1], decoded.args[2]
}

Generic transaction details such as ID, block information, or the origin of the transaction are available in the object as well.

Try It Yourself

import { subscriptions } from '@vechain/sdk-network';
import WebSocket from 'ws';

const wsUrl = subscriptions.getEventSubscriptionUrl(
  'https://mainnet.vechain.org',
  "event Transfer(address indexed from, address indexed to, uint256 value)",
  [],
  { address: '0x0000000000000000000000000000456e65726779' }
);

const ws = new WebSocket(wsUrl);

ws.onopen = () => {
  console.log('Connected to', wsUrl);
};

ws.onmessage = (message) => {
  const eventLog = JSON.parse(message.data);
  console.log('Received data', eventLog);
};