Skip to main content

Connect to Ganache using Golang

Previous Topic: Ganache Overview

Connect to Ganache:

We are going use the go-ethereum - ethclient package to make a connection with the ganache server using Golang.
 go get github.com/ethereum/go-ethereum/ethclient
In the below example, we are just simply connecting with ganache server and retrieve the chain Id value from the server.
 package main
 import (
	"context"
	"fmt"
	"log"

	"github.com/ethereum/go-ethereum/ethclient"
 )

 func main() {

	client, err := ethclient.Dial("http://127.0.0.1:7545")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Connection with ganache successful")

	chainId, err := client.ChainID(context.Background())
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Chain Id :", chainId)
 }

Output:

Connection with ganache successful
Chain Id : 1337

Retrieving Balance for the accounts:

 go get github.com/ethereum/go-ethereum/common
In the below example, we are going to retrieve the balance of address.
 package main

 import (
	"context"
	"fmt"
	"log"
	"math/big"

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/ethclient"
 )

 func main() {

	client, err := ethclient.Dial("http://127.0.0.1:7545")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Connection with ganache successful")

	blockNumber, err := client.BlockNumber(context.Background())
	if err != nil {
		log.Fatal(err)
	}

	address := common.HexToAddress("0xA3A0634b58CB4f800f4f4c1f61ba8d0f361a29Cf")
	accountBalance, err := client.BalanceAt(context.Background(), address, big.NewInt(int64(blockNumber)))
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Account - "+address.String()+" Balance:", accountBalance)
 }

Output:

Connection with ganache successful
Account - 0xA3A0634b58CB4f800f4f4c1f61ba8d0f361a29Cf Balance: 100000000000000000000


Comments