Listening For Smart Contract Events on Public Blockchains

Subscribing to events on public chains is not the same as on a local chain

Alex Roan
BlockCentric

--

Image by Pixabay

Prerequisite: A good understanding of Ethereum Smart Contracts, Events, Javascript, Web3 and state management tools like Redux or equivalent. If you don’t know how to subscribe to Smart Contract events, read this previous article.

I previously wrote an article on listening to contract events in your DApp using web3JS. This works great on local Blockchains like Ganache, but if you deploy to a public testnet you’ll notice that your subscriptions aren’t firing.

But Why?

HTTP is the most common protocol to interact with Infura nodes. Unfortunately, pushing events through HTTP is not supported. While this may work locally using a development blockchain like Ganache, events will never fire on a public blockchain so long as the connection you’re listening on is HTTP.

Fortunately, Infura offers alternatives.

Websockets, in contrast to HTTP, will fire events to your DApp. So, all you’d need to do to fix this subscription problem is to change your current web3 provider to use a WebSocket URL instead, right?

So, instead of:

// using the provider given…

--

--

Alex Roan
BlockCentric

CoFounder at Cyfrin. Previously: Chainlink Labs.