description: Tutorial on how to load an initialize a smart contract with Go.

Loading 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.

Once you’ve compiled your smart contract’s ABI to a Go package using the abigen tool, the next step is to call the “New” method, which is in the format New<ContractName>, so in our example if you recall it’s going to be NewStore. This initializer method takes in the address of the smart contract and returns a contract instance that you can start interact with it.

  1. address := common.HexToAddress("0x147B8eb97fD247D06C4006D269c90C1908Fb5D54")
  2. instance, err := store.NewStore(address, client)
  3. if err != nil {
  4. log.Fatal(err)
  5. }
  6. _ = instance // we'll be using this in the next section

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_load.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. fmt.Println("contract is loaded")
  20. _ = instance
  21. }

solc version used for these examples

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