description: Tutorial on how to query a smart contract with Go.

Querying a Smart Contract

These section requires knowledge of how to compile a smart contract’s ABI to a Go contract file. If you haven’t already gone through it, please read the section first.

In the previous section we learned how to initialize a contract instance in our Go application. Now we’re going to read the smart contract using the provided methods by the new contract instance. If you recall we had a global variable named version in our contract that was set during deployment. Because it’s public that means that they’ll be a getter function automatically created for us. Constant and view functions also accept bind.CallOpts as the first argument. To learn about what options you can pass checkout the type’s documentation but usually this is set to nil.

  1. version, err := instance.Version(nil)
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. fmt.Println(version) // "1.0"

Full code

Commands

  1. solc --abi Store.sol
  2. solc --bin Store.sol
  3. abigen --bin=Store_sol_Store.bin --abi=Store_sol_Store.abi --pkg=store --out=Store.go

Store.sol

  1. pragma solidity ^0.4.24;
  2. contract Store {
  3. event ItemSet(bytes32 key, bytes32 value);
  4. string public version;
  5. mapping (bytes32 => bytes32) public items;
  6. constructor(string _version) public {
  7. version = _version;
  8. }
  9. function setItem(bytes32 key, bytes32 value) external {
  10. items[key] = value;
  11. emit ItemSet(key, value);
  12. }
  13. }

contract_read.go

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "github.com/ethereum/go-ethereum/common"
  6. "github.com/ethereum/go-ethereum/ethclient"
  7. store "./contracts" // for demo
  8. )
  9. func main() {
  10. client, err := ethclient.Dial("https://rinkeby.infura.io")
  11. if err != nil {
  12. log.Fatal(err)
  13. }
  14. address := common.HexToAddress("0x147B8eb97fD247D06C4006D269c90C1908Fb5D54")
  15. instance, err := store.NewStore(address, client)
  16. if err != nil {
  17. log.Fatal(err)
  18. }
  19. version, err := instance.Version(nil)
  20. if err != nil {
  21. log.Fatal(err)
  22. }
  23. fmt.Println(version) // "1.0"
  24. }

solc version used for these examples

  1. $ solc --version
  2. 0.4.24+commit.e67f0147.Emscripten.clang