How to send ERC-20 tokens using Go
In this support guide we're going to learn how to send ERC-20 tokens using Go and the go-ethereum packages. As usual, if you only need the script's code, feel free to scroll down to the end of the article.
Prerequisites
For this tutorial to work, you will need:
- Go installed on your system
- The go-ethereumpackages (they will be automatically installed when you run the code)
- dotenv(optional, but recommended for better security)
Setting up our project
Let's start by importing the required libraries and creating our .env file, which will contain our account's private key (you can use a test wallet without any real funds on it) and the Infura project ID.
If you need a little more help on creating a .env file, you can check out this repository.
For this tutorial's purposes you don't have to use environmental variables, but it's a good practice to use them so that sensitive information is not easily accessible within the code.
package main
import (
	"context"
	"fmt"
	"log"
	"math/big"
	"os"
	"github.com/ethereum/go-ethereum/accounts/abi/bind"
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/ethclient"
)
func main() {
	// Connect to an Ethereum node using Infura
	client, err := ethclient.Dial(fmt.Sprintf("https://goerli.infura.io/v3/%s", os.Getenv("INFURA_API_KEY")))
	if err != nil {
		log.Fatal(err)
	}