forked from chenzhijie/go-web3
/
erc20.go
314 lines (269 loc) · 6.68 KB
/
erc20.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
package erc20
import (
"bytes"
"fmt"
"math/big"
"sync/atomic"
"time"
"github.com/Black-Shard/go-web3"
"github.com/Black-Shard/go-web3/eth"
"github.com/Black-Shard/go-web3/types"
"github.com/ethereum/go-ethereum/common"
eTypes "github.com/ethereum/go-ethereum/core/types"
)
type ERC20 struct {
contr *eth.Contract
w3 *web3.Web3
confirmation int
txPollTimeout int
}
func NewERC20(w3 *web3.Web3, contractAddress common.Address) (*ERC20, error) {
contr, err := w3.Eth.NewContract(ERC20_ABI, contractAddress.String())
if err != nil {
return nil, err
}
e := &ERC20{
contr: contr,
w3: w3,
txPollTimeout: 720,
}
return e, nil
}
func (e *ERC20) Address() common.Address {
return e.contr.Address()
}
func (e *ERC20) SetConfirmation(blockCount int) {
e.confirmation = blockCount
}
func (e *ERC20) SetTxPollTimeout(txPollTimeout int) {
e.txPollTimeout = txPollTimeout
}
func (e *ERC20) Allowance(owner, spender common.Address) (*big.Int, error) {
ret, err := e.contr.Call("allowance", owner, spender)
if err != nil {
return nil, err
}
allow, ok := ret.(*big.Int)
if !ok {
return nil, fmt.Errorf("invalid result %v, type %T", ret, ret)
}
return allow, nil
}
func (e *ERC20) Decimals() (uint8, error) {
ret, err := e.contr.Call("decimals")
if err != nil {
return 0, err
}
decimals, ok := ret.(uint8)
if !ok {
return 0, fmt.Errorf("invalid result %v, type %T", ret, ret)
}
return decimals, nil
}
func (e *ERC20) Symbol() (string, error) {
ret, err := e.contr.Call("symbol")
if err != nil {
return "", err
}
symbol, ok := ret.(string)
if !ok {
return "", fmt.Errorf("invalid result %v, type %T", ret, ret)
}
return symbol, nil
}
func (e *ERC20) BalanceOf(owner common.Address) (*big.Int, error) {
ret, err := e.contr.Call("balanceOf", owner)
if err != nil {
return nil, err
}
allow, ok := ret.(*big.Int)
if !ok {
return nil, fmt.Errorf("invalid result %v, type %T", ret, ret)
}
return allow, nil
}
func (e *ERC20) Approve(spender common.Address, limit, gasPrice, gasTipCap, gasFeeCap *big.Int) (common.Hash, error) {
code, err := e.contr.EncodeABI("approve", spender, limit)
if err != nil {
return common.Hash{}, err
}
return e.invokeAndWait(code, gasPrice, gasTipCap, gasFeeCap)
}
func (e *ERC20) Transfer(to common.Address, amount, gasPrice, gasTipCap, gasFeeCap *big.Int) (common.Hash, error) {
code, err := e.contr.EncodeABI("transfer", to, amount)
if err != nil {
return common.Hash{}, err
}
return e.invokeAndWait(code, gasPrice, gasTipCap, gasFeeCap)
}
func (e *ERC20) EstimateGasLimit(to common.Address, data []byte, gasPrice, wei *big.Int) (uint64, error) {
call := &types.CallMsg{
To: to,
Data: data,
Gas: types.NewCallMsgBigInt(big.NewInt(types.MAX_GAS_LIMIT)),
Value: types.NewCallMsgBigInt(wei),
}
if gasPrice != nil {
call.GasPrice = types.NewCallMsgBigInt(gasPrice)
}
var emptyAddr common.Address
from := e.w3.Eth.Address()
if !bytes.Equal(emptyAddr[:], from[:]) {
call.From = from
}
gasLimit, err := e.w3.Eth.EstimateGas(call)
if err != nil {
return 0, err
}
return gasLimit, nil
}
func (e *ERC20) WaitBlock(blockCount uint64) error {
num, err := e.w3.Eth.GetBlockNumber()
if err != nil {
return err
}
ti := time.NewTicker(time.Second)
defer ti.Stop()
for {
<-ti.C
nextNum, err := e.w3.Eth.GetBlockNumber()
if err != nil {
return err
}
if nextNum >= num+blockCount {
return nil
}
}
}
func (e *ERC20) SyncSendRawTransactionForTx(
gasPrice *big.Int, gasLimit uint64, to common.Address, data []byte, wei *big.Int,
) (*eTypes.Receipt, error) {
nonce, err := e.w3.Eth.GetNonce(e.w3.Eth.Address(), nil)
if err != nil {
return nil, err
}
hash, err := e.w3.Eth.SendRawTransaction(to, wei, nonce, gasLimit, gasPrice, data)
if err != nil {
return nil, err
}
type ReceiptCh struct {
ret *eTypes.Receipt
err error
}
var timeoutFlag int32
ch := make(chan *ReceiptCh, 1)
go func() {
for {
receipt, err := e.w3.Eth.GetTransactionReceipt(hash)
if err != nil && err.Error() != "not found" {
ch <- &ReceiptCh{
err: err,
}
break
}
if receipt != nil {
ch <- &ReceiptCh{
ret: receipt,
err: nil,
}
break
}
if atomic.LoadInt32(&timeoutFlag) == 1 {
break
}
}
// fmt.Println("send tx done")
}()
select {
case result := <-ch:
if result.err != nil {
return nil, err
}
return result.ret, nil
case <-time.After(time.Duration(e.txPollTimeout) * time.Second):
atomic.StoreInt32(&timeoutFlag, 1)
return nil, fmt.Errorf("transaction was not mined within %v seconds, "+
"please make sure your transaction was properly sent. Be aware that it might still be mined!", e.txPollTimeout)
}
}
func (e *ERC20) SyncSendEIP1559Tx(
gasTipCap *big.Int,
gasFeeCap *big.Int,
gasLimit uint64,
to common.Address,
data []byte,
wei *big.Int,
) (*eTypes.Receipt, error) {
nonce, err := e.w3.Eth.GetNonce(e.w3.Eth.Address(), nil)
if err != nil {
return nil, err
}
hash, err := e.w3.Eth.SendRawEIP1559Transaction(to, wei, nonce, gasLimit, gasTipCap, gasFeeCap, data)
if err != nil {
return nil, err
}
type ReceiptCh struct {
ret *eTypes.Receipt
err error
}
var timeoutFlag int32
ch := make(chan *ReceiptCh, 1)
go func() {
for {
receipt, err := e.w3.Eth.GetTransactionReceipt(hash)
if err != nil && err.Error() != "not found" {
ch <- &ReceiptCh{
err: err,
}
break
}
if receipt != nil {
ch <- &ReceiptCh{
ret: receipt,
err: nil,
}
break
}
if atomic.LoadInt32(&timeoutFlag) == 1 {
break
}
}
// fmt.Println("send tx done")
}()
select {
case result := <-ch:
if result.err != nil {
return nil, err
}
return result.ret, nil
case <-time.After(time.Duration(e.txPollTimeout) * time.Second):
atomic.StoreInt32(&timeoutFlag, 1)
return nil, fmt.Errorf("transaction was not mined within %v seconds, "+
"please make sure your transaction was properly sent. Be aware that it might still be mined!", e.txPollTimeout)
}
}
func (e *ERC20) invokeAndWait(code []byte, gasPrice, gasTipCap, gasFeeCap *big.Int) (common.Hash, error) {
gasLimit, err := e.EstimateGasLimit(e.contr.Address(), code, nil, nil)
if err != nil {
return common.Hash{}, err
}
var tx *eTypes.Receipt
if gasPrice != nil {
tx, err = e.SyncSendRawTransactionForTx(gasPrice, gasLimit, e.contr.Address(), code, nil)
} else {
tx, err = e.SyncSendEIP1559Tx(gasTipCap, gasFeeCap, gasLimit, e.contr.Address(), code, nil)
}
if err != nil {
return common.Hash{}, err
}
if tx == nil {
return common.Hash{}, nil
}
if e.confirmation == 0 {
return tx.TxHash, nil
}
if err := e.WaitBlock(uint64(e.confirmation)); err != nil {
return common.Hash{}, err
}
return tx.TxHash, nil
}