description: Tutorial on how to read the bytecode of a deployed smart contract with Go.

Reading Smart Contract Bytecode

Sometimes you’ll need to read the bytecode of a deployed smart contract. Since all the smart contract bytecode lives on the blockchain, we can easily fetch it.

First set up the client and the smart contract address you want to read the bytecode of.

  1. client, err := ethclient.Dial("https://rinkeby.infura.io")
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. contractAddress := common.HexToAddress("0x147B8eb97fD247D06C4006D269c90C1908Fb5D54")

Now all you have to is call the codeAt method of the client. The codeAt method accepts a smart contract address and an optional block number, and returns the bytecode in bytes format.

  1. bytecode, err := client.CodeAt(context.Background(), contractAddress, nil) // nil is latest block
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. fmt.Println(hex.EncodeToString(bytecode)) // 60806...10029

See the same bytecode hex on etherscan https://rinkeby.etherscan.io/address/0x147b8eb97fd247d06c4006d269c90c1908fb5d54#code

Full code

contract_bytecode.go

  1. package main
  2. import (
  3. "context"
  4. "encoding/hex"
  5. "fmt"
  6. "log"
  7. "github.com/ethereum/go-ethereum/common"
  8. "github.com/ethereum/go-ethereum/ethclient"
  9. )
  10. func main() {
  11. client, err := ethclient.Dial("https://rinkeby.infura.io")
  12. if err != nil {
  13. log.Fatal(err)
  14. }
  15. contractAddress := common.HexToAddress("0x147B8eb97fD247D06C4006D269c90C1908Fb5D54")
  16. bytecode, err := client.CodeAt(context.Background(), contractAddress, nil) // nil is latest block
  17. if err != nil {
  18. log.Fatal(err)
  19. }
  20. fmt.Println(hex.EncodeToString(bytecode)) // 60806...10029
  21. }