Infura currently doesn't support WebSockets (required for events using Web3 v1, otherwise you get the error "The current provider doesn't support subscriptions" when using infura as HttpProvider), so what you have to do is run a local geth node that connects and syncs to the network.
Here we enable the websocket flag and allow any origin to connect to the local geth node that is syncing with the rinkeby testnet:
geth --rinkeby --ws --wsport=8546 --wsorigins="*" --datadir=$HOME/.rinkeby --cache=512 --rpc --rpcapi="personal,eth,network" --rpcport=8545 --fast --bootnodes=enode://a24ac7c5484ef4ed0c5eb2d36620ba4e4aa13b8c84684e1b4aab0cebea2ae45cb4d375b77eab56516d34bfbd3c1a833fc51296ff084b770b94fb9028c4d25ccf@52.169.42.101:30303
To check the syncing status:
geth attach ipc:$HOME/.rinkeby/geth.ipc
> eth.syncing
Once it's done syncing you can connect using the WebsocketProvider
:
const web3 = new Web3(new Web3.providers.WebsocketProvider('ws://localhost:8546'))
You should now be able to receive events:
myContract.events.allEvents((error, event) => {
if (error) {
console.error(error)
return false
}
console.log(event)
})
Tested this with geth v1.6.5
and web3 v1.0.0
.
Update Oct 11, 2017:
Infura is experimenting with websocket support. You can ask for beta access in this github issue thread:
https://github.com/INFURA/infura/issues/29
Best Answer
To use the
web3
object, you need to specify where and how to connect to an ethereum node.'where' can be localhost or an external provider such as infura.io or etherscan.io
'how' can be http or websocket, etc.
Once you have set this value e.g.
var web3 = new Web3(new Web3.providers.WebsocketProvider("ws://localhost:7545"))
then theweb3
object will know which protocol to use and which hostname to contact to get the block data for the blockchain or where to send transaction calls to.