-
Notifications
You must be signed in to change notification settings - Fork 12
/
eth_tx.go
89 lines (82 loc) · 2.26 KB
/
eth_tx.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package client
import (
"context"
"fmt"
"math/big"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
ethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
)
func BuildEthTransaction(ctx context.Context, cli *ethclient.Client, priKey cryptotypes.PrivKey, to *common.Address, value *big.Int, data []byte) (*ethtypes.Transaction, error) {
sender := common.BytesToAddress(priKey.PubKey().Address().Bytes())
chainId, err := cli.ChainID(ctx)
if err != nil {
return nil, err
}
nonce, err := cli.NonceAt(ctx, sender, nil)
if err != nil {
return nil, err
}
head, err := cli.HeaderByNumber(ctx, nil)
if err != nil {
return nil, err
}
var gasTipCap, gasFeeCap, gasPrice *big.Int
if head.BaseFee != nil {
tip, err := cli.SuggestGasTipCap(ctx)
if err != nil {
return nil, err
}
gasTipCap = tip
gasFeeCap = new(big.Int).Add(tip, new(big.Int).Mul(head.BaseFee, big.NewInt(2)))
if gasFeeCap.Cmp(gasTipCap) < 0 {
return nil, fmt.Errorf("maxFeePerGas (%v) < maxPriorityFeePerGas (%v)", gasFeeCap, gasTipCap)
}
} else {
gasPrice, err = cli.SuggestGasPrice(ctx)
if err != nil {
return nil, err
}
}
msg := ethereum.CallMsg{From: sender, To: to, GasPrice: gasPrice, GasTipCap: gasTipCap, GasFeeCap: gasFeeCap, Value: value, Data: data}
gasLimit, err := cli.EstimateGas(ctx, msg)
if err != nil {
return nil, fmt.Errorf("failed to estimate gas needed: %v", err)
}
gasLimit = gasLimit * 130 / 100
if value == nil {
value = big.NewInt(0)
}
var rawTx *ethtypes.Transaction
if gasFeeCap == nil {
baseTx := ðtypes.LegacyTx{
Nonce: nonce,
GasPrice: gasPrice,
Gas: gasLimit,
To: to,
Value: value,
Data: data,
}
rawTx = ethtypes.NewTx(baseTx)
} else {
baseTx := ðtypes.DynamicFeeTx{
ChainID: chainId,
Nonce: nonce,
GasFeeCap: gasFeeCap,
GasTipCap: gasTipCap,
Gas: gasLimit,
To: to,
Value: value,
Data: data,
}
rawTx = ethtypes.NewTx(baseTx)
}
signer := ethtypes.NewLondonSigner(chainId)
signature, err := priKey.Sign(signer.Hash(rawTx).Bytes())
if err != nil {
return nil, err
}
return rawTx.WithSignature(signer, signature)
}