Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Last active September 17, 2023 05:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save miguelmota/bb4783c29069603a85753453c2f571b4 to your computer and use it in GitHub Desktop.
Save miguelmota/bb4783c29069603a85753453c2f571b4 to your computer and use it in GitHub Desktop.
Go encode unsigned transaction, decode transaction, sign and broadcast examples
package main
import (
"context"
"encoding/hex"
"fmt"
"log"
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/rlp"
)
func main() {
client, err := ethclient.Dial("https://rinkeby.infura.io")
if err != nil {
log.Fatal(err)
}
value := big.NewInt(100000000000000000)
gasLimit := uint64(21000)
gasPrice, err := client.SuggestGasPrice(context.Background())
if err != nil {
log.Fatal(err)
}
fromAddress := common.HexToAddress("0x96216849c49358B10257cb55b28eA603c874b05E")
nonce, err := client.PendingNonceAt(context.Background(), fromAddress)
if err != nil {
log.Fatal(err)
}
toAddress := common.HexToAddress("0x4592d8f8d7b001e72cb26a73e4fa1806a51ac79d")
var data []byte
tx := types.NewTransaction(nonce, toAddress, value, gasLimit, gasPrice, data)
chainID, err := client.NetworkID(context.Background())
if err != nil {
log.Fatal(err)
}
ts := types.Transactions{tx}
rawTxBytes := ts.GetRlp(0)
rawTxHex := hex.EncodeToString(rawTxBytes)
fmt.Printf("Unsigned Tx: %s\n", rawTxHex)
// read from unsigned tx bytes
tx = new(types.Transaction)
rlp.DecodeBytes(rawTxBytes, &tx)
privateKey, err := crypto.HexToECDSA("fad9c8855b740a0b7ed4c221dbad0f33a83a49cad6b3fe8d5817ac83d38b6a19")
if err != nil {
log.Fatal(err)
}
signer := types.NewEIP155Signer(chainID)
signedTx, err := types.SignTx(tx, signer, privateKey)
if err != nil {
log.Fatal(err)
}
ts = types.Transactions{tx}
signedRawTxBytes := ts.GetRlp(0)
fmt.Printf("Signed Tx: %x\n", signedRawTxBytes)
err = client.SendTransaction(context.Background(), signedTx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Tx Hash: %s\n", signedTx.Hash().Hex())
}
@huahuayu
Copy link

hi Miguel, below code is not working anymore, type.Transaction now doesn't have this method.

	ts = types.Transactions{tx}
	signedRawTxBytes := ts.GetRlp(0)

@brendan-mccaffrey
Copy link

Can we get support on updated syntax for replacing
ts.GetRlp(0)
??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment