-
Notifications
You must be signed in to change notification settings - Fork 0
/
erc721.go
691 lines (554 loc) · 18.4 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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
package erc721
import "C"
import (
"context"
"crypto/ecdsa"
"encoding/json"
"errors"
"fmt"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/jason-bateman/go-erc-standard-contract/contracts/common/bind"
erc721 "github.com/jason-bateman/go-erc-standard-contract/contracts/erc721/contract"
"github.com/jason-bateman/go-erc-standard-contract/contracts/erc721/model"
chainModel "github.com/jason-bateman/go-erc-standard-contract/model"
"github.com/jason-bateman/go-erc-standard-contract/utils"
"log"
"math"
"math/big"
"strings"
"time"
)
type contractTransactor struct {
client *ethclient.Client // client
key *ecdsa.PrivateKey
transactor *erc721.StandardERC721Transactor // transactor
}
type contractCaller struct {
client *ethclient.Client // client
caller *erc721.StandardERC721Caller // caller
}
type contractFilterer struct {
client *ethclient.Client // client
stepNum uint64 // step num default is 100 block
filterFuzzyAddress bool // fuzzy bind contract address(listen for the full number of matching topic events)
events []model.ContractEvent // events
filterer *erc721.StandardERC721Filterer // Filterer
}
type ContractOpts struct {
Rpc string // rpc
ContractAddr string // contract address
EnableTransactors bool // enable transactors
EnableFilter bool // enable filter
FilterStep uint64 // the step size of the block interval obtained each time
FilterFuzzyAddress bool // fuzzy bind contract address(listen for the full number of matching topic events)
}
type Contract struct {
rpc string // rpc
chainId int64 // chain id
contractAddr common.Address // contract address
enableTransactors bool // enable transactors
enableFilter bool // enable filter
transactors map[string]*contractTransactor // transactors
caller *contractCaller // caller
filter *contractFilterer // filter
}
func NewContract(ops *ContractOpts) (*Contract, error) {
var caller contractCaller
var err error
con := &Contract{}
if !common.IsHexAddress(ops.ContractAddr) {
return nil, errors.New("invalid address")
}
// 合约地址格式转换
contractAddr := common.HexToAddress(ops.ContractAddr)
// caller 初始化
caller.client, err = ethclient.Dial(ops.Rpc)
if err != nil {
return nil, err
}
chainId, err := caller.client.ChainID(context.Background())
if err != nil {
return nil, err
}
caller.caller, err = erc721.NewStandardERC721Caller(contractAddr, caller.client)
if err != nil {
return nil, err
}
// 填充返回
con.rpc = ops.Rpc
con.chainId = chainId.Int64()
con.contractAddr = contractAddr
con.enableTransactors = ops.EnableTransactors
con.enableFilter = ops.EnableFilter
con.caller = &caller
if ops.EnableFilter {
var filter contractFilterer
// filter初始化
filter.client, err = ethclient.Dial(ops.Rpc)
if err != nil {
return nil, err
}
filter.filterer, err = erc721.NewStandardERC721Filterer(contractAddr, ops.FilterFuzzyAddress, filter.client)
if err != nil {
return nil, err
}
if ops.FilterStep == 0 {
filter.stepNum = chainModel.EVENT_FILTER_STEP_NUM
} else {
filter.stepNum = ops.FilterStep
}
filter.filterFuzzyAddress = ops.FilterFuzzyAddress
con.filter = &filter
}
if ops.EnableTransactors {
con.transactors = make(map[string]*contractTransactor)
}
return con, nil
}
func (c *Contract) AddTransactors(privateKeys []string) error {
var err error
if !c.enableTransactors {
return errors.New("the transactors is not supported. check the instantiation parameters")
}
transactors := make(map[string]*contractTransactor)
for _, k := range privateKeys {
var transactor contractTransactor
transactor.client, err = ethclient.Dial(c.rpc)
if err != nil {
return err
}
transactor.key, err = crypto.HexToECDSA(k)
if err != nil {
return err
}
transactor.transactor, err = erc721.NewStandardERC721Transactor(c.contractAddr, transactor.client)
if err != nil {
return err
}
transactors[crypto.PubkeyToAddress(transactor.key.PublicKey).Hex()] = &transactor
}
c.transactors = transactors
return nil
}
func (c *Contract) AddEvents(events []model.ContractEvent) error {
if !c.enableFilter {
return errors.New("the filter is not supported. check the instantiation parameters")
}
for _, e := range events {
if c.filter.isEventSupport(e) {
c.filter.events = append(c.filter.events, e)
} else {
errMsg := fmt.Sprintf("unsupported Event:%s", model.SupportEvents[e])
return errors.New(errMsg)
}
}
return nil
}
func (c *Contract) GetCallerClient() *ethclient.Client {
return c.caller.client
}
func (c *Contract) ReadBalanceOf(owner string) (uint64, error) {
balance, err := c.caller.caller.BalanceOf(&bind.CallOpts{}, common.HexToAddress(owner))
if err != nil {
return 0, err
}
return balance.Uint64(), nil
}
func (c *Contract) ReadOwnerOf(tokenId string) (string, error) {
// 参数处理
bTokenId := utils.String2BigInt(tokenId)
owner, err := c.caller.caller.OwnerOf(&bind.CallOpts{}, bTokenId)
if err != nil {
return "", err
}
return owner.Hex(), nil
}
func (c *Contract) ReadGetApproved(tokenId string) (string, error) {
// 参数处理
bTokenId := utils.String2BigInt(tokenId)
approver, err := c.caller.caller.GetApproved(&bind.CallOpts{}, bTokenId)
if err != nil {
return "", err
}
return approver.Hex(), nil
}
func (c *Contract) ReadIsApprovedForAll(inputs *model.MethodReadIsApprovedForAllInputs) (bool, error) {
approved, err := c.caller.caller.IsApprovedForAll(&bind.CallOpts{}, common.HexToAddress(inputs.Owner), common.HexToAddress(inputs.Operator))
if err != nil {
return false, err
}
return approved, nil
}
func (c *Contract) ReadName() (string, error) {
name, err := c.caller.caller.Name(&bind.CallOpts{})
if err != nil {
return "", err
}
return name, nil
}
func (c *Contract) ReadSymbol() (string, error) {
symbol, err := c.caller.caller.Symbol(&bind.CallOpts{})
if err != nil {
return "", err
}
return symbol, nil
}
func (c *Contract) ReadTotalSupply() (uint64, error) {
totalSupply, err := c.caller.caller.TotalSupply(&bind.CallOpts{})
if err != nil {
return 0, err
}
return totalSupply.Uint64(), nil
}
func (c *Contract) ReadTokenURI(id string) (string, error) {
// 参数处理
tokenId := utils.String2BigInt(id)
uri, err := c.caller.caller.TokenURI(&bind.CallOpts{}, tokenId)
if err != nil {
return "", err
}
return uri, nil
}
func (c *Contract) ReadTokenByIndex(id string) (uint64, error) {
// 参数处理
tokenId := utils.String2BigInt(id)
index, err := c.caller.caller.TokenByIndex(&bind.CallOpts{}, tokenId)
if err != nil {
return 0, err
}
return index.Uint64(), nil
}
func (c *Contract) ReadTokenOfOwnerByIndex(inputs *model.MethodReadTokenOfOwnerByIndexInputs) (string, error) {
tokenId, err := c.caller.caller.TokenOfOwnerByIndex(&bind.CallOpts{}, common.HexToAddress(inputs.Owner), big.NewInt(inputs.Index))
if err != nil {
return "", err
}
return tokenId.String(), nil
}
func (c *Contract) ReadSupportsInterface(interfaceId string) (bool, error) {
var idBytes4 [4]byte
if !strings.HasPrefix(interfaceId, "0x") && len(interfaceId) != 10 {
return false, errors.New("invalid parameter, please check parameter, must with hex prefix")
}
idBytes, err := hexutil.Decode(interfaceId)
if err != nil {
return false, err
}
copy(idBytes4[:], idBytes[:4])
supported, err := c.caller.caller.SupportsInterface(&bind.CallOpts{}, idBytes4)
if err != nil {
return false, err
}
return supported, nil
}
func (c *Contract) WriteSafeTransferFrom(txNonce uint64, inputs *model.MethodWriteSafeTransferFromInputs) (string, error) {
if !c.enableTransactors {
return "", errors.New("the transactors is not supported. check the instantiation parameters")
}
if !c.isTransactorExist(inputs.From) {
return "", errors.New("transactor not exist")
}
// 获取Transactor参数
opts, err := c.genTransactorOptions(inputs.From, txNonce, inputs.PayableValue)
if err != nil {
return "", err
}
// 参数处理
tokenId := utils.String2BigInt(inputs.Id)
// 提交交易
tx, err := c.transactors[inputs.From].transactor.SafeTransferFrom0(opts, common.HexToAddress(inputs.From), common.HexToAddress(inputs.To), tokenId, inputs.Data)
if err != nil {
return "", err
}
return tx.Hash().String(), nil
}
func (c *Contract) WriteSafeTransferFromWithoutData(txNonce uint64, inputs *model.MethodWriteSafeTransferFromWithoutDataInputs) (string, error) {
if !c.enableTransactors {
return "", errors.New("the transactors is not supported. check the instantiation parameters")
}
if !c.isTransactorExist(inputs.From) {
return "", errors.New("transactor not exist")
}
// 获取Transactor参数
opts, err := c.genTransactorOptions(inputs.From, txNonce, inputs.PayableValue)
if err != nil {
return "", err
}
// 参数处理
tokenId := utils.String2BigInt(inputs.Id)
// 提交交易
tx, err := c.transactors[inputs.From].transactor.SafeTransferFrom(opts, common.HexToAddress(inputs.From), common.HexToAddress(inputs.To), tokenId)
if err != nil {
return "", err
}
return tx.Hash().String(), nil
}
func (_Contract *Contract) WriteTransferFrom(txNonce uint64, inputs *model.MethodWriteTransferFromInputs) (string, error) {
if !_Contract.enableTransactors {
return "", errors.New("the transactors is not supported. check the instantiation parameters")
}
if !_Contract.isTransactorExist(inputs.From) {
return "", errors.New("transactor not exist")
}
// 获取Transactor参数
opts, err := _Contract.genTransactorOptions(inputs.From, txNonce, inputs.PayableValue)
if err != nil {
return "", err
}
// 参数处理
tokenId := utils.String2BigInt(inputs.Id)
// 提交交易
tx, err := _Contract.transactors[inputs.From].transactor.TransferFrom(opts, common.HexToAddress(inputs.From), common.HexToAddress(inputs.To), tokenId)
if err != nil {
return "", err
}
return tx.Hash().String(), nil
}
func (_Contract *Contract) WriteApprove(senderAddress string, txNonce uint64, inputs *model.MethodWriteApproveInputs) (string, error) {
if !_Contract.enableTransactors {
return "", errors.New("the transactors is not supported. check the instantiation parameters")
}
if !_Contract.isTransactorExist(senderAddress) {
return "", errors.New("transactor not exist")
}
// 获取Transactor参数
opts, err := _Contract.genTransactorOptions(senderAddress, txNonce, 0)
if err != nil {
return "", err
}
// 参数处理
tokenId := utils.String2BigInt(inputs.Id)
// 提交交易
tx, err := _Contract.transactors[senderAddress].transactor.Approve(opts, common.HexToAddress(inputs.ApprovedAddress), tokenId)
if err != nil {
return "", err
}
return tx.Hash().String(), nil
}
func (_Contract *Contract) WriteSetApprovalForAll(senderAddress string, txNonce uint64, inputs *model.MethodWriteSetApprovalForAllInputs) (string, error) {
if !_Contract.enableTransactors {
return "", errors.New("the transactors is not supported. check the instantiation parameters")
}
if !_Contract.isTransactorExist(senderAddress) {
return "", errors.New("transactor not exist")
}
// 获取Transactor参数
opts, err := _Contract.genTransactorOptions(senderAddress, txNonce, 0)
if err != nil {
return "", err
}
tx, err := _Contract.transactors[senderAddress].transactor.SetApprovalForAll(opts, common.HexToAddress(inputs.Operator), inputs.Approved)
if err != nil {
return "", err
}
return tx.Hash().String(), nil
}
func (_Contract *Contract) FilterEvents(startBlockNum uint64, stopBlockNum *uint64) ([]*chainModel.EthereumEventMessage, error) {
var events, eventsAll []*chainModel.EthereumEventMessage
if !_Contract.enableFilter {
return nil, errors.New("the filter is not supported. check the instantiation parameters")
}
latestBlockNum, err := utils.GetLatestBlockNumWithClient(_Contract.caller.client)
if err != nil {
return nil, err
}
// 如果请求结束区块大于最新区块,赋值最新区块
if latestBlockNum < *stopBlockNum {
*stopBlockNum = latestBlockNum
}
if *stopBlockNum > startBlockNum+_Contract.filter.stepNum {
errMsg := fmt.Sprintf("Max Filter step num is %d, current is %d", _Contract.filter.stepNum, *stopBlockNum-startBlockNum)
return nil, errors.New(errMsg)
}
stop := stopBlockNum
opts := &bind.FilterOpts{
Start: startBlockNum,
End: stop,
}
for _, e := range _Contract.filter.events {
switch e {
case model.EventApproval:
events, err = _Contract.eventApproval(opts)
if err != nil {
return nil, err
}
case model.EventApprovalForAll:
events, err = _Contract.eventApprovalForAll(opts)
if err != nil {
return nil, err
}
case model.EventTransfer:
events, err = _Contract.eventTransfer(opts)
if err != nil {
return nil, err
}
default:
errMsg := fmt.Sprintf("unsupported Event:%s", model.SupportEvents[e])
return nil, errors.New(errMsg)
}
if len(events) != 0 {
log.Printf("Filter for %d out %d \"%s\" messages, from %d -- %d ", _Contract.chainId, len(events), model.SupportEvents[e], startBlockNum, *stopBlockNum)
eventsAll = utils.MergeEventMessage(eventsAll, events)
}
}
if len(eventsAll) != 0 {
log.Printf("Filter for %d out total %d messages, from %d -- %d ", _Contract.chainId, len(eventsAll), startBlockNum, *stopBlockNum)
}
return eventsAll, nil
}
func (_Contract *Contract) ReleaseResource() {
//释放caller
_Contract.caller.client.Close()
//释放filter
if _Contract.enableFilter {
_Contract.filter.client.Close()
_Contract.filter.events = nil
}
// 释放transactors
if _Contract.enableTransactors {
for _, v := range _Contract.transactors {
v.client.Close()
v.key = nil
}
_Contract.transactors = make(map[string]*contractTransactor)
}
}
func (_Contract *Contract) genTransactorOptions(providerAddress string, txNonce uint64, payableValue float64) (*bind.TransactOpts, error) {
// 填充TransactOpts结构
opts, err := bind.NewKeyedTransactorWithChainID(_Contract.transactors[providerAddress].key, big.NewInt(_Contract.chainId))
if err != nil {
return nil, err
}
// 自定义nonce配置
if txNonce > 0 {
opts.Nonce = big.NewInt(int64(txNonce))
}
// 支付Native货币数量
if payableValue > 0 {
decimal := big.NewFloat(math.Pow(10, 18))
convertPayableValue, _ := new(big.Float).Mul(decimal, big.NewFloat(payableValue)).Int(&big.Int{})
opts.Value = convertPayableValue
}
//自定义gas limit
opts.GasLimit = chainModel.TRANSCATION_MAX_GAS_LIMINT
// 获取网络手续费
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(3)*time.Second)
defer cancel()
gasPrice, err := _Contract.transactors[providerAddress].client.SuggestGasPrice(ctx)
if err != nil {
return nil, err
}
opts.GasPrice = gasPrice
return opts, nil
}
func (_Contract *Contract) eventApproval(opts *bind.FilterOpts) ([]*chainModel.EthereumEventMessage, error) {
var events []*chainModel.EthereumEventMessage
iter, err := _Contract.filter.filterer.FilterApproval(opts, []common.Address{}, []common.Address{}, []*big.Int{})
if err != nil {
return nil, err
}
defer func() {
_ = iter.Close()
}()
for {
if iter.Next() {
message := &model.Event4Approval{
Owner: iter.Event.Owner.Hex(),
Approved: iter.Event.Approved.Hex(),
TokenId: iter.Event.TokenId.String(),
}
messageBytes, err := json.Marshal(message)
if err != nil {
return nil, err
}
event := _Contract.eventMsgCommonFill(model.EventApproval, iter.Event.Raw, string(messageBytes))
log.Printf("Filter for %d: ApprovalForAll get a new event :%+v", _Contract.chainId, event)
events = append(events, event)
} else {
break
}
}
return events, nil
}
func (_Contract *Contract) eventApprovalForAll(opts *bind.FilterOpts) ([]*chainModel.EthereumEventMessage, error) {
var events []*chainModel.EthereumEventMessage
iter, err := _Contract.filter.filterer.FilterApprovalForAll(opts, []common.Address{}, []common.Address{})
if err != nil {
return nil, err
}
defer func() {
_ = iter.Close()
}()
for {
if iter.Next() {
message := &model.Event4ApprovalForAll{
Account: iter.Event.Owner.Hex(),
Operator: iter.Event.Operator.Hex(),
Approved: iter.Event.Approved,
}
messageBytes, err := json.Marshal(message)
if err != nil {
return nil, err
}
event := _Contract.eventMsgCommonFill(model.EventApprovalForAll, iter.Event.Raw, string(messageBytes))
log.Printf("Filter for %d: ApprovalForAll get a new event :%+v", _Contract.chainId, event)
events = append(events, event)
} else {
break
}
}
return events, nil
}
func (_Contract *Contract) eventTransfer(opts *bind.FilterOpts) ([]*chainModel.EthereumEventMessage, error) {
var events []*chainModel.EthereumEventMessage
iter, err := _Contract.filter.filterer.FilterTransfer(opts, []common.Address{}, []common.Address{}, []*big.Int{})
if err != nil {
return nil, err
}
defer func() {
_ = iter.Close()
}()
for {
if iter.Next() {
message := &model.Event4Transfer{
From: iter.Event.From.Hex(),
To: iter.Event.To.Hex(),
TokenId: iter.Event.TokenId.String(),
}
messageBytes, err := json.Marshal(message)
if err != nil {
return nil, err
}
event := _Contract.eventMsgCommonFill(model.EventTransfer, iter.Event.Raw, string(messageBytes))
log.Printf("Filter for %d: TransferSingle get a new event :%+v", _Contract.chainId, event)
events = append(events, event)
} else {
break
}
}
return events, nil
}
func (_Contract *Contract) eventMsgCommonFill(event model.ContractEvent, logs types.Log, msg string) *chainModel.EthereumEventMessage {
commonMsg := &chainModel.EthereumEventMessage{
ChainId: _Contract.chainId,
Contract: _Contract.contractAddr.Hex(),
BlockNumber: logs.BlockNumber,
TxId: logs.TxHash.String(),
BlockIndex: uint64(logs.Index),
Event: model.SupportEvents[event],
Message: msg,
}
return commonMsg
}
func (_Contract *Contract) isTransactorExist(addr string) bool {
_, ok := _Contract.transactors[addr]
return ok
}
func (_ContractFilterer *contractFilterer) isEventSupport(event model.ContractEvent) bool {
_, ok := model.SupportEvents[event]
return ok
}