VeChain Docs
  • Welcome to VeChain
  • Blockchain Basics
    • Introduction to blockchain
    • Introduction to digital property
    • The evolution of the internet
  • Introduction to VeChain
    • About the VeChain blockchain
      • Consensus Deep Dive
      • Governance
    • Dual-Token Economic Model
      • VeChain (VET)
      • VeThor (VTHO)
    • Acquire VeChain Assets
    • Sustainability
  • Core Concepts
    • Networks
      • Thor Solo Node
      • Testnet
      • Mainnet
    • Nodes
      • Node Rewards Programme
    • Blocks
      • Block Model
    • Transactions
      • Transaction Model
      • Transaction Fees
      • Transaction Calculation
      • Meta Transaction Features
        • Transaction Uniqueness
        • Controllable Transaction Lifecycle
        • Clauses (Multi-Task Transaction)
        • Fee Delegation
          • Multi-Party Payment (MPP)
          • Designated Gas Payer (VIP-191)
        • Transaction Dependency
    • Block Explorers
    • Wallets
      • VeWorld
        • User Guide
          • Setup
          • Wallet
          • Signing
          • Activities
          • Settings
        • FAQ
      • Sync2
        • User Guide
          • Setup
          • Wallet
          • Signing
          • Activities
          • Settings
        • FAQ
      • Sync
        • User Guide
          • Wallet
          • Ledger Device
          • Browser dApps and web
          • Interact with dApps
          • Activities
          • Settings
          • Report an Issue
          • Contributing
        • FAQ
    • EVM Compatibility
      • VeChain Modifications
      • Methodology
      • Test Coverage
        • Gas model
        • Raw transaction
        • hardhat specific
          • Ganache failures
          • evm_increaseTime
        • Failures in constructor
        • eth_sign
        • Contract address prediction
        • BadBeacon proxy address at 0x1
      • How to Recreate
      • Additional Information
        • Using Governance Contracts
        • ERC1820/ERC777 Testnet
        • Delegate Options
    • Account Abstraction
      • UserOperation
      • Bundler
      • EntryPoint Contract
      • Account Factory Contract
      • Paymaster Contract
    • Token Bound Accounts
  • How to run a node
    • Nodes
    • How to run a Thor Solo Node
    • Custom Network
    • Connect Sync2 to a Thor Solo Node
  • Developer Resources
    • Getting Started
    • How to build on VeChain
      • Connect to the Network
      • Read Data
        • Read Blocks
        • Read Transactions
        • Read Accounts
        • States & Views
        • Events & Logs
        • VET Transfers
      • Write Data
        • Transactions
        • Fee Delegation
      • Listen to Changes
        • Events
        • VET Transfers
        • Transactions
        • Blocks
        • Beats
      • Build with Hardhat
      • Utilities
        • BigInt and Unit-Handling
        • Name Service Lookups
    • Example dApps
      • Buy me a Coffee
      • Token Bound Accounts
      • PWA with Privy and Account Abstraction
    • EVM Compatibility for Developers
      • Key Architectural Differences and Optimizations
      • Practical Implications for Developers: Key Considerations
      • RPC Methods (Detailed Breakdown)
      • Frequently Asked Questions (FAQs)
      • VeChain Blockchain Specifications
      • Key Differences Between VeChain and Ethereum (Summary)
      • Best Practices for Developing on VeChainThor
    • How to verify Address-Ownership
      • Next.js Session Verification
    • Debug Reverted Transactions
    • Account Abstraction
    • VIP-191: Designated Gas Payer
      • How to Integrate VIP-191 (I)
      • How to Integrate VIP-191 (II)
      • How to Integrate VIP-191 (III)
    • Index with Graph Node
      • Setup with Docker
      • Index with OpenZeppelin
        • Create Subgraph Project
        • Configure Contracts
        • Deploy Subgraph and start Indexing
        • Track Subgraph Indexing
        • Access Subgraph
        • Update Subgraph
    • SDKs & Providers
      • SDK
        • Architecture
        • Accounts
        • Bloom Filter
        • Certificates
        • Contracts
        • Cryptography
        • Debug
        • Encoding
        • Polls
        • Subscriptions
        • Thor Client
        • Transactions
      • Thor DevKit
        • Installation
        • Usage
          • Cryptography
          • Accounts
          • Encoding
          • Transactions
          • Certificates
          • Bloom Filter
      • DApp Kit
        • v2
          • Installation
          • React
            • Installation
            • Usage
          • Vanilla JS
            • Installation
            • Usage
          • Core
            • Installation
            • Usage
          • Theme Variables
          • i18n
        • v1
          • Installation
          • React
            • Installation
            • Usage
          • Vanilla JS
            • Installation
            • Usage
          • Core
            • Installation
            • Usage
          • Theme Variables
          • i18n
          • Node Polyfills
          • V0 to V1
        • v0
          • Installation
          • Usage
          • React
            • Installation
            • Usage
          • Vanilla (UI)
            • Installation
            • Usage
          • Styles (UI)
          • i18n
      • DevPal
      • Web3-Providers-Connex
        • Installation
        • Usage
      • Connex
        • Installation
        • API Specification
    • Frameworks & IDEs
      • Hardhat
      • Remix
    • Built-in Contracts
    • VORJ
    • Useful Links
  • How to contribute
Powered by GitBook
On this page
  • Example Data
  • Connection
  • Filter Specific Events
  • Event Parameters
  • Blockchain Parameters
  • Decoding Events
  • Example Project

Was this helpful?

  1. Developer Resources
  2. How to build on VeChain
  3. Listen to Changes

Events

PreviousListen to ChangesNextVET Transfers

Last updated 2 months ago

Was this helpful?

Example Data

This example used below will utilize the VTHO contract, which manages VeChain's VTHO Token.

  • Smart Contract Address: 0x0000000000000000000000000000456e65726779

  • The contract's source code can be found on GitHub at:

  • Its Application Binary Interface (ABI) is shared on b32, a repository that gathers publicly available interfaces for VeChain projects:

Connection

The connection is managed using WebSockets, which connect directly to a VeChain node.

A simple connection can be established with this snippet:

import WebSocket from 'ws';
const ws = new WebSocket('wss://mainnet.vechain.org/subscriptions/event');
ws.onmessage = (message) => {
    console.log('New event', message.data);
}

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

Filter Specific Events

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)"
);

Event Parameters

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

The transfer event uses two indexed parameters: from and to.

For instance, to filter all transfers originating from a specific address, you would supply that address as the first parameter:

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

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

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

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

Blockchain Parameters

Emitter

Many contracts emit similar events, which sometimes necessitates restricting listening to a specific contract. An optional options 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',
  "event Transfer(address indexed from, address indexed to, uint256 value)",
  [],
  { 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.

Decoding Events

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:

import WebSocket from "ws";
import { ABIContract } from "@vechain/sdk-core";
import { subscriptions } from "@vechain/sdk-network";

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

ws.onmessage = (message) => {
    console.log(message.data);
  const eventData = JSON.parse(message.data as any);

  // Ensure topics is an array of strings
  const topics = Array.isArray(eventData.topics)
    ? eventData.topics.map(String)
    : [String(eventData.topics)];

  // Ensure data is a single hex string
  const data = Array.isArray(eventData.data)
    ? eventData.data.map(String).join("")
    : String(eventData.data) || "0x";

  const abiContract = new ABIContract([
    {
      type: "event",
      name: "Transfer",
      inputs: [
        { type: "address", name: "from", indexed: true },
        { type: "address", name: "to", indexed: true },
        { type: "uint256", name: "value", indexed: false },
      ],
    },
  ]);

  const decoded = abiContract.parseLog<"Transfer">(data, topics);

  if (!decoded || decoded.eventName !== "Transfer") {
    throw new Error("Transfer event not detected");
  }
};

Example Project

For additional details on the options, check out the documentation of .

Generic transaction details such as ID, block information, or the origin of the transaction are available in the object as well. Check eventLog.meta from the example. Learn more about the message type definition in the documentation of .

https://github.com/vechain/thor/blob/f58c17ae50f1ec8698d9daf6e05076d17dcafeaf/builtin/gen/energy.sol
https://github.com/vechain/b32/blob/master/ABIs/energy.json
EventSubscriptionOptions
EventLogs
Vechain-energy - Example Snippets - StackBlitzStackBlitz
Logo