>

>

2. Reactive Applications with WebSockets

Listening in Real-Time

Reading the past is great, but reacting to the present is better! 🚀

For things like live payment notifications, you don't want to keep "refreshing" the chain. Instead, you listen.

VeChain offers a native WebSocket system for real-time subscriptions. "Think of a WebSocket like..." a phone line that stays open so the blockchain can call you the moment something happens.

You can subscribe to all VET transfers on the network with just a few lines of code:

import WebSocket from 'ws';
const ws = new WebSocket('wss://testnet.vechain.org/subscriptions/transfer');

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

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

ws.onmessage = (message) => {
  console.log('New activity:', message.data);
};

You're getting it! But what if you only care about your users?

The SDK has a helper to filter the stream by recipient or signerAddress. This way, your app only reacts to the transfers that matter to you. Nice!


Common Pitfalls to Avoid: Always verify that a transaction wasn't reverted before trusting the events in the receipt! Also, remember to decode the amount using BigInt because it has 18 decimals.