Chuyển đến nội dung chính

How to send an EIP-1559 transaction using Go

If you're using Go, check out this pretty good guide about how to interact with Ethereum. In particular, this example shows how to send a legacy transaction. But since there isn't an example for the EIP-1559 transaction type, we'll cover that here.

Representative example

This example uses fixed gas values for demonstration. In a production environment, you should fetch current gas values from the network based on your transaction's priority and current network conditions.

Guide

  1. Download and install Go
  2. Create a Go script and call it eip1559_tx.go
  3. Replace the API key and ADDRESS_TO with your relevant values
  4. Run the script with:
go run eip1559_tx.go
  1. Expected response:
Transaction hash: 0x...

Code

package main

import (
"context"
"crypto/ecdsa"
"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"
)

func main() {
client, err := ethclient.Dial("https://sepolia.infura.io/v3/API_KEY")
if err != nil {
log.Fatal(err)
}

privateKey, err := crypto.HexToECDSA("PRIVATE_KEY")
if err != nil {
log.Fatal(err)
}

publicKey := privateKey.Public()
publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
if !ok {
log.Fatal("error casting public key to ECDSA")
}

fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA)

nonce, err := client.PendingNonceAt(context.Background(), fromAddress)
if err != nil {
log.Fatal(err)
}

value := big.NewInt(100000000000000000) // in wei (0.1 eth)
gasLimit := uint64(21000) // in units
tip := big.NewInt(2000000000) // maxPriorityFeePerGas = 2 Gwei
feeCap := big.NewInt(20000000000) // maxFeePerGas = 20 Gwei
if err != nil {
log.Fatal(err)
}

toAddress := common.HexToAddress("ADDRESS_TO")
var data []byte

chainID, err := client.NetworkID(context.Background())
if err != nil {
log.Fatal(err)
}

tx := types.NewTx(&types.DynamicFeeTx{
ChainID: chainID,
Nonce: nonce,
GasFeeCap: feeCap,
GasTipCap: tip,
Gas: gasLimit,
To: &toAddress,
Value: value,
Data: data,
})

signedTx, err := types.SignTx(tx, types.LatestSignerForChainID(chainID), privateKey)

if err != nil {
log.Fatal(err)
}

err = client.SendTransaction(context.Background(), signedTx)
if err != nil {
log.Fatal(err)
}

fmt.Printf("Transaction hash: %s", signedTx.Hash().Hex())

}
Was this helpful?
Connect MetaMask to provide feedback
What is this?
This is a trial feedback system that uses Verax to record your feedback as onchain attestations on Linea Mainnet. When you vote, submit a transaction in your wallet.