5

I'm trying to connect to Solana mainnet using websockets. I can't find out how to connect using web3.js. Maybe someone faced this issue and can help me ?

Thanks

Here's a simple line of code I made:

let con = new web3.Connection('https://api.mainnet-beta.solana.com', { commitment: "confirmed", wsEndpoint: 'ws://api.mainnet-beta.solana.com' });
mercvry.eth
  • 89
  • 1
  • 6

2 Answers2

3

Check out this example for subscribing to websockets using web3 on the Solana Cookbook: https://solanacookbook.com/references/local-development.html#subscribing-to-websocket

Jon C
  • 7,019
  • 10
  • 17
2
function monitor() {
    ws = new WebSocket(WSS_ENDPOINT)
    ws.onopen = () => {
        ws.send(
            JSON.stringify({
                jsonrpc: '2.0',
                id: 1,
                method: 'programSubscribe',
                params: [
                    address,
                    {
                        encoding: 'base64',
                        commitment: 'finalized',
                    },
                ],
            })
        )
    }

the endpoint you want to use goes in that method entry.

now each time you want to react to something... you use

 ws.on('message', (evt) => {
        try {
            const buffer = evt.toString('utf8')

            console.log(buffer)
        } catch (e) {
            console.log(e)
        }
    })
}
josh hoffer
  • 126
  • 1
  • 7