forked from chenzhijie/go-web3
/
erc721.go
330 lines (290 loc) · 7.21 KB
/
erc721.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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
package erc721
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 ERC721 struct {
contr *eth.Contract
w3 *web3.Web3
confirmation int
txPollTimeout int
}
func NewERC721(w3 *web3.Web3, contractAddress common.Address) (*ERC721, error) {
contr, err := w3.Eth.NewContract(ERC721_ABI, contractAddress.String())
if err != nil {
return nil, err
}
e := &ERC721{
contr: contr,
w3: w3,
txPollTimeout: 720,
}
return e, nil
}
func (e *ERC721) Address() common.Address {
return e.contr.Address()
}
func (e *ERC721) SetConfirmation(blockCount int) {
e.confirmation = blockCount
}
func (e *ERC721) SetTxPollTimeout(txPollTimeout int) {
e.txPollTimeout = txPollTimeout
}
func (e *ERC721) TotalSupply() (*big.Int, error) {
ret, err := e.contr.Call("totalSupply")
if err != nil {
return nil, err
}
supply, ok := ret.(*big.Int)
if !ok {
return nil, fmt.Errorf("invalid response %v type %T expect *big.Int", ret, ret)
}
return supply, nil
}
func (e *ERC721) BalanceOf(owner common.Address) (*big.Int, error) {
ret, err := e.contr.Call("balanceOf", owner)
if err != nil {
return nil, err
}
bal, ok := ret.(*big.Int)
if !ok {
return nil, fmt.Errorf("invalid result %v, type %T", ret, ret)
}
return bal, nil
}
func (e *ERC721) OwnerOf(tokenId *big.Int) (common.Address, error) {
ret, err := e.contr.Call("ownerOf", tokenId)
if err != nil {
return common.Address{}, err
}
owner, ok := ret.(common.Address)
if !ok {
return common.Address{}, fmt.Errorf("invalid result %v, type %T", ret, ret)
}
return owner, nil
}
func (e *ERC721) IsApprovedForAll(owner, operator common.Address) (bool, error) {
ret, err := e.contr.Call("isApprovedForAll", owner, operator)
if err != nil {
return false, err
}
approved, ok := ret.(bool)
if !ok {
return false, fmt.Errorf("invalid response type %T", ret)
}
return approved, nil
}
func (e *ERC721) SetApprovalForAll(
spender common.Address,
approve bool,
gasPrice *big.Int,
gasTipCap *big.Int,
gasFeeCap *big.Int,
) (common.Hash, error) {
code, err := e.contr.EncodeABI("setApprovalForAll", spender, approve)
if err != nil {
return common.Hash{}, err
}
return e.invokeAndWait(code, gasPrice, gasTipCap, gasFeeCap)
}
func (e *ERC721) TransferFrom(
from common.Address,
to common.Address,
tokenId *big.Int,
gasPrice *big.Int,
gasTipCap *big.Int,
gasFeeCap *big.Int,
) (common.Hash, error) {
code, err := e.contr.EncodeABI("transferFrom", from, to, tokenId)
if err != nil {
return common.Hash{}, err
}
return e.invokeAndWait(code, gasPrice, gasTipCap, gasFeeCap)
}
func (e *ERC721) IsApprovalForAll(owner, spender common.Address) (bool, error) {
ret, err := e.contr.Call("isApprovedForAll", owner, spender)
if err != nil {
return false, err
}
approved, ok := ret.(bool)
if !ok {
return false, fmt.Errorf("invalid response %v type %T expect bool", ret, ret)
}
return approved, nil
}
func (e *ERC721) 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.Compare(emptyAddr[:], from[:]) != 0 {
call.From = from
}
gasLimit, err := e.w3.Eth.EstimateGas(call)
if err != nil {
return 0, err
}
return gasLimit, nil
}
func (e *ERC721) 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 *ERC721) 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 *ERC721) 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 *ERC721) 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 e.confirmation == 0 {
return tx.TxHash, nil
}
if err := e.WaitBlock(uint64(e.confirmation)); err != nil {
return common.Hash{}, err
}
return tx.TxHash, nil
}