/
eth.go
109 lines (90 loc) · 2.73 KB
/
eth.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package eth_multi_transactions
import (
"context"
"crypto/ecdsa"
"fmt"
"math/big"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/haihongs/eth-multi-transactions/common/logger"
)
var (
Wei = big.NewInt(1)
GWei = big.NewInt(1e9)
Ether = big.NewInt(0).Mul(GWei, GWei) // 1ether = 1e18wei
)
func GetBalance(c *ethclient.Client, addr string) (*big.Int, error) {
return c.BalanceAt(context.Background(), common.HexToAddress(addr), nil)
}
func PollingTransaction(ethc *ethclient.Client, txid string, threshold int64, timeout time.Duration) error {
end := time.Now().Add(timeout)
ticker := time.NewTicker(5 * time.Second)
cnt := int64(0)
for range ticker.C {
if time.Now().After(end) {
return fmt.Errorf("polling timeout, txid: %s", txid)
}
_, isPending, err := ethc.TransactionByHash(context.Background(), common.HexToHash(txid))
if err != nil {
logger.Error("failed to get transaction by hash", "err", err)
continue
}
if isPending {
continue
}
cnt++
if cnt >= threshold {
return nil
}
}
return nil
}
func SendEthTransaction(
obj *DbWithdrawalObj,
ethc *ethclient.Client,
fromAddr common.Address,
prvKey *ecdsa.PrivateKey,
chainID *big.Int,
) (string, error) {
// build tx
ctx := context.Background()
nonce, err := ethc.NonceAt(ctx, fromAddr, nil)
if err != nil {
return "", err
}
gasPrice, err := ethc.SuggestGasPrice(ctx)
if err != nil {
return "", err
}
if balance, err := ethc.BalanceAt(ctx, fromAddr, nil); err != nil {
return "", err
} else {
if balance.Cmp(obj.Amount) <= 0 {
return "", fmt.Errorf("not enough balance, need: %v real: %v", obj.Amount, balance)
}
}
gasPrice.Add(gasPrice, big.NewInt(0).Mul(big.NewInt(5), GWei))
toAddr := common.HexToAddress(obj.Address)
logger.Info("xx", "nonce", nonce, "gasprice", gasPrice, "toaddr", toAddr)
tx := types.NewTx(&types.LegacyTx{
Nonce: nonce,
To: &toAddr,
Value: obj.Amount,
Gas: 21000,
GasPrice: gasPrice,
Data: []byte{},
})
signer := types.LatestSignerForChainID(chainID)
signedTx, err := types.SignTx(tx, signer, prvKey)
//signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, prvKey)
if err != nil {
return "", err
}
// broadcast
if err = ethc.SendTransaction(ctx, signedTx); err != nil {
return "", err
}
return signedTx.Hash().Hex(), nil
}