Home > Net >  How to connect binance network in nodejs using web3
How to connect binance network in nodejs using web3

Time:02-05

I tried to connect with binance testnet in Nodejs. This is my code.

const Web3 = require('web3');
const web3 = new Web3(new Web3.providers.HttpProvider('https://data-seed-prebsc-1-s2.binance.org:8545'));

But I got the error code like

Error: The current provider doesn't support subscriptions: HttpProvider
    at Timeout._onTimeout (E:\test\share1\node_modules\web3-core-subscriptions\lib\subscription.js:176:24)

Please let me know how I can fix it.

CodePudding user response:

HTTP provider, does not support subscriptions.

Source: https://web3js.readthedocs.io/en/v1.7.0/web3.html#value


If you want to use subscriptions, you need to connect to a websocket node - not HTTP.

There is a list of 3rd party node providers recommended by Binance in their docs page. Some of them support websocket connection as well.

Example connecting to a WSS node provider:

const Web3 = require('web3');
const web3 = new Web3(
    new Web3.providers.WebsocketProvider(
        'wss://speedy-nodes-nyc.moralis.io/<your_key>/bsc/mainnet/ws'
    )
);

web3.eth.subscribe('newBlockHeaders', (err, newBlock) => {
    console.log(newBlock.number);
});

CodePudding user response:

The above web3 part works fine. Please try the below lines,

var Web3 = require('web3');
const web3_bsc = new Web3('https://data-seed-prebsc-1-s2.binance.org:8545');

Then using the web3_bsc, access the functions in your contract or perform any functions that web3 supports.

  •  Tags:  
  • Related