2

Trying to connect to a geth machine over websocket? JS code.

var Web3=require('web3');
var web3 = new Web3(new 
Web3.providers.WebsocketProvider('ws://10.244.5.43:8546'));
console.log(web3.isConnected());

Not sure how to connect using WebSocket?

2

I had the same issue with web3 v1.0.0 beta 30. Never got to the bottom of it but skipping the provider construction appeared to fix it:

var Web3=require('web3');
var web3 = new Web3('ws://10.244.5.43:8546');
1

I assume that you're using a version of Web3.js older than 1.0. I believe that the WebsocketProvider was added in 1.0.

1
  • Same issue with 1.3.4 (via TypeScript but I doubt it changed something)
    – Matt
    Mar 30 at 17:28
0

So in my particular case, I'm using TypeScript and it appears the typings were misleading. The package web3-providers-ws says that the following import should be valid:

import { WebsocketProvider } from "web3-providers-ws"

const provider = new WebsocketProvider("<host>", { ... })

It seems the typings lies a bit (or at least, there is something else that prevent it to work as expected).

I had to do the following to overcome the problem:

import WebsocketProvider from "web3-providers-ws"

// @ts-ignore It appears default export is required otherwise it throws 'WebsocketProvider is not a constructor error', the typings says otherwise but well ...
const provider = new WebsocketProvider("<host>", { ... })

I tried to play with various tsconfig.json options around module and default imports, but did not succeed. Not sure what is not working yet, but at least I have a workaround.

Hopefully it helps someone else.

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.