Last active
September 17, 2023 05:42
-
-
Save miguelmota/bb4783c29069603a85753453c2f571b4 to your computer and use it in GitHub Desktop.
Go encode unsigned transaction, decode transaction, sign and broadcast examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
} |
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
hi Miguel, below code is not working anymore,
type.Transaction
now doesn't have this method.