Intro to Web3.go Part 3: Events

Marius Van Der Wijden
2 min readJul 8, 2020

--

How to use go-ethereum as a library

Many developers have asked me how they can use their favorite programming language, Go, to access the Ethereum network(s). This article is part of a series that should explain the little known ability to use go-ethereum as a library to access Ethereum. You can find part 1 of this series here, and part 2 here.

In this part of the tutorial, we’ll discuss how to filter and watch for events. We will be using our CoolContract.sol from part 2 for this. Also we are reusingctx (context.Context) and ctr (*coolcontract.CoolContract)from the last article.

Watching Events vs Filtering for Events

Solidity has the ability to emit events which notify the user of important state changes. We have two different concepts in go-ethereum: filtering for events and listening for events. Filtering means we set up a filter function that filters the old state and looks for events that match our filter. Filtering only works on archive nodes (or full nodes that don’t properly prune events). It does not work on infura. Watching works on all types of nodes.

The abigen tool automatically generates a Watch<EventName> and a Filter<EventName> function for every event we define in our solidity code.
For filtering we need to create a bind.FilterOpts object which takes a start and end argument to define which blocks we want to filter for events. Please use a sensible range so you are not choking your node with filtering operations.

Filter for a Deposited event

This is all pretty cool, but what if we don’t care about historical events but want to be notified of new events from our contract? For this, we can use the Watch<EventName> function.

Watch for new Deposited events

Tip: If you want both historical events and new events, create your subscription goroutine before your filter old states and wait for a bit so you’re certain it gets scheduled, otherwise you might loose events.

You can also parse a event from a types.Log which might be useful in some scenarios:

Parse a log into a Deposited event

Do we really need to setup a new node for all our tests? What if we want to run blockchain tests in our CI-pipeline? What if we want to rollback our blockchain after some tests? We will discuss these questions in part 4 of this ongoing series!

If you want to get in touch, just message me at @vdWijden on twitter or Linkedin.

Part1: Connecting and sending transactions
Part2: Calling functions on smart contracts
Part3: Listening on events from smart contracts
Part4: Creating a mock-blockchain for testing

Special thanks to Rene for proof-reading!

--

--

Marius Van Der Wijden

Ethereum Developer, State Channel Researcher, Student at TU Darmstadt