[Ethereum] How to connect with WebSocket with Web3

eventsinfuraweb3jswebsocket

Already referred web3 documentations and other Q-A for web socket connection. Currently using infura as provider.

Best Answer

I think this is what you are looking for:

const Web3 = require('web3');
const web3 = new Web3('wss://ropsten.infura.io/ws/v3/<yourID>');

const abi = "placeYourABI";

const address = 'yourContractAddress';

const contract = new web3.eth.Contract(abi, address);

contract.getPastEvents('allEvents', {
    fromBlock: 0,
    toBlock: 'latest'
}).then(function(events){
    console.log(events);
});

Replace the variables. Take note of the URL. Websocket URL is not only different by wss at the front.

This code is tested and surely works.

EDIT: Please write why you downvote this answer! It is completely correct.

Related Topic