golang以太坊发送交易
以下是使用golang发送以太坊交易的示例代码:
package main
import (
"context"
"crypto/ecdsa"
"fmt"
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/core/types"
)
func main() {
// 连接以太坊网络
client, err := ethclient.Dial("https://mainnet.infura.io")
if err != nil {
panic(err)
}
// 获取发送者的私钥
privateKey, err := crypto.HexToECDSA("私钥")
if err != nil {
panic(err)
}
// 获取发送者地址
fromAddress := crypto.PubkeyToAddress(privateKey.PublicKey)
// 获取nonce
nonce, err := client.PendingNonceAt(context.Background(), fromAddress)
if err != nil {
panic(err)
}
// 设置gas价格和gas限制
gasPrice, err := client.SuggestGasPrice(context.Background())
if err != nil {
panic(err)
}
gasLimit := uint64(21000)
// 设置接收者地址、转账金额和数据
toAddress := common.HexToAddress("接收者地址")
value := big.NewInt(1000000000000000000) // 1 ETH
data := []byte{}
// 创建交易对象
tx := types.NewTransaction(nonce, toAddress, value, gasLimit, gasPrice, data)
// 对交易进行签名
signedTx, err := types.SignTx(tx, types.NewEIP155Signer(client.ChainID()), privateKey)
if err != nil {
panic(err)
}
// 发送交易
err = client.SendTransaction(context.Background(), signedTx)
if err != nil {
panic(err)
}
// 输出交易hash
fmt.Printf("tx sent: %s", signedTx.Hash().Hex())
}
请注意,要成功发送交易,您需要将代码中的私钥和接收者地址替换为您自己的私钥和地址。此外,您还需要确保您的私钥具有足够的以太坊余额以支付交易费用。
原文地址: https://www.cveoy.top/t/topic/ime 著作权归作者所有。请勿转载和采集!