I want to subscribe and listen to events that involve funds moving to my wallet, however I for some reason am not able to establish a socket connection to an Infura node.

First I npm init and npm web3.

The code:

const Web3 = require('web3');

class TransactionChecker {

    constructor(projectId, account) {
        web3ws = new Web3.providers.WebsocketProvider('wss://kovan.infura.io/ws/v3/' + projectId);
        web3 = new Web3.providers.HttpProvider('https://kovan.infura.io/v3/' + projectId);
        account = account.toLowerCase();

    subscribe(topic) {
        this.subscription = web3ws.eth.subscribe(topic, (err, res) => {
            if (err) console.error(err);

    watchTransactions() {
        console.log('Watching all pending transactions...');
        this.subscription.on('data', (txHash) => {
            setTimeout(async () => {
                try {
                    let tx = await this.web3.eth.getTransaction(txHash);
                    if (tx != null) {
                        if (this.account == tx.to.toLowerCase()) {
                            console.log({address: tx.from, value: this.web3.utils.fromWei(tx.value, 'ether'), timestamp: new Date()});
                } catch (err) {
            }, 60000)

let txChecker = new TransactionChecker('projectId', 'address');

Gives me the following err: 'failed to create stateful backend, closing connection: websocket: bad handshake'

URLs are all good, why the error?

  • What are the settings of your project at Infura.io (whitelisting, etc.) Feb 28, 2021 at 0:55

1 Answer 1


It is creating a provider instance, it also needs creating a Web3 with the provider. It can combine the two steps like this

web3 = new Web3('wss://kovan.infura.io/ws/v3/' + projectId)

It is doing something like

web3provider = new Web3.providers.WebsocketProvider('wss://kovan.infura.io/ws/v3/' + projectId)
web3 = new Web3(web3provider)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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