Transferring ETH with Go: A Step-by-Step Guide

·

This tutorial demonstrates how to transfer Ethereum (ETH) between accounts using the Go programming language. You'll learn to construct, sign, and broadcast transactions while adhering to Ethereum's security protocols.

Prerequisites

Key Components of an ETH Transfer

  1. Sender's Private Key: Cryptographic signature generator
  2. Nonce: Transaction counter for the sending account
  3. Gas Parameters:

    • Gas Limit (21,000 units for ETH transfers)
    • Gas Price (dynamic, market-dependent)
  4. Recipient Address: Destination wallet
  5. Value: Amount in wei (1 ETH = 10¹⁸ wei)

Step-by-Step Implementation

1. Loading the Private Key

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

2. Deriving the Public Address

publicKey := privateKey.Public()
publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
if !ok {
    log.Fatal("error asserting public key type")
}
fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA)

3. Setting Transaction Parameters

nonce, err := client.PendingNonceAt(context.Background(), fromAddress)
value := big.NewInt(1000000000000000000) // 1 ETH in wei
gasLimit := uint64(21000)
gasPrice, err := client.SuggestGasPrice(context.Background())
toAddress := common.HexToAddress("0x4592d8f8d7b001e72cb26a73e4fa1806a51ac79d")

4. Creating and Signing the Transaction

tx := types.NewTransaction(nonce, toAddress, value, gasLimit, gasPrice, nil)
chainID, err := client.NetworkID(context.Background())
signedTx, err := types.SignTx(tx, types.NewEIP155Signer(chainID), privateKey)

5. Broadcasting the Transaction

err = client.SendTransaction(context.Background(), signedTx)
fmt.Printf("Transaction hash: %s", signedTx.Hash().Hex())

👉 Track your ETH transfer on Etherscan

Best Practices for ETH Transfers

Common Errors and Solutions

ErrorSolution
"nonce too low"Fetch current nonce with PendingNonceAt
"insufficient funds"Check ETH balance and gas costs
"invalid sender"Verify private key corresponds to fromAddress

FAQ

Q: How do I calculate gas costs?

A: Multiply gas limit by gas price. For example: 21,000 units * 30 Gwei = 630,000 Gwei (0.00063 ETH).

Q: Can I speed up a pending transaction?

A: Yes, by resending with higher gas price using the same nonce.

Q: Why 21,000 gas units for ETH transfers?

A: This is Ethereum's fixed cost for standard value transfers without smart contract execution.

Q: How do I convert ETH to wei?

A: Multiply ETH amount by 10¹⁸. Example: 1.5 ETH = 1.5 * 10¹⁸ wei.

👉 Advanced Ethereum development resources

Complete Code Example

[The complete code example from the original content]

Remember: Always keep your private keys secure and test transactions on testnets before executing them on mainnet. For additional Ethereum development guidance, check our 👉 Go Ethereum Handbook.