Intro to Web3.go Part 2: abigen

Marius Van Der Wijden
2 min readJul 7, 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.

In part 2 of this series we’ll discuss how to interact with smart contracts.

Smart Contract Bindings: abigen and the bind package.

A full installation of geth includes a binary to create golang bindings to solidity smart contracts called abigen
If you haven’t installed geth yet, take a look here: https://geth.ethereum.org/docs/install-and-build/installing-geth
You can also make it by going to go-ethereum/cmd/abigen and running go build to create the abigen binary.

During this example, I’ll be using the following smart contract saved under CoolContract.sol:

The smart contract we’ll use in this tutorial

You can create go-bindings for the smart contract by running:

Create contract bindings with abigen

This will create a file CoolContract.go which can be imported in your Go project. It has a lot of useful methods to deploy and interact with the contract. You can also use it to connect to an already deployed contract. For all interaction we need an Object that implements the ContractBackend interface. Luckily the ethclient.Client Object from the previous part already implements the needed interface, so we can connect to an already deployed contract like this:

Bind to an already deployed contract

You can also deploy a new contract as follows (we already learned how to create TransactOpts in the last part). If your contract has a constructor with arguments, you have to specify them in your call to Deploy<ContractName> .

Deploy a new contract

Now that we have our contract instance, we can start sending some transactions. There is a difference between view/pure and normal functions. Pure and view functions can be calculated by the node itself without having to contact the network. This means we don’t need funds to call them.

Call a function of the smart contract

But what about the emitted event in Deposit ? This will be the topic of the next part!

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

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

--

--

Marius Van Der Wijden

Ethereum Developer, State Channel Researcher, Student at TU Darmstadt