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.
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);
});