I'm finding a way to subscribe the specific event in the Smart Contract and there is a web3.eth.subscribe to subscribe an event.

[Web3.js 1.0.0]

The web3.eth.subscribe function lets you subscribe to specific events in the blockchain.

>> web3.eth.subscribe(type [, options] [, callback]);

var subscription = web3.eth.subscribe('logs', {
    address: '0x123456..',
    topics: ['0x12345...']
}, function(error, result){
    if (!error)

// unsubscribes the subscription
subscription.unsubscribe(function(error, success){
        console.log('Successfully unsubscribed!');

I want to make a script which will be running on the server and then, get the result back after noticing the event occur while the script is listening. For instance, now I have to ask consistently the state of variable to the smart contract using myContractInstacne.methods.MyMethods.call() using setInterval() in the script but what I want to do in this situation is just keep listening and get the result only the moment when the event was occuring.

Do you guys have an idea with this? Is it impossible to implement this?

1 Answer 1


Yes, it's possible. But web3.eth.subscribe works only with WebsocketProvider (or local IpcProvider). You need to do like this:

const Web3 = require('web3');
let web3Provider = new Web3.providers.WebsocketProvider("wss://ropsten.infura.io/ws");
var web3Obj = new Web3(web3Provider);
var subscription = web3Obj.eth.subscribe('logs', {
    address: '0x123456..', //Smart contract address
    topics: ['0x12345...'] //topics for events
}, function(error, result){
    if (error) console.log(error);
}).on("data", function(trxData){
  console.log("Event received", trxData);
  //Code from here would be run immediately when event appeared

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.