Search code examples
websocketweb3jsrsk

How to subscribe to `newBlockHeaders` on local RSK node over websockets?


I'm connecting to RSKj using the following endpoint:

ws://localhost:4444/

... However, I am unable to connect.

Note that the equivalent HTTP endpoint http://localhost:4444/ work for me, so I know that my RSKj node is running properly.

I need to listen for newBlockHeaders, so I prefer to use WebSockets (instead of HTTP).

How can I do this?


Solution

  • RSKj by default uses 4444 as the port for the HTTP transport; and 4445 as the port for the Websockets transport. Also note that the websockets endpoint is not at /, but rather at websocket. Therefore use ws://localhost:4445/websocket as your endpoint.

    If you're using web3.js, you can create a web3 instance that connects over Websockets using the following:

    const Web3 = require('web3');
    const wsEndpoint = 'ws://localhost:4445/websocket';
    const wsProvider =
      new Web3.providers.WebsocketProvider(wsEndpoint);
    const web3 = new Web3(wsProvider);
    
    

    The second part of your question can be done using eth_subscribe on newBlockHeaders. Using the web3 instance from above like so:

    // eth_subscribe newBlockHeaders
    web3.eth.subscribe('newBlockHeaders', function(error, blockHeader) {
      if (!error) {
        // TODO something with blockHeader
      } else {
        // TODO something with error
      }
    });