Stock Markets
Daily Stock Markets News

Create an API to interact with Ethereum Blockchain using Golang PART 1


Author profile picture

Hi folks! In this tutorial, we are going to learn how to create a simple REST API to interact with the Ethereum blockchain using Golang

Web3.js is the de-facto library to interact for interacting with Ethereum in JavaScript and Node.js. It takes care of encoding payloads and generating the RPC calls. Web3.js is very popular and heavily documented.

On the other hand, (geth), the most popular Ethereum implementation, is written in Go. It’s a complete Ethereum node. If you build a dApp in Go, then you’ll be using the go-ethereum libraries directly which means you can do everything the node can do.

So, for this tutorial, I chose to use Go as our weapon.

In simple terms, interacting with the blockchain means that you will be making RPC calls over HTTP. Any language will be able to do that for you but, using a compiled language such as Go will give you a better performance… If performance is important to you or your team.

Enough of boring introduction!

For our tutorial, we are going to set up four endpoints:

Get the latest blockGet transaction by hashGet address balanceTransfer ether to an address

This is not a big deal, but I think is cool as a starting point to more complex implementations.

If you want to get the whole code you can download it here.

SET UP

I used go 1.13.8 for this tutorial, to get your Go version just run:

$ go version
# outputs
go version go1.13.8 darwin/amd64

First we are going to create our project by running the following command:

That will create at the root of your working directory the file

go.mod

with the following content:

module github.com/LuisAcerv/goeth-api

go 1.13

Now let’s create our project structure. I have to say here that you can use the structure that better fits your needs.

At the root of your project create a new

main.go

file.

$ echo "package main"  main.go

Now we need to create three directories:

$ mkdir handler
$ mkdir models
$ mkdir modules

And inside each of those folders we are going to create a

main.go

file, and we should have the following structure:

.
├── handler
│   └── main.go
├── models
│   └── main.go
├── modules
│   └── main.go
├── go.mod
├── go.sum
├── main.go

Ganache-CLI

In order to interact with the Ethereum blockchain, we need a provider, a provider is a node we have access to make RPC calls over HTTP. You can use a testnet such as ropsten or kovan through a provider such as Infura, but for this tutorial, we are going to set up a local virtual node using ganache.

At the official truffle website you can download ganache, is pretty easy to set up and will give you all you need for testing proposes. It comes with a nice UI which will show you the transactions, accounts and logs of your “node”.

Once you have ganache installed and running we are good to start writing some code.

We have a

./models/main.go

file. This file contains the structures we are going to use in our API.

We add the following content:

package models

// Block data structure
type Block struct {
	BlockNumber       int64         `json:"blockNumber"`
	Timestamp         uint64        `json:"timestamp"`
	Difficulty        uint64        `json:"difficulty"`
	Hash              string        `json:"hash"`
	TransactionsCount int           `json:"transactionsCount"`
	Transactions      []Transaction `json:"transactions"`
}

// Transaction data structure
type Transaction struct {
	Hash     string `json:"hash"`
	Value    string `json:"value"`
	Gas      uint64 `json:"gas"`
	GasPrice uint64 `json:"gasPrice"`
	Nonce    uint64 `json:"nonce"`
	To       string `json:"to"`
	Pending  bool   `json:"pending"`
}

// TransferEthRequest data structure
type TransferEthRequest struct {
	PrivKey string `json:"privKey"`
	To      string `json:"to"`
	Amount  int64  `json:"amount"`
}

// HashResponse data structure
type HashResponse struct {
	Hash string `json:"hash"`
}

// BalanceResponse data structure
type BalanceResponse struct {
	Address string `json:"address"`
	Balance string `json:"balance"`
	Symbol  string `json:"symbol"`
	Units   string `json:"units"`
}

// Error data structure
type Error struct {
	Code    uint64 `json:"code"`
	Message string `json:"message"`
}

Now that we have our models defined and ready to be used, we are going to create the methods in charge of interacting with the blockchain.

First of all we want to install the

go-ethereum

module, and we can do that by running the following command:

$ go get -u github.com/ethereum/go-ethereum

In our

./modules/main.go

we are going to create a function that retrieves the latest block from the blockchain.

This function is going to give us the information about the block and the transactions embedded in it.

func GetLatestBlock(client ethclient.Client) *Models.Block {
	// We add a recover function from panics to prevent our API...



Read More: Create an API to interact with Ethereum Blockchain using Golang PART 1

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for subscribing.

Something went wrong.