Interacting with ERC20 tokens is a fundamental skill in Ethereum development. Whether you're building a wallet, decentralized exchange, or blockchain analytics tool, the ability to read token data from smart contracts using code is essential. This guide walks you through how to query an ERC20 token smart contract using Go (Golang), one of the most efficient and widely used languages in blockchain infrastructure.
By the end of this tutorial, you'll be able to connect to any ERC20 token on the Ethereum network, retrieve balance information, and interpret token metadata such as name, symbol, and decimal precision—all programmatically.
Understanding the ERC20 Interface
The ERC20 standard defines a set of functions and events that all compliant tokens must implement. To interact with these tokens in Go, we first define a Solidity interface that mirrors the standard:
pragma solidity ^0.4.24;
contract ERC20 {
string public constant name = "";
string public constant symbol = "";
uint8 public constant decimals = 0;
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}This interface does not contain implementation logic—it only specifies what methods are available for external calls.
👉 Learn how to integrate blockchain data into your applications seamlessly.
Compiling the ABI and Generating Go Bindings
Once the interface is defined (erc20.sol), compile it to generate the JSON ABI:
solc --abi erc20.solThis outputs erc20_sol_ERC20.abi, which describes the contract’s structure in machine-readable format. Next, use abigen—a tool from the Go Ethereum library—to generate a native Go package:
abigen --abi=erc20_sol_ERC20.abi --pkg=token --out=erc20.goThis creates erc20.go, a type-safe Go wrapper that allows you to call Ethereum smart contract functions as if they were regular Go methods.
Connecting to the Ethereum Network
Before querying token data, establish a connection to an Ethereum node. You can use a public endpoint like Cloudflare’s Ethereum gateway:
client, err := ethclient.Dial("https://cloudflare-eth.com")
if err != nil {
log.Fatal(err)
}This lightweight setup avoids running your own node while still allowing full read access to the blockchain.
Now import the generated token package and instantiate the contract using a known ERC20 address. In this example, we use Golem Network Token (GNT):
tokenAddress := common.HexToAddress("0xa74476443119A942dE498590Fe1f2454d7D4aC0d")
instance, err := token.NewToken(tokenAddress, client)
if err != nil {
log.Fatal(err)
}You now have a fully functional Go object representing the GNT token contract.
Reading Token Balances and Metadata
With the contract instance ready, you can query user balances:
address := common.HexToAddress("0x0536806df512d6cdde913cf95c9886f65b1d3462")
bal, err := instance.BalanceOf(&bind.CallOpts{}, address)
if err != nil {
log.Fatal(err)
}
fmt.Printf("wei: %s\n", bal) // Raw balance in smallest unitERC20 tokens often store values in "wei"-like units—integers with no decimal point. The actual human-readable value depends on the token’s decimals field.
Read other critical metadata:
name, err := instance.Name(&bind.CallOpts{})
if err != nil {
log.Fatal(err)
}
symbol, err := instance.Symbol(&bind.CallOpts{})
if err != nil {
log.Fatal(err)
}
decimals, err := instance.Decimals(&bind.CallOpts{})
if err != nil {
log.Fatal(err)
}
fmt.Printf("name: %s\n", name) // "Golem Network"
fmt.Printf("symbol: %s\n", symbol) // "GNT"
fmt.Printf("decimals: %v\n", decimals) // Usually 18These fields are crucial for correctly formatting balances and displaying token information in user interfaces.
Converting Raw Balances to Human-Readable Format
Since blockchain stores values as integers, converting them requires dividing by 10^decimals. Use Go’s big.Float for precision:
fbal := new(big.Float)
fbal.SetString(bal.String())
value := new(big.Float).Quo(fbal, big.NewFloat(math.Pow10(int(decimals))))
fmt.Printf("balance: %f", value) // "balance: 74605500.647409"This step ensures accurate representation without floating-point errors—especially important for financial applications.
👉 Discover powerful tools for real-time blockchain interaction.
Core Keywords for SEO
- ERC20 token
- Go Ethereum
- Smart contract query
- Golang blockchain development
- Read ERC20 balance
- abigen tool
- Ethereum client
- Token metadata
These keywords reflect high-intent search queries from developers looking to build or debug Ethereum-based applications using Go.
Frequently Asked Questions
How do I find the ABI of any ERC20 token?
Most ERC20 tokens follow the standard interface, so you can reuse the same minimal ABI shown above. For custom implementations, retrieve the full ABI from explorers like Etherscan under the "Contract" tab.
Can I interact with other ERC standards the same way?
Yes. The same pattern applies to ERC721 (NFTs), ERC1155, and others. Define the correct Solidity interface, generate Go bindings via abigen, and connect using ethclient.
Is it safe to use public Ethereum nodes like Cloudflare's?
Public nodes are suitable for read-only operations in development or lightweight apps. For production systems requiring high availability and privacy, consider dedicated RPC services or self-hosted nodes.
What if a token doesn’t implement all ERC20 methods?
Some older tokens may lack certain functions (e.g., decimals). Always wrap calls in error handling and verify responses before processing.
Can I write to the contract using this method?
Yes—methods like Transfer or Approve can be invoked using authenticated transactions. This requires signing with a private key via bind.TransactOpts, which we’ll cover in future guides.
Why use Go instead of JavaScript for Ethereum development?
Go offers superior performance, concurrency support, and is widely used in core blockchain infrastructure (e.g., Geth). It’s ideal for backend services, indexers, and high-throughput systems.
Final Thoughts
Querying ERC20 tokens programmatically unlocks powerful possibilities—from tracking portfolio values to automating DeFi strategies. By leveraging Go's robustness and Ethereum's open architecture, developers can build scalable, secure applications that interact directly with blockchain data.
Whether you're retrieving token balances or parsing contract events, mastering these fundamentals puts you on solid ground for more advanced blockchain development.
👉 Start building your next blockchain project with reliable tools today.