-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrpc.go
800 lines (734 loc) · 21.2 KB
/
rpc.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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
package go_eth_client
import (
"context"
"crypto/ecdsa"
"encoding/json"
"fmt"
"math/big"
"math/rand"
"strings"
"time"
"github.com/Rican7/retry"
"github.com/Rican7/retry/backoff"
"github.com/Rican7/retry/strategy"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/compiler"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/meshplus/bitxhub-kit/log"
"github.com/meshplus/go-eth-client/utils"
)
var _ Client = (*EthRPC)(nil)
const (
defaultPoolSize = 6 // 连接池默认大小
defaultPoolInit = 4 // 连接池默认初始连接数
defaultPoolIdleTimeout = 1 * time.Hour // 连接池中连接的默认闲置时间阈值
defaultCallTimeout = 6 * time.Second // 默认请求超时时间
waitReceipt = 300 * time.Millisecond
)
type EthRPC struct {
urls []string // bitxhub各节点的URL
privateKey *ecdsa.PrivateKey // 用于交易签名的默认私钥
cid *big.Int // ChainID
pool *Pool // 客户端连接池
poolSize int // 连接池大小
poolInit int // 连接池初始连接数
poolIdleTimeout time.Duration // 连接池中连接的闲置时间阈值
callTimeout time.Duration // 请求的超时时间(包括等待连接和json-rpc请求的超时时间总和)
logger Logger
}
type Option func(*EthRPC)
func WithUrls(urls []string) Option {
return func(config *EthRPC) {
config.urls = urls
}
}
func WithPriKey(pk *ecdsa.PrivateKey) Option {
return func(config *EthRPC) {
config.privateKey = pk
}
}
func WithPoolSize(poolSize int) Option {
return func(config *EthRPC) {
config.poolSize = poolSize
}
}
func WithPoolInit(poolInit int) Option {
return func(config *EthRPC) {
config.poolInit = poolInit
}
}
func WithPoolIdleTimeout(t time.Duration) Option {
return func(config *EthRPC) {
config.poolIdleTimeout = t
}
}
func WithCallTimeout(t time.Duration) Option {
return func(config *EthRPC) {
config.callTimeout = t
}
}
func WithLogger(logger Logger) Option {
return func(config *EthRPC) {
config.logger = logger
}
}
func New(opts ...Option) (*EthRPC, error) {
// initialize config
rpc := &EthRPC{}
for _, opt := range opts {
opt(rpc)
}
// check and set config
if len(rpc.urls) == 0 {
return nil, fmt.Errorf("bitxhub urls cant not be 0")
}
if rpc.poolSize <= 0 {
rpc.poolSize = defaultPoolSize
}
if rpc.poolInit <= 0 {
rpc.poolInit = defaultPoolInit
}
if rpc.poolIdleTimeout <= 0 {
rpc.poolIdleTimeout = defaultPoolIdleTimeout
}
if rpc.callTimeout <= 0 {
rpc.callTimeout = defaultCallTimeout
}
if rpc.logger == nil {
rpc.logger = log.NewWithModule("go-eth-client")
}
// generate other config
var err error
rpc.pool, err = NewPool(rpc.newClient, rpc.poolInit, rpc.poolSize, rpc.poolIdleTimeout)
if err != nil {
return nil, err
}
if err := rpc.wrapper(func(ctx context.Context, client *clientConn) error {
rpc.cid, err = client.conn.ChainID(ctx)
if err != nil {
return err
}
return nil
}); err != nil {
return nil, err
}
return rpc, nil
}
func (rpc *EthRPC) newClient() (*ethclient.Client, string, error) {
randIndex := rand.New(rand.NewSource(time.Now().UnixNano())).Intn(len(rpc.urls))
// Dial can't create connection, only create an instance
client, err := ethclient.Dial(rpc.urls[randIndex])
if err != nil {
rpc.logger.Errorf("Dial url %s failed", rpc.urls[randIndex])
return nil, "", fmt.Errorf("dial url %s failed", rpc.urls[randIndex])
}
rpc.logger.Debugf("Create instance that dial with %s successfully", rpc.urls[randIndex])
return client, rpc.urls[randIndex], nil
}
func (rpc *EthRPC) putClient(client *clientConn) {
if err := rpc.pool.Put(client); err != nil {
rpc.logger.Errorf("Put into pool err: %s", err)
}
}
func (rpc *EthRPC) wrapper(f func(ctx context.Context, client *clientConn) error) error {
var otherErr error
if err := retry.Retry(func(attempt uint) error {
ctx, cancel := context.WithTimeout(context.Background(), rpc.callTimeout)
defer cancel()
client, err := rpc.pool.Get(ctx)
if err != nil {
return err
}
defer rpc.putClient(client)
if err := retry.Retry(func(attempt uint) error {
ctx, cancel := context.WithTimeout(context.Background(), rpc.callTimeout)
defer cancel()
if err := f(ctx, client); err != nil {
rpc.logger.Warning(err.Error())
// if error is 'connection refused', retry
if strings.Contains(err.Error(), "connection refused") {
return err
}
otherErr = err
}
return nil
}, strategy.Wait(200*time.Millisecond), strategy.Limit(3)); err != nil {
// if still failed after retry 5 times, close the client
client.Close()
rpc.logger.Errorf("close connection with %s", client.url)
return err
}
return nil
}, strategy.Wait(1*time.Second), strategy.Limit(uint(2*len(rpc.urls)))); err != nil {
return err
}
if otherErr != nil {
return otherErr
}
return nil
}
func (rpc *EthRPC) EthEstimateGas(msg ethereum.CallMsg) (uint64, error) {
var estimateGas uint64
if err := rpc.wrapper(func(ctx context.Context, client *clientConn) error {
var err error
estimateGas, err = client.conn.EstimateGas(ctx, msg)
if err != nil {
return err
}
return nil
}); err != nil {
return 0, err
}
return estimateGas, nil
}
func (rpc *EthRPC) EthGetTransactionByHash(txHash common.Hash) (*types.Transaction, error) {
var tx *types.Transaction
if err := rpc.wrapper(func(ctx context.Context, client *clientConn) error {
var err error
tx, _, err = client.conn.TransactionByHash(ctx, txHash)
if err != nil {
return err
}
return nil
}); err != nil {
return nil, err
}
return tx, nil
}
func (rpc *EthRPC) EthGetTransactionByBlockHashAndIndex(blockHash common.Hash, index int) (*types.Transaction, error) {
var tx *types.Transaction
if err := rpc.wrapper(func(ctx context.Context, client *clientConn) error {
var err error
tx, err = client.conn.TransactionInBlock(ctx, blockHash, uint(index))
if err != nil {
return err
}
return nil
}); err != nil {
return nil, err
}
return tx, nil
}
func (rpc *EthRPC) EthGetTransactionByBlockNumberAndIndex(blockNumber *big.Int, index int) (*types.Transaction, error) {
var block *types.Block
if err := rpc.wrapper(func(ctx context.Context, client *clientConn) error {
var err error
block, err = client.conn.BlockByNumber(ctx, blockNumber)
if err != nil {
return err
}
return nil
}); err != nil {
return nil, err
}
return block.Transactions()[index], nil
}
func (rpc *EthRPC) EthGetBlockTransactionCountByHash(blockHash common.Hash) (uint64, error) {
var num uint
if err := rpc.wrapper(func(ctx context.Context, client *clientConn) error {
var err error
num, err = client.conn.TransactionCount(ctx, blockHash)
if err != nil {
return err
}
return nil
}); err != nil {
return 0, err
}
return uint64(num), nil
}
func (rpc *EthRPC) EthGetBlockTransactionCountByNumber(blockNumber *big.Int) (uint64, error) {
var block *types.Block
if err := rpc.wrapper(func(ctx context.Context, client *clientConn) error {
var err error
block, err = client.conn.BlockByNumber(ctx, blockNumber)
if err != nil {
return err
}
return nil
}); err != nil {
return 0, err
}
return uint64(block.Transactions().Len()), nil
}
func (rpc *EthRPC) Compile(sourceFiles ...string) (*CompileResult, error) {
contracts, err := compiler.CompileSolidity("", sourceFiles...)
if err != nil {
return nil, fmt.Errorf("compile contract: %w", err)
}
var abis, bins, names []string
for name, contract := range contracts {
contractAbi, err := json.Marshal(contract.Info.AbiDefinition)
if err != nil {
return nil, fmt.Errorf("failed to parse ABIs from compiler output: %w", err)
}
abis = append(abis, string(contractAbi))
bins = append(bins, contract.Code)
names = append(names, name)
}
return &CompileResult{
Abi: abis,
Bin: bins,
Names: names,
}, nil
}
func (rpc *EthRPC) DeployByCode(privKey *ecdsa.PrivateKey, abi abi.ABI, code string, args []interface{}, opts ...TransactionOption) (string, uint64, error) {
// set transaction options
transactionOpts := &TransactionOptions{}
for _, opt := range opts {
opt(transactionOpts)
}
txOpts, err := bind.NewKeyedTransactorWithChainID(privKey, rpc.cid)
if err != nil {
return "", 0, err
}
txOpts.GasPrice = transactionOpts.GasPrice
if transactionOpts.Nonce == 0 {
nonce, err := rpc.EthGetTransactionCount(crypto.PubkeyToAddress(privKey.PublicKey), nil)
if err != nil {
return "", 0, err
}
transactionOpts.Nonce = nonce
}
txOpts.Nonce = big.NewInt(int64(transactionOpts.Nonce))
if transactionOpts.GasLimit == 0 {
txOpts.GasLimit = 100000000
} else {
txOpts.GasLimit = transactionOpts.GasLimit
}
var (
address common.Address
tx *types.Transaction
receipt *types.Receipt
)
// deploy contract
if err := rpc.wrapper(func(ctx context.Context, client *clientConn) error {
var err error
address, tx, _, err = bind.DeployContract(txOpts, abi, common.FromHex(code), client.conn, args...)
if err != nil {
return err
}
time.Sleep(waitReceipt)
if err := retry.Retry(func(attempt uint) error {
receipt, err = client.conn.TransactionReceipt(ctx, tx.Hash())
if err != nil {
return err
}
return nil
}, strategy.Limit(5), strategy.Backoff(backoff.Fibonacci(200*time.Millisecond))); err != nil {
return err
}
return nil
}); err != nil {
return "", 0, err
}
if receipt.Status == types.ReceiptStatusFailed {
return "", 0, fmt.Errorf("deploy contract failed, tx hash is: %s", tx.Hash())
}
return address.String(), receipt.BlockNumber.Uint64(), nil
}
func (rpc *EthRPC) Deploy(privKey *ecdsa.PrivateKey, result *CompileResult, args []interface{}, opts ...TransactionOption) ([]string, error) {
if len(result.Abi) == 0 || len(result.Bin) == 0 || len(result.Names) == 0 {
return nil, fmt.Errorf("empty contract")
}
txOpts, err := rpc.generateTxOpts(privKey, opts...)
if err != nil {
return nil, err
}
addresses := make([]string, 0)
for i, bin := range result.Bin {
if bin == "0x" {
continue
}
parsed, err := abi.JSON(strings.NewReader(result.Abi[i]))
if err != nil {
return nil, err
}
code := strings.TrimPrefix(strings.TrimSpace(bin), "0x")
var address common.Address
// deploy contract
if err := rpc.wrapper(func(ctx context.Context, client *clientConn) error {
var err error
address, _, _, err = bind.DeployContract(txOpts, parsed, common.FromHex(code), client.conn, args...)
if err != nil {
return err
}
return nil
}); err != nil {
return nil, err
}
addresses = append(addresses, address.String())
}
return addresses, nil
}
func (rpc *EthRPC) DeployWithReceipt(privKey *ecdsa.PrivateKey, result *CompileResult, args []interface{},
opts ...TransactionOption) ([]string, error) {
if len(result.Abi) == 0 || len(result.Bin) == 0 || len(result.Names) == 0 {
return nil, fmt.Errorf("empty contract")
}
txOpts, err := rpc.generateTxOpts(privKey, opts...)
if err != nil {
return nil, err
}
addresses := make([]string, 0)
for i, bin := range result.Bin {
if bin == "0x" {
continue
}
parsed, err := abi.JSON(strings.NewReader(result.Abi[i]))
if err != nil {
return nil, err
}
code := strings.TrimPrefix(strings.TrimSpace(bin), "0x")
var (
address common.Address
tx *types.Transaction
receipt *types.Receipt
)
// deploy contract
if err := rpc.wrapper(func(ctx context.Context, client *clientConn) error {
var err error
address, tx, _, err = bind.DeployContract(txOpts, parsed, common.FromHex(code), client.conn, args...)
if err != nil {
return err
}
time.Sleep(waitReceipt)
if err := retry.Retry(func(attempt uint) error {
receipt, err = client.conn.TransactionReceipt(ctx, tx.Hash())
if err != nil {
return err
}
return nil
}, strategy.Limit(5), strategy.Backoff(backoff.Fibonacci(200*time.Millisecond))); err != nil {
return err
}
return nil
}); err != nil {
return nil, err
}
if receipt.Status == types.ReceiptStatusFailed {
return nil, fmt.Errorf("deploy contract failed, tx hash is: %s", tx.Hash())
}
addresses = append(addresses, address.String())
}
return addresses, nil
}
func (rpc *EthRPC) generateTxOpts(privKey *ecdsa.PrivateKey, opts ...TransactionOption) (*bind.TransactOpts, error) {
transactionOpts := &TransactionOptions{}
// set transaction options
for _, opt := range opts {
opt(transactionOpts)
}
// load privateKey
if transactionOpts.PrivateKey != nil {
privKey = transactionOpts.PrivateKey
}
txOpts, err := bind.NewKeyedTransactorWithChainID(privKey, rpc.cid)
if err != nil {
return nil, err
}
txOpts.GasPrice = transactionOpts.GasPrice
if transactionOpts.Nonce == 0 {
nonce, err := rpc.EthGetTransactionCount(crypto.PubkeyToAddress(privKey.PublicKey), nil)
if err != nil {
return nil, err
}
transactionOpts.Nonce = nonce
}
txOpts.Nonce = big.NewInt(int64(transactionOpts.Nonce))
if transactionOpts.GasLimit == 0 {
txOpts.GasLimit = 100000000
} else {
txOpts.GasLimit = transactionOpts.GasLimit
}
return txOpts, nil
}
func (rpc *EthRPC) EthCall(contractAbi *abi.ABI, address string, method string, args []interface{}) ([]interface{}, error) {
var invokeRes []interface{}
to := common.HexToAddress(address)
packed, err := contractAbi.Pack(method, args...)
if err != nil {
return nil, err
}
msg := ethereum.CallMsg{To: &to, Data: packed}
if !contractAbi.Methods[method].IsConstant() {
return nil, fmt.Errorf("EthCall function need the method is read-only")
}
var output []byte
if err := rpc.wrapper(func(ctx context.Context, client *clientConn) error {
var err error
output, err = client.conn.CallContract(ctx, msg, nil)
if err != nil {
return err
}
return nil
}); err != nil {
return nil, err
}
if err != nil {
return nil, err
}
if len(output) == 0 {
if code, err := rpc.EthGetCode(to, nil); err != nil {
return nil, err
} else if code == "0x" {
return nil, fmt.Errorf("no code at your contract addresss")
}
return nil, fmt.Errorf("output is empty")
}
// unpack result for display
invokeRes, err = utils.UnpackOutput(contractAbi, method, string(output))
if err != nil {
return nil, err
}
return invokeRes, nil
}
func (rpc *EthRPC) Invoke(privKey *ecdsa.PrivateKey, contractAbi *abi.ABI, address string, method string,
args []interface{}, opts ...TransactionOption) ([]interface{}, error) {
return rpc.invoke(false, privKey, contractAbi, address, method, args, opts...)
}
func (rpc *EthRPC) InvokeWithReceipt(privKey *ecdsa.PrivateKey, contractAbi *abi.ABI, address string, method string,
args []interface{}, opts ...TransactionOption) ([]interface{}, error) {
return rpc.invoke(true, privKey, contractAbi, address, method, args, opts...)
}
func (rpc *EthRPC) invoke(withReceipt bool, privKey *ecdsa.PrivateKey, contractAbi *abi.ABI, address string,
method string, args []interface{}, opts ...TransactionOption) ([]interface{}, error) {
var invokeRes []interface{}
txOpts := &TransactionOptions{}
for _, opt := range opts {
opt(txOpts)
}
from := crypto.PubkeyToAddress(privKey.PublicKey)
to := common.HexToAddress(address)
packed, err := contractAbi.Pack(method, args...)
if err != nil {
return nil, err
}
msg := ethereum.CallMsg{From: from, To: &to, Data: packed}
if contractAbi.Methods[method].IsConstant() {
var output []byte
if err := rpc.wrapper(func(ctx context.Context, client *clientConn) error {
var err error
output, err = client.conn.CallContract(ctx, msg, nil)
if err != nil {
return err
}
return nil
}); err != nil {
return nil, err
}
if len(output) == 0 {
if code, err := rpc.EthGetCode(to, nil); err != nil {
return nil, err
} else if code == "0x" {
return nil, fmt.Errorf("no code at your contract addresss")
}
return nil, fmt.Errorf("output is empty")
}
// unpack result for display
invokeRes, err = utils.UnpackOutput(contractAbi, method, string(output))
if err != nil {
return nil, err
}
return invokeRes, nil
}
if txOpts.Nonce == 0 {
nonce, err := rpc.EthGetTransactionCount(crypto.PubkeyToAddress(privKey.PublicKey), nil)
if err != nil {
return nil, err
}
txOpts.Nonce = nonce
}
if txOpts.GasLimit == 0 {
txOpts.GasLimit = 1000000
}
if txOpts.GasPrice == nil {
price, err := rpc.EthGasPrice()
if err != nil {
return nil, err
}
txOpts.GasPrice = price
}
tx := utils.NewTransaction(txOpts.Nonce, to, txOpts.GasLimit, txOpts.GasPrice, packed, nil)
if withReceipt {
receipt, err := rpc.EthSendTransactionWithReceipt(privKey, tx)
if err != nil {
return nil, fmt.Errorf("invoke err:%s", err)
}
return []interface{}{receipt}, nil
}
hash, err := rpc.EthSendTransaction(privKey, tx)
if err != nil {
return nil, fmt.Errorf("invoke err:%s", err)
}
return []interface{}{hash}, nil
}
func (rpc *EthRPC) EthGasPrice() (*big.Int, error) {
var price *big.Int
if err := rpc.wrapper(func(ctx context.Context, client *clientConn) error {
var err error
price, err = client.conn.SuggestGasPrice(ctx)
if err != nil {
return err
}
return nil
}); err != nil {
return nil, err
}
return price, nil
}
func (rpc *EthRPC) EthGetTransactionReceipt(hash common.Hash) (*types.Receipt, error) {
var (
receipt *types.Receipt
err error
)
if err := rpc.wrapper(func(ctx context.Context, client *clientConn) error {
if err := retry.Retry(func(attempt uint) error {
receipt, err = client.conn.TransactionReceipt(ctx, hash)
if err != nil {
return err
}
return nil
}, strategy.Limit(5), strategy.Backoff(backoff.Fibonacci(200*time.Millisecond))); err != nil {
return err
}
return nil
}); err != nil {
return nil, err
}
return receipt, nil
}
func (rpc *EthRPC) EthGetTransactionCount(account common.Address, blockNumber *big.Int) (uint64, error) {
var nonce uint64
if err := rpc.wrapper(func(ctx context.Context, client *clientConn) error {
var err error
nonce, err = client.conn.NonceAt(ctx, account, blockNumber)
if err != nil {
return err
}
return nil
}); err != nil {
return 0, err
}
return nonce, nil
}
func (rpc *EthRPC) EthGetBlockByNumber(blockNumber *big.Int, fullTx bool) (*types.Block, error) {
var (
err error
block *types.Block
)
if err := rpc.wrapper(func(ctx context.Context, client *clientConn) error {
if !fullTx {
blockHeader, err := client.conn.HeaderByNumber(ctx, blockNumber)
if err != nil {
return err
}
block = types.NewBlockWithHeader(blockHeader)
return nil
}
block, err = client.conn.BlockByNumber(ctx, blockNumber)
if err != nil {
return err
}
return nil
}); err != nil {
return nil, err
}
return block, nil
}
func (rpc *EthRPC) EthGetBalance(account common.Address, blockNumber *big.Int) (*big.Int, error) {
var balance *big.Int
if err := rpc.wrapper(func(ctx context.Context, client *clientConn) error {
var err error
balance, err = client.conn.BalanceAt(ctx, account, blockNumber)
if err != nil {
return err
}
return nil
}); err != nil {
return nil, err
}
return balance, nil
}
func (rpc *EthRPC) EthSendTransaction(privKey *ecdsa.PrivateKey, transaction *types.Transaction) (common.Hash, error) {
signTx, err := types.SignTx(transaction, types.NewEIP155Signer(rpc.cid), privKey)
if err != nil {
return common.Hash{}, err
}
if err := rpc.wrapper(func(ctx context.Context, client *clientConn) error {
err := client.conn.SendTransaction(ctx, signTx)
if err != nil {
return err
}
return nil
}); err != nil {
return common.Hash{}, err
}
return signTx.Hash(), nil
}
func (rpc *EthRPC) EthSendRawTransaction(transaction *types.Transaction) (common.Hash, error) {
if err := rpc.wrapper(func(ctx context.Context, client *clientConn) error {
err := client.conn.SendTransaction(ctx, transaction)
if err != nil {
return err
}
return nil
}); err != nil {
return common.Hash{}, err
}
return transaction.Hash(), nil
}
func (rpc *EthRPC) EthSendTransactionWithReceipt(privKey *ecdsa.PrivateKey, transaction *types.Transaction) (*types.Receipt, error) {
hash, err := rpc.EthSendTransaction(privKey, transaction)
if err != nil {
return nil, err
}
time.Sleep(waitReceipt)
receipt, err := rpc.EthGetTransactionReceipt(hash)
if err != nil {
return nil, err
}
return receipt, nil
}
func (rpc *EthRPC) EthSendRawTransactionWithReceipt(transaction *types.Transaction) (*types.Receipt, error) {
hash, err := rpc.EthSendRawTransaction(transaction)
if err != nil {
return nil, err
}
time.Sleep(waitReceipt)
receipt, err := rpc.EthGetTransactionReceipt(hash)
if err != nil {
return nil, err
}
return receipt, nil
}
func (rpc *EthRPC) EthGetCode(account common.Address, blockNumber *big.Int) (string, error) {
var code []byte
err := rpc.wrapper(func(ctx context.Context, client *clientConn) error {
var err error
code, err = client.conn.CodeAt(ctx, account, blockNumber)
if err != nil {
return err
}
return nil
})
if err != nil || len(code) == 0 {
return "0x", err
}
return common.Bytes2Hex(code), nil
}
func (rpc *EthRPC) EthGetChainId() *big.Int {
return rpc.cid
}
func (rpc *EthRPC) Stop() {
if rpc.pool == nil {
return
}
rpc.pool.Close()
rpc.pool = nil
}