/
ethereum.go
1689 lines (1499 loc) · 58.2 KB
/
ethereum.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
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package blockchain
// Contains implementations for multi and single node ethereum clients
import (
"bytes"
"context"
"crypto/ecdsa"
"encoding/hex"
"errors"
"fmt"
"math/big"
"regexp"
"strconv"
"strings"
"sync"
"time"
"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/hexutil"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/rpc"
"github.com/rs/zerolog"
"go.uber.org/atomic"
"golang.org/x/sync/errgroup"
"github.com/smartcontractkit/chainlink-testing-framework/k8s/environment"
"github.com/smartcontractkit/chainlink-testing-framework/utils/conversions"
)
const MaxTimeoutForFinality = 15 * time.Minute
// EthereumClient wraps the client and the BlockChain network to interact with an EVM based Blockchain
type EthereumClient struct {
ID int
Client *ethclient.Client
rawRPC *rpc.Client
NetworkConfig EVMNetwork
Wallets []*EthereumWallet
DefaultWallet *EthereumWallet
NonceSettings *NonceSettings
FinalizedHeader atomic.Pointer[FinalizedHeader]
headerSubscriptions map[string]HeaderEventSubscription
subscriptionMutex *sync.Mutex
queueTransactions bool
gasStats *GasStats
connectionIssueCh chan time.Time
connectionRestoredCh chan time.Time
doneChan chan struct{}
l zerolog.Logger
subscriptionWg sync.WaitGroup
}
// newEVMClient creates an EVM client for a single node/URL
func newEVMClient(networkSettings EVMNetwork, logger zerolog.Logger) (EVMClient, error) {
logger.Info().
Str("Name", networkSettings.Name).
Str("URL", networkSettings.URL).
Int64("Chain ID", networkSettings.ChainID).
Bool("Simulated", networkSettings.Simulated).
Bool("Supports EIP-1559", networkSettings.SupportsEIP1559).
Bool("Finality Tag", networkSettings.FinalityTag).
Msg("Connecting client")
cl, err := ethclient.Dial(networkSettings.URL)
if err != nil {
return nil, err
}
raw, err := rpc.Dial(networkSettings.URL)
if err != nil {
return nil, err
}
ec := &EthereumClient{
NetworkConfig: networkSettings,
Client: cl,
rawRPC: raw,
Wallets: make([]*EthereumWallet, 0),
headerSubscriptions: map[string]HeaderEventSubscription{},
subscriptionMutex: &sync.Mutex{},
queueTransactions: false,
connectionIssueCh: make(chan time.Time, 100), // buffered to prevent blocking, size is probably overkill, but some tests might not care
connectionRestoredCh: make(chan time.Time, 100),
doneChan: make(chan struct{}),
l: logger,
}
if ec.NetworkConfig.Simulated {
ec.NonceSettings = newNonceSettings()
} else { // un-simulated chain means potentially running tests in parallel, need to share nonces
ec.NonceSettings = useGlobalNonceManager(ec.GetChainID())
}
if err := ec.LoadWallets(networkSettings); err != nil {
return nil, err
}
ec.gasStats = NewGasStats(ec.ID)
err = ec.subscribeToNewHeaders()
if err != nil {
return nil, err
}
// Check if the chain supports EIP-1559
// https://eips.ethereum.org/EIPS/eip-1559
if networkSettings.SupportsEIP1559 {
ec.l.Debug().Msg("Network supports EIP-1559, using Dynamic transactions")
} else {
ec.l.Debug().Msg("Network does NOT support EIP-1559, using Legacy transactions")
}
return wrapSingleClient(networkSettings, ec), nil
}
// SyncNonce sets the NonceMu and Nonces value based on existing EVMClient
// it ensures the instance of EthereumClient is synced with passed EVMClient's nonce updates.
func (e *EthereumClient) SyncNonce(c EVMClient) {
n := c.GetNonceSetting()
n.NonceMu.Lock()
defer n.NonceMu.Unlock()
e.NonceSettings.NonceMu = n.NonceMu
e.NonceSettings.Nonces = n.Nonces
}
// Get returns the underlying client type to be used generically across the framework for switching
// network types
func (e *EthereumClient) Get() interface{} {
return e
}
// GetNetworkName retrieves the ID of the network that the client interacts with
func (e *EthereumClient) GetNetworkName() string {
return e.NetworkConfig.Name
}
// NetworkSimulated returns true if the network is a simulated geth instance, false otherwise
func (e *EthereumClient) NetworkSimulated() bool {
return e.NetworkConfig.Simulated
}
func (e *EthereumClient) GetNonceSetting() NonceSettings {
e.NonceSettings.NonceMu.Lock()
defer e.NonceSettings.NonceMu.Unlock()
return NonceSettings{
NonceMu: e.NonceSettings.NonceMu,
Nonces: e.NonceSettings.Nonces,
}
}
// GetChainID retrieves the ChainID of the network that the client interacts with
func (e *EthereumClient) GetChainID() *big.Int {
return big.NewInt(e.NetworkConfig.ChainID)
}
// GetClients not used, only applicable to EthereumMultinodeClient
func (e *EthereumClient) GetClients() []EVMClient {
return []EVMClient{e}
}
// DefaultWallet returns the default wallet for the network
func (e *EthereumClient) GetDefaultWallet() *EthereumWallet {
return e.DefaultWallet
}
// DefaultWallet returns the default wallet for the network
func (e *EthereumClient) GetWallets() []*EthereumWallet {
return e.Wallets
}
// DefaultWallet returns the default wallet for the network
func (e *EthereumClient) GetNetworkConfig() *EVMNetwork {
return &e.NetworkConfig
}
// SetID sets client id, only used for multi-node networks
func (e *EthereumClient) SetID(id int) {
e.ID = id
}
// SetDefaultWallet sets default wallet
func (e *EthereumClient) SetDefaultWallet(num int) error {
if num >= len(e.GetWallets()) {
return fmt.Errorf("no wallet #%d found for default client", num)
}
e.DefaultWallet = e.Wallets[num]
return nil
}
// SetWallets sets all wallets to be used by the client
func (e *EthereumClient) SetWallets(wallets []*EthereumWallet) {
e.Wallets = wallets
}
// LoadWallets loads wallets from config
func (e *EthereumClient) LoadWallets(cfg EVMNetwork) error {
pkStrings := cfg.PrivateKeys
for _, pks := range pkStrings {
w, err := NewEthereumWallet(pks)
if err != nil {
return err
}
e.Wallets = append(e.Wallets, w)
}
if len(e.Wallets) == 0 {
return fmt.Errorf("no private keys found to load wallets")
}
e.DefaultWallet = e.Wallets[0]
return nil
}
// BalanceAt returns the ETH balance of the specified address
func (e *EthereumClient) BalanceAt(ctx context.Context, address common.Address) (*big.Int, error) {
return e.Client.BalanceAt(ctx, address, nil)
}
// SwitchNode not used, only applicable to EthereumMultinodeClient
func (e *EthereumClient) SwitchNode(_ int) error {
return nil
}
// HeaderHashByNumber gets header hash by block number
func (e *EthereumClient) HeaderHashByNumber(ctx context.Context, bn *big.Int) (string, error) {
h, err := e.HeaderByNumber(ctx, bn)
if err != nil {
return "", err
}
return h.Hash.String(), nil
}
// HeaderTimestampByNumber gets header timestamp by number
func (e *EthereumClient) HeaderTimestampByNumber(ctx context.Context, bn *big.Int) (uint64, error) {
h, err := e.HeaderByNumber(ctx, bn)
if err != nil {
return 0, err
}
return uint64(h.Timestamp.UTC().Unix()), nil
}
// BlockNumber gets latest block number
func (e *EthereumClient) LatestBlockNumber(ctx context.Context) (uint64, error) {
bn, err := e.Client.BlockNumber(ctx)
if err != nil {
return 0, err
}
return bn, nil
}
func (e *EthereumClient) SendTransaction(ctx context.Context, tx *types.Transaction) error {
// for instant txs, wait for permission to go
if e.NetworkConfig.MinimumConfirmations <= 0 {
fromAddr, err := types.Sender(types.LatestSignerForChainID(tx.ChainId()), tx)
if err != nil {
return err
}
<-e.NonceSettings.registerInstantTransaction(fromAddr.Hex(), tx.Nonce())
}
return e.Client.SendTransaction(ctx, tx)
}
// Fund sends some ETH to an address using the default wallet
func (e *EthereumClient) Fund(
toAddress string,
amount *big.Float,
gasEstimations GasEstimations,
) error {
privateKey, err := crypto.HexToECDSA(e.DefaultWallet.PrivateKey())
if err != nil {
return fmt.Errorf("invalid private key: %w", err)
}
to := common.HexToAddress(toAddress)
nonce, err := e.GetNonce(context.Background(), common.HexToAddress(e.DefaultWallet.Address()))
if err != nil {
return err
}
tx, err := e.NewTx(privateKey, nonce, to, conversions.EtherToWei(amount), gasEstimations)
if err != nil {
return err
}
e.l.Info().
Str("Token", "ETH").
Str("From", e.DefaultWallet.Address()).
Str("To", toAddress).
Str("Hash", tx.Hash().Hex()).
Uint64("Nonce", tx.Nonce()).
Str("Network Name", e.GetNetworkName()).
Str("Amount", amount.String()).
Uint64("Estimated Gas Cost", tx.Cost().Uint64()).
Msg("Funding Address")
if err := e.SendTransaction(context.Background(), tx); err != nil {
if strings.Contains(err.Error(), "nonce") {
err = fmt.Errorf("using nonce %d err: %w", nonce, err)
}
return err
}
return e.ProcessTransaction(tx)
}
// ReturnFunds achieves a lazy method of fund return as too many guarantees get too complex
func (e *EthereumClient) ReturnFunds(fromKey *ecdsa.PrivateKey) error {
fromAddress, err := conversions.PrivateKeyToAddress(fromKey)
if err != nil {
return err
}
nonce, err := e.Client.PendingNonceAt(context.Background(), fromAddress)
if err != nil {
return err
}
balance, err := e.Client.BalanceAt(context.Background(), fromAddress, nil)
if err != nil {
return err
}
gasLimit, err := e.Client.EstimateGas(context.Background(), ethereum.CallMsg{
From: fromAddress,
To: &e.DefaultWallet.address,
})
if err != nil {
e.l.Warn().Int("Default", 21_000).Msg("Could not estimate gas for return funds transaction, using default")
gasLimit = 21_000
}
gasPrice, err := e.Client.SuggestGasPrice(context.Background())
if err != nil {
return err
}
totalGasCost := new(big.Int).Mul(big.NewInt(0).SetUint64(gasLimit), gasPrice)
toSend := new(big.Int).Sub(balance, totalGasCost)
// Negative values can happen on large gas costs, and we can't send negative ETH
if toSend.Cmp(big.NewInt(0)) <= 0 {
e.l.Error().Str("From", fromAddress.Hex()).
Uint64("Estimated Gas Cost", totalGasCost.Uint64()).
Uint64("Balance", balance.Uint64()).
Str("To Send", toSend.String()).
Msg("Insufficient funds to return at current gas prices")
return fmt.Errorf("insufficient funds to return at current gas prices, balance: %s", balance.String())
}
tx := types.NewTransaction(nonce, e.DefaultWallet.address, toSend, gasLimit, gasPrice, nil)
signedTx, err := types.SignTx(tx, types.LatestSignerForChainID(e.GetChainID()), fromKey)
if err != nil {
return err
}
// There are several errors that can happen when trying to drain an ETH wallet.
// Ultimately, we want our money back, so we'll catch errors and react to them until we get something through,
// or an error we don't recognize.
// Try to send the money back, see if we hit any issues, and if we recognize them
fundReturnErr := e.Client.SendTransaction(context.Background(), signedTx)
// Handle overshot error
overshotRe := regexp.MustCompile(`overshot (\d+)`)
for fundReturnErr != nil && strings.Contains(fundReturnErr.Error(), "overshot") {
submatches := overshotRe.FindStringSubmatch(fundReturnErr.Error())
if len(submatches) < 1 {
return fmt.Errorf("error parsing overshot amount in error: %w", err)
}
numberString := submatches[1]
overshotAmount, err := strconv.Atoi(numberString)
if err != nil {
return err
}
toSend.Sub(toSend, big.NewInt(int64(overshotAmount)))
tx := types.NewTransaction(nonce, e.DefaultWallet.address, toSend, gasLimit, gasPrice, nil)
signedTx, err = types.SignTx(tx, types.LatestSignerForChainID(e.GetChainID()), fromKey)
if err != nil {
return err
}
fundReturnErr = e.Client.SendTransaction(context.Background(), signedTx)
}
// Handle insufficient funds error
// We don't get an overshot calculation, we just know it was too much, so subtract by 1 GWei and try again
for fundReturnErr != nil && (strings.Contains(fundReturnErr.Error(), "insufficient funds") || strings.Contains(fundReturnErr.Error(), "gas too low")) {
toSend.Sub(toSend, big.NewInt(GWei))
if toSend.Cmp(big.NewInt(0)) <= 0 {
e.l.Error().Str("From", fromAddress.Hex()).
Uint64("Estimated Gas Cost", totalGasCost.Uint64()).
Uint64("Balance", balance.Uint64()).
Str("To Send", toSend.String()).
Msg("Insufficient funds to return at current gas prices")
return fmt.Errorf("insufficient funds to return at current gas prices, balance: %s : %w", balance.String(), fundReturnErr)
}
gasLimit += 21_000 // Add 21k gas for each attempt in case gas limit is too low, this has happened in weird L2 scenarios
tx := types.NewTransaction(nonce, e.DefaultWallet.address, toSend, gasLimit, gasPrice, nil)
signedTx, err = types.SignTx(tx, types.LatestSignerForChainID(e.GetChainID()), fromKey)
if err != nil {
return err
}
fundReturnErr = e.Client.SendTransaction(context.Background(), signedTx)
}
e.l.Info().
Uint64("Funds", toSend.Uint64()).
Str("From", fromAddress.Hex()).
Str("To", e.DefaultWallet.Address()).
Msg("Returning funds to Default Wallet")
return fundReturnErr
}
// EstimateCostForChainlinkOperations calculates required amount of ETH for amountOfOperations Chainlink operations
// based on the network's suggested gas price and the chainlink gas limit. This is fairly imperfect and should be used
// as only a rough, upper-end estimate instead of an exact calculation.
// See https://ethereum.org/en/developers/docs/gas/#post-london for info on how gas calculation works
func (e *EthereumClient) EstimateCostForChainlinkOperations(amountOfOperations int) (*big.Float, error) {
bigAmountOfOperations := big.NewInt(int64(amountOfOperations))
gasPriceInWei, err := e.Client.SuggestGasPrice(context.Background())
if err != nil {
return nil, err
}
// https://ethereum.stackexchange.com/questions/19665/how-to-calculate-transaction-fee
// total gas limit = chainlink gas limit + gas limit buffer
gasLimit := e.NetworkConfig.GasEstimationBuffer + e.NetworkConfig.ChainlinkTransactionLimit
// gas cost for TX = total gas limit * estimated gas price
gasCostPerOperationWei := big.NewInt(1).Mul(big.NewInt(1).SetUint64(gasLimit), gasPriceInWei)
gasCostPerOperationETH := conversions.WeiToEther(gasCostPerOperationWei)
// total Wei needed for all TXs = total value for TX * number of TXs
totalWeiForAllOperations := big.NewInt(1).Mul(gasCostPerOperationWei, bigAmountOfOperations)
totalEthForAllOperations := conversions.WeiToEther(totalWeiForAllOperations)
e.l.Debug().
Int("Number of Operations", amountOfOperations).
Uint64("Gas Limit per Operation", gasLimit).
Str("Value per Operation (ETH)", gasCostPerOperationETH.String()).
Str("Total (ETH)", totalEthForAllOperations.String()).
Msg("Calculated ETH for Chainlink Operations")
return totalEthForAllOperations, nil
}
func (e *EthereumClient) RawJsonRPCCall(ctx context.Context, result interface{}, method string, params ...interface{}) error {
err := e.rawRPC.CallContext(ctx, &result, method, params...)
return err
}
// DeployContract acts as a general contract deployment tool to an ethereum chain
func (e *EthereumClient) DeployContract(
contractName string,
deployer ContractDeployer,
) (*common.Address, *types.Transaction, interface{}, error) {
opts, err := e.TransactionOpts(e.DefaultWallet)
if err != nil {
return nil, nil, nil, err
}
if !e.NetworkConfig.SupportsEIP1559 {
opts.GasPrice, err = e.EstimateGasPrice()
if err != nil {
return nil, nil, nil, err
}
}
contractAddress, transaction, contractInstance, err := deployer(opts, e.Client)
if err != nil {
if strings.Contains(err.Error(), "nonce") {
err = fmt.Errorf("using nonce %d err: %w", opts.Nonce.Uint64(), err)
}
return nil, nil, nil, err
}
if err = e.ProcessTransaction(transaction); err != nil {
return nil, nil, nil, err
}
e.l.Info().
Str("Contract Address", contractAddress.Hex()).
Str("Contract Name", contractName).
Str("From", e.DefaultWallet.Address()).
Str("Total Gas Cost", conversions.WeiToEther(transaction.Cost()).String()).
Str("Network Name", e.NetworkConfig.Name).
Msg("Deployed contract")
return &contractAddress, transaction, contractInstance, err
}
// LoadContract load already deployed contract instance
func (e *EthereumClient) LoadContract(contractName string, contractAddress common.Address, loader ContractLoader) (interface{}, error) {
contractInstance, err := loader(contractAddress, e.Client)
if err != nil {
return nil, err
}
e.l.Info().
Str("Contract Address", contractAddress.Hex()).
Str("Contract Name", contractName).
Str("Network Name", e.NetworkConfig.Name).
Msg("Loaded contract instance")
return contractInstance, err
}
// TransactionOpts returns the base Tx options for 'transactions' that interact with a smart contract. Since most
// contract interactions in this framework are designed to happen through abigen calls, it's intentionally quite bare.
func (e *EthereumClient) TransactionOpts(from *EthereumWallet) (*bind.TransactOpts, error) {
privateKey, err := crypto.HexToECDSA(from.PrivateKey())
if err != nil {
return nil, fmt.Errorf("invalid private key: %w", err)
}
opts, err := bind.NewKeyedTransactorWithChainID(privateKey, big.NewInt(e.NetworkConfig.ChainID))
if err != nil {
return nil, err
}
opts.From = common.HexToAddress(from.Address())
opts.Context = context.Background()
nonce, err := e.GetNonce(context.Background(), common.HexToAddress(from.Address()))
if err != nil {
return nil, err
}
opts.Nonce = big.NewInt(int64(nonce))
if e.NetworkConfig.MinimumConfirmations <= 0 { // Wait for your turn to send on an L2 chain
<-e.NonceSettings.registerInstantTransaction(from.Address(), nonce)
}
// if the gas limit is less than the default gas limit, use the default
if e.NetworkConfig.DefaultGasLimit > opts.GasLimit {
opts.GasLimit = e.NetworkConfig.DefaultGasLimit
}
if !e.NetworkConfig.SupportsEIP1559 {
opts.GasPrice, err = e.EstimateGasPrice()
if err != nil {
return nil, err
}
}
return opts, nil
}
func (e *EthereumClient) NewTx(
fromPrivateKey *ecdsa.PrivateKey,
nonce uint64,
to common.Address,
value *big.Int,
gasEstimations GasEstimations,
) (*types.Transaction, error) {
var (
tx *types.Transaction
err error
)
if e.NetworkConfig.SupportsEIP1559 {
tx, err = types.SignNewTx(fromPrivateKey, types.LatestSignerForChainID(e.GetChainID()), &types.DynamicFeeTx{
ChainID: e.GetChainID(),
Nonce: nonce,
To: &to,
Value: value,
GasTipCap: gasEstimations.GasTipCap,
GasFeeCap: gasEstimations.GasFeeCap,
Gas: gasEstimations.GasUnits,
})
if err != nil {
return nil, err
}
} else {
tx, err = types.SignNewTx(fromPrivateKey, types.LatestSignerForChainID(e.GetChainID()), &types.LegacyTx{
Nonce: nonce,
To: &to,
Value: value,
GasPrice: gasEstimations.GasPrice,
Gas: gasEstimations.GasUnits,
})
if err != nil {
return nil, err
}
}
return tx, nil
}
// MarkTxAsSent On an L2 chain, indicate the tx has been sent
func (e *EthereumClient) MarkTxAsSentOnL2(tx *types.Transaction) error {
if e.NetworkConfig.MinimumConfirmations > 0 {
return nil
}
fromAddr, err := types.Sender(types.LatestSignerForChainID(tx.ChainId()), tx)
if err != nil {
return err
}
e.NonceSettings.sentInstantTransaction(fromAddr.Hex())
return nil
}
// ProcessTransaction will queue or wait on a transaction depending on whether parallel transactions are enabled
func (e *EthereumClient) ProcessTransaction(tx *types.Transaction) error {
e.l.Trace().Str("Hash", tx.Hash().Hex()).Msg("Processing Tx")
var txConfirmer HeaderEventSubscription
if e.GetNetworkConfig().MinimumConfirmations <= 0 {
err := e.MarkTxAsSentOnL2(tx)
if err != nil {
return err
}
txConfirmer = NewInstantConfirmer(e, tx.Hash(), nil, nil, e.l)
} else {
txConfirmer = NewTransactionConfirmer(e, tx, e.GetNetworkConfig().MinimumConfirmations, e.l)
}
e.AddHeaderEventSubscription(tx.Hash().String(), txConfirmer)
if !e.queueTransactions { // For sequential transactions
e.l.Debug().Str("Hash", tx.Hash().String()).Msg("Waiting for TX to confirm before moving on")
defer e.DeleteHeaderEventSubscription(tx.Hash().String())
return txConfirmer.Wait()
}
return nil
}
func (e *EthereumClient) GetEthClient() *ethclient.Client {
return e.Client
}
// ProcessEvent will queue or wait on an event depending on whether parallel transactions are enabled
func (e *EthereumClient) ProcessEvent(name string, event *types.Log, confirmedChan chan bool, errorChan chan error) error {
var eventConfirmer HeaderEventSubscription
if e.GetNetworkConfig().MinimumConfirmations <= 0 {
eventConfirmer = NewInstantConfirmer(e, event.TxHash, confirmedChan, errorChan, e.l)
} else {
eventConfirmer = NewEventConfirmer(name, e, event, e.GetNetworkConfig().MinimumConfirmations, confirmedChan, errorChan)
}
subscriptionHash := fmt.Sprintf("%s-%s", event.TxHash.Hex(), name) // Many events can occupy the same tx hash
e.AddHeaderEventSubscription(subscriptionHash, eventConfirmer)
if !e.queueTransactions { // For sequential transactions
e.l.Debug().Str("Hash", event.Address.Hex()).Msg("Waiting for Event to confirm before moving on")
defer e.DeleteHeaderEventSubscription(subscriptionHash)
return eventConfirmer.Wait()
}
return nil
}
// PollFinalizedHeader continuously polls the latest finalized header and stores it in the client
func (e *EthereumClient) PollFinality() error {
if e.NetworkConfig.FinalityDepth > 0 {
return fmt.Errorf("finality depth is greater than zero. no need to poll for finality")
}
f := newGlobalFinalizedHeaderManager(e)
if f == nil {
return fmt.Errorf("could not create finalized header manager")
}
e.FinalizedHeader.Store(f)
e.AddHeaderEventSubscription(FinalizedHeaderKey, f)
return nil
}
// CancelFinalityPolling stops polling for the latest finalized header
func (e *EthereumClient) CancelFinalityPolling() {
if _, ok := e.headerSubscriptions[FinalizedHeaderKey]; ok {
e.DeleteHeaderEventSubscription(FinalizedHeaderKey)
}
}
// WaitForFinalizedTx waits for a transaction to be finalized
// If the network is simulated, it will return immediately
// otherwise it waits for the transaction to be finalized and returns the block number and time of the finalization
func (e *EthereumClient) WaitForFinalizedTx(txHash common.Hash) (*big.Int, time.Time, error) {
receipt, err := e.Client.TransactionReceipt(context.Background(), txHash)
if err != nil {
return nil, time.Time{}, err
}
txHdr, err := e.HeaderByNumber(context.Background(), receipt.BlockNumber)
if err != nil {
return nil, time.Time{}, err
}
finalizer := NewTransactionFinalizer(e, txHdr, receipt.TxHash)
key := "txFinalizer-" + txHash.String()
e.AddHeaderEventSubscription(key, finalizer)
defer e.DeleteHeaderEventSubscription(key)
err = finalizer.Wait()
if err != nil {
return nil, time.Time{}, err
}
return finalizer.FinalizedBy, finalizer.FinalizedAt, nil
}
// IsTxHeadFinalized checks if the transaction is finalized on chain
// in case of network with finality tag if the tx is not finalized it returns false,
// the latest finalized header number and the time at which it was finalized
// if the tx is finalized it returns true, the finalized header number by which the tx was considered finalized and the time at which it was finalized
func (e *EthereumClient) IsTxHeadFinalized(txHdr, header *SafeEVMHeader) (bool, *big.Int, time.Time, error) {
if e.NetworkConfig.FinalityDepth > 0 {
if header.Number.Cmp(new(big.Int).Add(txHdr.Number,
big.NewInt(int64(e.NetworkConfig.FinalityDepth)))) > 0 {
return true, header.Number, header.Timestamp, nil
}
return false, nil, time.Time{}, nil
}
fHead := e.FinalizedHeader.Load()
if fHead != nil {
latestFinalized := fHead.LatestFinalized.Load().(*big.Int)
latestFinalizedAt := fHead.FinalizedAt.Load().(time.Time)
if latestFinalized.Cmp(txHdr.Number) >= 0 {
return true, latestFinalized, latestFinalizedAt, nil
}
return false, latestFinalized, latestFinalizedAt, nil
}
return false, nil, time.Time{}, fmt.Errorf("no finalized head found. start polling for finalized header")
}
// IsTxConfirmed checks if the transaction is confirmed on chain or not
func (e *EthereumClient) IsTxConfirmed(txHash common.Hash) (bool, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
tx, isPending, err := e.Client.TransactionByHash(ctx, txHash)
cancel()
if err != nil {
if errors.Is(err, ethereum.NotFound) { // not found is fine, it's not on chain yet
return false, nil
}
return !isPending, err
}
if !isPending && e.NetworkConfig.MinimumConfirmations > 0 { // Instant chains don't bother with this receipt nonsense
ctx, cancel = context.WithTimeout(context.Background(), time.Second*5)
receipt, err := e.Client.TransactionReceipt(ctx, txHash)
cancel()
if err != nil {
if errors.Is(err, ethereum.NotFound) { // not found is fine, it's not on chain yet
return false, nil
}
return !isPending, err
}
e.gasStats.AddClientTXData(TXGasData{
TXHash: txHash.String(),
Value: tx.Value().Uint64(),
GasLimit: tx.Gas(),
GasUsed: receipt.GasUsed,
GasPrice: tx.GasPrice().Uint64(),
CumulativeGasUsed: receipt.CumulativeGasUsed,
})
if receipt.Status == 0 { // 0 indicates failure, 1 indicates success
reason, err := e.errorReason(e.Client, tx, receipt)
if err != nil {
to := "(none)"
if tx.To() != nil {
to = tx.To().Hex()
}
e.l.Warn().Str("TX Hash", txHash.Hex()).
Str("To", to).
Uint64("Nonce", tx.Nonce()).
Str("Error extracting reason", err.Error()).
Msg("Transaction failed and was reverted! Unable to retrieve reason!")
} else {
e.l.Warn().Str("TX Hash", txHash.Hex()).
Str("Revert reason", reason).
Msg("Transaction failed and was reverted!")
}
return false, fmt.Errorf("transaction failed and was reverted")
}
}
return !isPending, err
}
// IsEventConfirmed returns if eth client can confirm that the event happened
func (e *EthereumClient) IsEventConfirmed(event *types.Log) (confirmed, removed bool, err error) {
if event.Removed {
return false, event.Removed, nil
}
eventTx, isPending, err := e.Client.TransactionByHash(context.Background(), event.TxHash)
if err != nil {
return false, event.Removed, err
}
if isPending {
return false, event.Removed, nil
}
eventReceipt, err := e.Client.TransactionReceipt(context.Background(), eventTx.Hash())
if err != nil {
return false, event.Removed, err
}
if eventReceipt.Status == 0 { // Failed event tx
reason, err := e.errorReason(e.Client, eventTx, eventReceipt)
if err != nil {
e.l.Warn().Str("TX Hash", eventTx.Hash().Hex()).
Str("Error extracting reason", err.Error()).
Msg("Transaction failed and was reverted! Unable to retrieve reason!")
} else {
e.l.Warn().Str("TX Hash", eventTx.Hash().Hex()).
Str("Revert reason", reason).
Msg("Transaction failed and was reverted!")
}
return false, event.Removed, err
}
headerByNumber, err := e.HeaderByNumber(context.Background(), big.NewInt(0).SetUint64(event.BlockNumber))
if err != nil || headerByNumber == nil {
return false, event.Removed, err
}
if headerByNumber.Hash != event.BlockHash {
return false, event.Removed, nil
}
return true, event.Removed, nil
}
// GetTxReceipt returns the receipt of the transaction if available, error otherwise
func (e *EthereumClient) GetTxReceipt(txHash common.Hash) (*types.Receipt, error) {
receipt, err := e.Client.TransactionReceipt(context.Background(), txHash)
if err != nil {
return nil, err
}
return receipt, nil
}
// RevertReasonFromTx returns the revert reason for the transaction error by parsing through abi defined error list
func (e *EthereumClient) RevertReasonFromTx(txHash common.Hash, abiString string) (string, interface{}, error) {
tx, _, err := e.Client.TransactionByHash(context.Background(), txHash)
if err != nil {
return "", nil, err
}
re, err := e.GetTxReceipt(txHash)
if err != nil {
return "", nil, err
}
errData, err := e.errorReason(e.Client, tx, re)
if err != nil {
return "", nil, err
}
if errData == "" {
return "", nil, fmt.Errorf("no revert reason found")
}
data, err := hex.DecodeString(errData[2:])
if err != nil {
return "", nil, err
}
jsonABI, err := abi.JSON(strings.NewReader(abiString))
if err != nil {
return "", nil, err
}
for errName, abiError := range jsonABI.Errors {
if bytes.Equal(data[:4], abiError.ID.Bytes()[:4]) {
// Found a matching error
v, err := abiError.Unpack(data)
if err != nil {
return "", nil, err
}
return errName, v, nil
}
}
return "", nil, fmt.Errorf("revert Reason could not be found for given abistring")
}
// ParallelTransactions when enabled, sends the transaction without waiting for transaction confirmations. The hashes
// are then stored within the client and confirmations can be waited on by calling WaitForEvents.
func (e *EthereumClient) ParallelTransactions(enabled bool) {
e.queueTransactions = enabled
}
// Close tears down the current open Ethereum client
func (e *EthereumClient) Close() error {
// close(e.NonceSettings.doneChan)
close(e.doneChan)
e.subscriptionWg.Wait()
return nil
}
// EstimateTransactionGasCost estimates the current total gas cost for a simple transaction
func (e *EthereumClient) EstimateTransactionGasCost() (*big.Int, error) {
gasPrice, err := e.Client.SuggestGasPrice(context.Background())
if err != nil {
return nil, err
}
return gasPrice.Mul(gasPrice, big.NewInt(21000)), err
}
// GasStats retrieves all information on gas spent by this client
func (e *EthereumClient) GasStats() *GasStats {
return e.gasStats
}
// EstimateGas estimates all gas values based on call data
func (e *EthereumClient) EstimateGas(callMsg ethereum.CallMsg) (GasEstimations, error) {
var (
gasUnits uint64
gasTipCap *big.Int
gasFeeCap *big.Int
err error
)
if callMsg.To == nil && callMsg.Data == nil {
return GasEstimations{}, fmt.Errorf("you've called EstimateGas with a nil To address, this can cause weird errors and inaccuracies, provide a To address in your callMsg, or use EstimateGasPrice for just a price")
}
ctx, cancel := context.WithTimeout(context.Background(), e.NetworkConfig.Timeout.Duration)
// Gas Units
gasUnits, err = e.Client.EstimateGas(ctx, callMsg)
cancel()
if err != nil {
return GasEstimations{}, err
}
gasPriceBuffer := big.NewInt(0).SetUint64(e.NetworkConfig.GasEstimationBuffer)
// Legacy Gas Price
ctx, cancel = context.WithTimeout(context.Background(), e.NetworkConfig.Timeout.Duration)
gasPrice, err := e.Client.SuggestGasPrice(ctx)
cancel()
if err != nil {
return GasEstimations{}, err
}
gasPrice.Add(gasPrice, gasPriceBuffer)
if e.NetworkConfig.SupportsEIP1559 {
// GasTipCap
ctx, cancel := context.WithTimeout(context.Background(), e.NetworkConfig.Timeout.Duration)
gasTipCap, err = e.Client.SuggestGasTipCap(ctx)
cancel()
if err != nil {
return GasEstimations{}, err
}
gasTipCap.Add(gasTipCap, gasPriceBuffer)
// GasFeeCap
ctx, cancel = context.WithTimeout(context.Background(), e.NetworkConfig.Timeout.Duration)
latestHeader, err := e.HeaderByNumber(ctx, nil)
cancel()
if err != nil {
return GasEstimations{}, err
}
baseFeeMult := big.NewInt(1).Mul(latestHeader.BaseFee, big.NewInt(2))
gasFeeCap = baseFeeMult.Add(baseFeeMult, gasTipCap)
} else {
gasFeeCap = gasPrice
gasTipCap = gasPrice
}
// Total Gas Cost
totalGasCost := big.NewInt(0).Mul(gasFeeCap, new(big.Int).SetUint64(gasUnits))
return GasEstimations{
GasUnits: gasUnits,
GasPrice: gasPrice,
GasFeeCap: gasFeeCap,
GasTipCap: gasTipCap,
TotalGasCost: totalGasCost,
}, nil
}
func (e *EthereumClient) EstimateGasPrice() (*big.Int, error) {
ctx, cancel := context.WithTimeout(context.Background(), e.NetworkConfig.Timeout.Duration)
defer cancel()
return e.Client.SuggestGasPrice(ctx)
}
// ConnectionIssue returns a channel that will receive a timestamp when the connection is lost
func (e *EthereumClient) ConnectionIssue() chan time.Time {
return e.connectionIssueCh
}
// ConnectionRestored returns a channel that will receive a timestamp when the connection is restored
func (e *EthereumClient) ConnectionRestored() chan time.Time {
return e.connectionRestoredCh
}
func (e *EthereumClient) Backend() bind.ContractBackend {
return e.Client
}
func (e *EthereumClient) DeployBackend() bind.DeployBackend {
return e.Client
}
func (e *EthereumClient) SubscribeNewHeaders(
ctx context.Context,
headerChan chan *SafeEVMHeader,
) (ethereum.Subscription, error) {
clientSub, err := e.rawRPC.EthSubscribe(ctx, headerChan, "newHeads")
if err != nil {
return nil, err
}
return clientSub, err
}
// HeaderByNumber retrieves a Safe EVM header by number, nil for latest
func (e *EthereumClient) HeaderByNumber(
ctx context.Context,
number *big.Int,
) (*SafeEVMHeader, error) {
var head *SafeEVMHeader
err := e.rawRPC.CallContext(ctx, &head, "eth_getBlockByNumber", toBlockNumArg(number), false)
if err == nil && head == nil {
err = ethereum.NotFound
}
return head, err
}
// HeaderByHash retrieves a Safe EVM header by hash
func (e *EthereumClient) HeaderByHash(ctx context.Context, hash common.Hash) (*SafeEVMHeader, error) {
var head *SafeEVMHeader
err := e.rawRPC.CallContext(ctx, &head, "eth_getBlockByHash", hash, false)
if err == nil && head == nil {
err = ethereum.NotFound
}
return head, err
}
// toBlockNumArg translates a block number to the correct argument for the RPC call
func toBlockNumArg(number *big.Int) string {
if number == nil {
return "latest"
}
pending := big.NewInt(-1)
if number.Cmp(pending) == 0 {
return "pending"
}