Introduction
A smart contract emits an event on interaction.
You can use web3.js and the WebSocket connection to subscribe to events and receive them in real time.
This tutorial will guide you through subscribing to a smart contract event.
As an example, you will use the Transfer event of Chainlink.
See also:
- Chainstack interactive API reference that has subscription examples
- Handle real-time data using WebSocket with JavaScript and Python
Step-by-step
Get the address of the smart contract whose events you want to listen to. For example, Chainlink.
Each event type emitted by a smart contract is identified as an event signature. An event signature is Keccak-256 hashed as topic[0].
Each smart contract interaction has topic[0] identifying the type of event that occurred on the interaction.
To get the topic[0] hash of an event signature:
- You can get the event signature and use an online converter. For example, the most common event type is Transfer. The event signature is Transfer(address,address,uint256). The event signature converts to the topic[0] value: 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef
- An easier way is to find your contract on Etherscan and check the contract's Events tab. All topic[0] values represent events. For example, Chainlink events.
Now that you have both the contract address and the hashed value of the event you want to subscribe to, create and run a Node.js instance:
const Web3 = require('web3');
const url = 'WSS_ENDPOINT';
const web3 = new Web3(url);
var options = {
address: 'CONTRACT',
topics: [
'TOPIC0'
]
};
var subscription = web3.eth.subscribe('logs', options, function(error, result){
if (!error) console.log('got result');
else console.log(error);
}).on("data", function(log){
console.log('got data', log);
}).on("changed", function(log){
console.log('changed');
});
where
- WSS_ENDPOINT — your node WSS endpoint.
- CONTRACT — the address of the contract whose events you subscribe to.
- TOPIC0 — the Keccak-256 value of the event.
For example, subscribing to the Transfer event of the Chainlink smart contract:
const Web3 = require('web3');
const url = 'wss://ws-nd-123-456-789.p2pify.com/3c6e0b8a9c15224a8228b9a98ca1531';
const web3 = new Web3(url);
var options = {
address: '0x514910771af9ca656af840dff83e8264ecf986ca',
topics: [
'0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'
]
};
var subscription = web3.eth.subscribe('logs', options, function(error, result){
if (!error) console.log('got result');
else console.log(error);
}).on("data", function(log){
console.log('got data', log);
}).on("changed", function(log){
console.log('changed');
});
You are now subscribed to the events and will receive them in real time as they are emitted.
You can also add the reconnect option to make sure you are always connected. See also web3.js reconnect documentation.
const Web3 = require('web3');
const url = 'wss://ws-nd-123-456-789.p2pify.com/3c6e0b8a9c15224a8228b9a98ca1531';
const web3 = new Web3(url);
var options = {
reconnect: {
auto: true,
delay: 5000, // ms
maxAttempts: 5,
onTimeout: false
},
address: '0x514910771af9ca656af840dff83e8264ecf986ca',
topics: [
'0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'
]
};
var subscription = web3.eth.subscribe('logs', options, function(error, result){
if (!error) console.log('got result');
else console.log(error);
}).on("data", function(log){
console.log('got data', log);
}).on("changed", function(log){
console.log('changed');
});
Subscribing to multiple addresses/events
In addition to subscribing to a single smart contract event, you may find the need to subscribe to events from multiple addresses or different types of events. This can be useful in scenarios where you are tracking various tokens or interacting with multiple contracts within your dApp. Below is an example demonstrating how to set up multiple subscriptions using web3.js, allowing you to efficiently manage and listen to events from different sources simultaneously.
const Web3 = require('web3');
const url = 'wss://ws-nd-123-456-789.p2pify.com/3c6e0b8a9c15224a8228b9a98ca1531';
const web3 = new Web3(url);
var options1 = {
address: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
topics: [
'0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925'
]
};
var options2 = {
address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
topics: [
'0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'
]
};
function subscribeToLogs(options) {
var subscription = web3.eth.subscribe('logs', options, function(error, result) {
if (!error) console.log('Subscription created');
else console.log(error);
})
.on("data", function(log) {
console.log('Log data:', log);
})
.on("changed", function(log) {
console.log('Log changed');
})
.on("error", function(error) {
console.error('Error:', error);
});
return subscription;
}
// Subscribing to different addresses and events
subscribeToLogs(options1);
subscribeToLogs(options2);
If you have any questions, feel free to contact Chainstack support by emailing support@chainstack.com or by submitting this form.
Comments
0 comments
Article is closed for comments.