Websocket contract events will disconnect if about 1hr no callback event found

This my code:

const erc20 = require('../lib/erc20abi');
const Web3 = require('web3');
const provider = new Web3.providers.WebsocketProvider(`${process.env.WSS}${process.env.API_KEY}`);
provider.on("connect",function(){console.log("connected ws")});
provider.on("error",function(err){console.log("provider err",err)});
provider.on("end",function(err){console.log("provider end")});
const web3 = new Web3(provider);
const contract = new web3.eth.Contract(erc20,'0xAb355D1ce2ED0105A831c12b911323CE301c922C');
contract.events.Transfer({filter: {to: "0x40C034E80fD6721ACA6285fbc85bca0fd595104E"}},function(err,result){
    if (err) console.log("event error",err);
    console.log('result');
})
.on("data",async (event)=>{
    console.log('new event');
})
.on("error",function(err){
    console.log("event error",err);
})

My contract event will disconnect about after 1hr but no callback disconnected event? How can I catch disconnected event and start my contract events subscribe again?

If you add pings that will allow you to monitor the health of the websocket connection. We will be releasing an update very soon that will improve the functionality of log/event subscriptions via websockets. In the meantime, the ping should fix this as well.

Sorry, but this stupid quest. How can I add ping/pong in this code?

Not sure specifically within Web3 library, I would recommend reaching out to that community

1 Like

Do you have example for any lib ping/pong method?

same code as:

ws.send('ping')

Is true?
Or this code:

ws.ping()

and catch pong with:

ws.on('pong',function(){
  //do something
})

Or just ping and no catch pong.

I edit my code:

const WebSocket = require('ws');
const ws = new WebSocket('wss://rinkeby.infura.io/ws/v3/key');
ws.on('open',function open(){
    ping(60*1000);
    ws.send(JSON.stringify({"jsonrpc":"2.0", "id": 1, "method": "eth_subscribe", "params": ["logs", {"address": "0xAb355D1ce2ED0105A831c12b911323CE301c922C", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",null,"0x00000000000000000000000040c034e80fd6721aca6285fbc85bca0fd595104e"]}]}));
});
ws.on('message',function incomming(data){
    console.log(data);
});
ws.on('pong',function(data){
    console.log('pong',data.toString());
})
ws.on('close',function(data){
    console.log('--- close ---');
})
function ping(timeout){
    setTimeout(()=>{
        ws.ping('Heartbeat');
        ping(timeout)
    },timeout)
}

But this event no callback about after 1hr. I added ping ws. My code is problem?

In golang, it’s send(ping) instead of send(message), if the connection is healthy you should receive no errors.

You could also try subscribing to newHeads as well and throw those responses away that should also keep the connection alive.