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

Writing to 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.

Writing to a smart contract requires us to sign the sign transaction with our private key.

  1. privateKey, err := crypto.HexToECDSA("fad9c8855b740a0b7ed4c221dbad0f33a83a49cad6b3fe8d5817ac83d38b6a19")
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. publicKey := privateKey.Public()
  6. publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
  7. if !ok {
  8. log.Fatal("cannot assert type: publicKey is not of type *ecdsa.PublicKey")
  9. }
  10. fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA)

We’ll also need to figure the nonce and gas price.

  1. nonce, err := client.PendingNonceAt(context.Background(), fromAddress)
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. gasPrice, err := client.SuggestGasPrice(context.Background())
  6. if err != nil {
  7. log.Fatal(err)
  8. }

Next we create a new keyed transactor which takes in the private key.

  1. auth := bind.NewKeyedTransactor(privateKey)

Then we need to set the standard transaction options attached to the keyed transactor.

  1. auth.Nonce = big.NewInt(int64(nonce))
  2. auth.Value = big.NewInt(0) // in wei
  3. auth.GasLimit = uint64(300000) // in units
  4. auth.GasPrice = gasPrice

Now we load an instance of the smart contract. If you recall in the previous sections we create a contract called Store and generated a Go package file using the abigen tool. To initialize it we just invoke the New method of the contract package and give the smart contract address and the ethclient, which returns a contract instance that we can use.

  1. address := common.HexToAddress("0x147B8eb97fD247D06C4006D269c90C1908Fb5D54")
  2. instance, err := store.NewStore(address, client)
  3. if err != nil {
  4. log.Fatal(err)
  5. }

The smart contract that we created has an external method called SetItem which takes in two arguments (key, value) in the from of solidity bytes32. This means that the Go contract package requires us to pass a byte array of length 32 bytes. Invoking the SetItem method requires us to pass the auth object we created earlier. Behind the scenes this method will encode this function call with it’s arguments, set it as the data property of the transaction, and sign it with the private key. The result will be a signed transaction object.

  1. key := [32]byte{}
  2. value := [32]byte{}
  3. copy(key[:], []byte("foo"))
  4. copy(value[:], []byte("bar"))
  5. tx, err := instance.SetItem(auth, key, value)
  6. if err != nil {
  7. log.Fatal(err)
  8. }
  9. fmt.Printf("tx sent: %s\n", tx.Hash().Hex()) // tx sent: 0x8d490e535678e9a24360e955d75b27ad307bdfb97a1dca51d0f3035dcee3e870

We can see now that the transaction has been successfully sent on the network: https://rinkeby.etherscan.io/tx/0x8d490e535678e9a24360e955d75b27ad307bdfb97a1dca51d0f3035dcee3e870

To verify that the key/value was set, we read the smart contract mapping value.

  1. result, err := instance.Items(nil, key)
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. fmt.Println(string(result[:])) // "bar"

There you have it.

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_write.go

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "github.com/ethereum/go-ethereum/accounts/abi/bind"
  6. "github.com/ethereum/go-ethereum/common"
  7. "github.com/ethereum/go-ethereum/ethclient"
  8. store "./contracts" // for demo
  9. )
  10. func main() {
  11. client, err := ethclient.Dial("https://rinkeby.infura.io")
  12. if err != nil {
  13. log.Fatal(err)
  14. }
  15. privateKey, err := crypto.HexToECDSA("fad9c8855b740a0b7ed4c221dbad0f33a83a49cad6b3fe8d5817ac83d38b6a19")
  16. if err != nil {
  17. log.Fatal(err)
  18. }
  19. publicKey := privateKey.Public()
  20. publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
  21. if !ok {
  22. log.Fatal("cannot assert type: publicKey is not of type *ecdsa.PublicKey")
  23. }
  24. fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA)
  25. nonce, err := client.PendingNonceAt(context.Background(), fromAddress)
  26. if err != nil {
  27. log.Fatal(err)
  28. }
  29. gasPrice, err := client.SuggestGasPrice(context.Background())
  30. if err != nil {
  31. log.Fatal(err)
  32. }
  33. auth := bind.NewKeyedTransactor(privateKey)
  34. auth.Nonce = big.NewInt(int64(nonce))
  35. auth.Value = big.NewInt(0) // in wei
  36. auth.GasLimit = uint64(300000) // in units
  37. auth.GasPrice = gasPrice
  38. address := common.HexToAddress("0x147B8eb97fD247D06C4006D269c90C1908Fb5D54")
  39. instance, err := store.NewStore(address, client)
  40. if err != nil {
  41. log.Fatal(err)
  42. }
  43. key := [32]byte{}
  44. value := [32]byte{}
  45. copy(key[:], []byte("foo"))
  46. copy(value[:], []byte("bar"))
  47. tx, err := instance.SetItem(auth, key, value)
  48. if err != nil {
  49. log.Fatal(err)
  50. }
  51. fmt.Printf("tx sent: %s", tx.Hash().Hex()) // tx sent: 0x8d490e535678e9a24360e955d75b27ad307bdfb97a1dca51d0f3035dcee3e870
  52. result, err := instance.Items(nil, key)
  53. if err != nil {
  54. log.Fatal(err)
  55. }
  56. fmt.Println(string(result[:])) // "bar"
  57. }

solc version used for these examples

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