description: Tutorial on how to send a raw Ethereum transaction with Go.

Send Raw Transaction

In the previous section we learned how to create a raw transaction. Now we’ll learn how to broadcast it to the Ethereum network in order for it to get processed and mined.

First decode the raw transaction hex to bytes format.

  1. rawTx := "f86d8202b28477359400825208944592d8f8d7b001e72cb26a73e4fa1806a51ac79d880de0b6b3a7640000802ca05924bde7ef10aa88db9c66dd4f5fb16b46dff2319b9968be983118b57bb50562a001b24b31010004f13d9a26b320845257a6cfc2bf819a3d55e3fc86263c5f0772"
  2. rawTxBytes, err := hex.DecodeString(rawTx)

Now initialize a new types.Transaction pointer and call DecodeBytes from the go-ethereum rlp package passing it the raw transaction bytes and the pointer to the ethereum transaction type. RLP is an encoding method used by Ethereum to serialized and derialized data.

  1. tx := new(types.Transaction)
  2. rlp.DecodeBytes(rawTxBytes, &tx)

Now we can easily broadcast the transaction with our ethereum client.

  1. err := client.SendTransaction(context.Background(), tx)
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. fmt.Printf("tx sent: %s", tx.Hash().Hex()) // tx sent: 0xc429e5f128387d224ba8bed6885e86525e14bfdc2eb24b5e9c3351a1176fd81f

You can see the transaction on etherscan: https://rinkeby.etherscan.io/tx/0xc429e5f128387d224ba8bed6885e86525e14bfdc2eb24b5e9c3351a1176fd81f

Full code

transaction_raw_sendreate.go

  1. package main
  2. import (
  3. "context"
  4. "encoding/hex"
  5. "fmt"
  6. "log"
  7. "github.com/ethereum/go-ethereum/core/types"
  8. "github.com/ethereum/go-ethereum/ethclient"
  9. "github.com/ethereum/go-ethereum/rlp"
  10. )
  11. func main() {
  12. client, err := ethclient.Dial("https://rinkeby.infura.io")
  13. if err != nil {
  14. log.Fatal(err)
  15. }
  16. rawTx := "f86d8202b28477359400825208944592d8f8d7b001e72cb26a73e4fa1806a51ac79d880de0b6b3a7640000802ca05924bde7ef10aa88db9c66dd4f5fb16b46dff2319b9968be983118b57bb50562a001b24b31010004f13d9a26b320845257a6cfc2bf819a3d55e3fc86263c5f0772"
  17. rawTxBytes, err := hex.DecodeString(rawTx)
  18. tx := new(types.Transaction)
  19. rlp.DecodeBytes(rawTxBytes, &tx)
  20. err = client.SendTransaction(context.Background(), tx)
  21. if err != nil {
  22. log.Fatal(err)
  23. }
  24. fmt.Printf("tx sent: %s", tx.Hash().Hex()) // tx sent: 0xc429e5f128387d224ba8bed6885e86525e14bfdc2eb24b5e9c3351a1176fd81f
  25. }