最近,想用golang做個(gè)以太坊的交易發(fā)送(不使用合約生成的代理類(lèi))腹缩。首先屿聋,在本機(jī)找了一圈發(fā)現(xiàn)之前的代碼沒(méi)了(換電腦了。藏鹊。润讥。想吐);接著盘寡,在自己簡(jiǎn)書(shū)上翻了一圈發(fā)現(xiàn)只記錄了js版本的楚殿;然后,打算去網(wǎng)上摘一下 哈哈宴抚,找了幾分鐘勒魔,沒(méi)找到自己想要的那種甫煞」角可氣的是冠绢,發(fā)現(xiàn)國(guó)內(nèi)的某網(wǎng)站的文章竟然要錢(qián)才能看?常潮?弟胀?are you kidding me?既然這樣喊式,那咱就手?jǐn)]一下孵户,順便,給新手學(xué)習(xí)或者省事想摘一下的朋友做點(diǎn)貢獻(xiàn)岔留,開(kāi)源O目蕖!献联!
安裝一下類(lèi)庫(kù): github.com/ethereum/go-ethereum v1.14.7竖配,完成后開(kāi)擼,里逆,进胯,
先做一個(gè)交易發(fā)送的方法封裝,暴露出常用的參數(shù)原押,另外胁镐,支持gasprice和gaslimit的參數(shù)外部自定義賦值,以及內(nèi)部動(dòng)態(tài)獲取诸衔。代碼如下:
// 僅實(shí)現(xiàn)發(fā)送DynamicFeeTx類(lèi)型的交易
func sendTransaction(ec *ethclient.Client, prvHex string, to *common.Address, value *big.Int, input []byte, gasPrice *big.Int, gasLimit uint64) (common.Hash, error) {
chainID, err := ec.ChainID(context.Background())
if err != nil {
return common.Hash{}, err
}
prvBytes, err := hexutil.Decode(prvHex)
if err != nil {
return common.Hash{}, err
}
prv, err := crypto.ToECDSA(prvBytes)
if err != nil {
return common.Hash{}, err
}
from := crypto.PubkeyToAddress(prv.PublicKey)
if gasPrice == nil || gasPrice.Uint64() == 0 {
gasPrice, err = ec.SuggestGasTipCap(context.Background())
if err != nil {
return common.Hash{}, err
}
}
if gasLimit == 0 {
gasLimit, err = ec.EstimateGas(context.Background(), ethereum.CallMsg{
From: from,
To: to,
Value: value,
Data: input,
})
if err != nil {
return common.Hash{}, err
}
}
nonce, err := ec.PendingNonceAt(context.Background(), from)
if err != nil {
return common.Hash{}, err
}
signer := types.LatestSignerForChainID(chainID)
// signer := types.NewLondonSigner(chainID) // 本地私有網(wǎng)絡(luò)使用舊版本時(shí)盯漂,需要自定義。
tx, err := types.SignNewTx(prv, signer, &types.DynamicFeeTx{
Nonce: nonce,
GasTipCap: gasPrice,
GasFeeCap: gasPrice,
Gas: gasLimit,
To: to,
Value: value,
Data: input,
AccessList: nil,
})
if err != nil {
return common.Hash{}, err
}
return tx.Hash(), ec.SendTransaction(context.Background(), tx)
}
下面做一個(gè)轉(zhuǎn)賬1 ether的測(cè)試笨农,代碼如下:
func main() {
transferTest()
//txUrl: https://holesky.etherscan.io/tx/0x4b0bdf38b91d225cf78c2034b90a05eec2f82b3df79286638fc505ffcf7a8b00
}
func transferTest() {
url := "https://holesky.infura.io/v3/d9044f2a78842d6b3e39aed7cxxx"
client, err := ethclient.Dial(url)
if err != nil {
fmt.Printf(" ethclient.Dial error:%s", err.Error())
return
}
privateKey := "0x" //addr: 0xAa1a88aa89F50ee9B7e3F6124f18a31d5E6dB1F9
transferTo := common.HexToAddress("0xBC1F42383f9567B43C219200D83C71CF144C1146")
tx, err := sendTransaction(client, privateKey, &transferTo, big.NewInt(1000000000000000000), nil, big.NewInt(0), 0)
if err != nil {
fmt.Printf(" sendTransaction error:%s", err.Error())
return
}
fmt.Printf("txHash: %s \n", tx.Hex())
}
ide執(zhí)行結(jié)果如下:
txHash: 0x4b0bdf38b91d225cf78c2034b90a05eec2f82b3df79286638fc505ffcf7a8b00
Process finished with the exit code 0
結(jié)束宠能!