-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
1140 lines (990 loc) · 36 KB
/
client.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 seth
import (
"context"
"crypto/ecdsa"
verr "errors"
"fmt"
"math/big"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/avast/retry-go"
"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/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/pkg/errors"
"github.com/rs/zerolog"
"golang.org/x/sync/errgroup"
)
const (
ErrEmptyConfigPath = "toml config path is empty, set SETH_CONFIG_PATH"
ErrCreateABIStore = "failed to create ABI store"
ErrReadingKeys = "failed to read keys"
ErrCreateNonceManager = "failed to create nonce manager"
ErrCreateTracer = "failed to create tracer"
ErrReadContractMap = "failed to read deployed contract map"
ErrNoKeyLoaded = "failed to load private key"
ErrRpcHealtCheckFailed = "RPC health check failed ¯\\_(ツ)_/¯"
ContractMapFilePattern = "deployed_contracts_%s_%s.toml"
RevertedTransactionsFilePattern = "reverted_transactions_%s_%s.json"
)
var (
// Number of ephemeral addresses to create
SixtyEphemeralAddresses int64 = 60
ZeroBigInt = big.NewInt(0)
// Amount of funds that will be left on the root key, when splitting funds between ephemeral addresses
ZeroRootKeyFundsBuffer = big.NewInt(0)
TracingLevel_None = "NONE"
TracingLevel_Reverted = "REVERTED"
TracingLevel_All = "ALL"
)
// Client is a vanilla go-ethereum client with enhanced debug logging
type Client struct {
Cfg *Config
Client *ethclient.Client
Addresses []common.Address
PrivateKeys []*ecdsa.PrivateKey
ChainID int64
URL string
Context context.Context
CancelFunc context.CancelFunc
Errors []error
ContractStore *ContractStore
NonceManager *NonceManager
Tracer *Tracer
ContractAddressToNameMap ContractMap
ABIFinder *ABIFinder
HeaderCache *LFUHeaderCache
}
// NewClientWithConfig creates a new seth client with all deps setup from config
func NewClientWithConfig(cfg *Config) (*Client, error) {
initDefaultLogging()
err := validateConfig(cfg)
if err != nil {
return nil, err
}
L.Debug().Msgf("Using tracing level: %s", cfg.TracingLevel)
cfg.setEphemeralAddrs()
cs, err := NewContractStore(filepath.Join(cfg.ConfigDir, cfg.ABIDir), filepath.Join(cfg.ConfigDir, cfg.BINDir))
if err != nil {
return nil, errors.Wrap(err, ErrCreateABIStore)
}
if cfg.ephemeral {
// we don't care about any other keys, only the root key
// you should not use ephemeral mode with more than 1 key
if len(cfg.Network.PrivateKeys) > 1 {
L.Warn().Msg("Ephemeral mode is enabled, but more than 1 key is loaded. Only the first key will be used")
}
cfg.Network.PrivateKeys = cfg.Network.PrivateKeys[:1]
pkeys, err := NewEphemeralKeys(*cfg.EphemeralAddrs)
if err != nil {
return nil, err
}
cfg.Network.PrivateKeys = append(cfg.Network.PrivateKeys, pkeys...)
} else {
if err := readKeyFileConfig(cfg); err != nil {
return nil, err
}
}
addrs, pkeys, err := cfg.ParseKeys()
if err != nil {
return nil, errors.Wrap(err, ErrReadingKeys)
}
nm, err := NewNonceManager(cfg, addrs, pkeys)
if err != nil {
return nil, errors.Wrap(err, ErrCreateNonceManager)
}
if !cfg.IsSimulatedNetwork() && cfg.SaveDeployedContractsMap && cfg.ContractMapFile == "" {
cfg.ContractMapFile = cfg.GenerateContractMapFileName()
}
// this part is kind of duplicated in NewClientRaw, but we need to create contract map before creating Tracer
// so that both the tracer and client have references to the same map
contractAddressToNameMap := NewEmptyContractMap()
contractAddressToNameMap.addressMap = make(map[string]string)
if !cfg.IsSimulatedNetwork() {
contractAddressToNameMap.addressMap, err = LoadDeployedContracts(cfg.ContractMapFile)
if err != nil {
return nil, errors.Wrap(err, ErrReadContractMap)
}
} else {
L.Debug().Msg("Simulated network, contract map won't be read from file")
}
abiFinder := NewABIFinder(contractAddressToNameMap, cs)
tr, err := NewTracer(cfg.Network.URLs[0], cs, &abiFinder, cfg, contractAddressToNameMap, addrs)
if err != nil {
return nil, errors.Wrap(err, ErrCreateTracer)
}
return NewClientRaw(
cfg,
addrs,
pkeys,
WithContractStore(cs),
WithNonceManager(nm),
WithTracer(tr),
WithContractMap(contractAddressToNameMap),
WithABIFinder(&abiFinder),
)
}
func validateConfig(cfg *Config) error {
if cfg.Network.GasPriceEstimationEnabled {
if cfg.Network.GasPriceEstimationBlocks == 0 {
return errors.New("when automating gas estimation is enabled blocks must be greater than 0. fix it or disable gas estimation")
}
cfg.Network.GasPriceEstimationTxPriority = strings.ToLower(cfg.Network.GasPriceEstimationTxPriority)
if cfg.Network.GasPriceEstimationTxPriority == "" {
cfg.Network.GasPriceEstimationTxPriority = Priority_Standard
}
switch cfg.Network.GasPriceEstimationTxPriority {
case Priority_Degen:
case Priority_Fast:
case Priority_Standard:
case Priority_Slow:
default:
return errors.New("when automating gas estimation is enabled priority must be fast, standard or slow. fix it or disable gas estimation")
}
}
if cfg.Network.GasLimit != 0 {
L.Warn().
Msg("Gas limit is set, this will override the gas limit set by the network. This option should be used **ONLY** if node is incapable of estimating gas limit itself, which happens only with very old versions")
}
if cfg.TracingLevel == "" {
cfg.TracingLevel = TracingLevel_Reverted
}
cfg.TracingLevel = strings.ToUpper(cfg.TracingLevel)
switch cfg.TracingLevel {
case TracingLevel_None:
case TracingLevel_Reverted:
case TracingLevel_All:
default:
return errors.New("tracing level must be one of: NONE, REVERTED, ALL")
}
return nil
}
// NewClient creates a new raw seth client with all deps setup from env vars
func NewClient() (*Client, error) {
cfg, err := ReadConfig()
if err != nil {
return nil, err
}
return NewClientWithConfig(cfg)
}
// NewClientRaw creates a new raw seth client without dependencies
func NewClientRaw(
cfg *Config,
addrs []common.Address,
pkeys []*ecdsa.PrivateKey,
opts ...ClientOpt,
) (*Client, error) {
client, err := ethclient.Dial(cfg.Network.URLs[0])
if err != nil {
return nil, fmt.Errorf("failed to connect to '%s' due to: %w", cfg.Network.URLs[0], err)
}
cID, err := strconv.Atoi(cfg.Network.ChainID)
if err != nil {
return nil, err
}
ctx, cancel := context.WithCancel(context.Background())
c := &Client{
Cfg: cfg,
Client: client,
Addresses: addrs,
PrivateKeys: pkeys,
URL: cfg.Network.URLs[0],
ChainID: int64(cID),
Context: ctx,
CancelFunc: cancel,
}
for _, o := range opts {
o(c)
}
if c.ContractAddressToNameMap.addressMap == nil {
c.ContractAddressToNameMap = NewEmptyContractMap()
if !cfg.IsSimulatedNetwork() {
c.ContractAddressToNameMap.addressMap, err = LoadDeployedContracts(cfg.ContractMapFile)
if err != nil {
return nil, errors.Wrap(err, ErrReadContractMap)
}
if len(c.ContractAddressToNameMap.addressMap) > 0 {
L.Info().
Int("Size", len(c.ContractAddressToNameMap.addressMap)).
Str("File name", cfg.ContractMapFile).
Msg("No contract map provided, read it from file")
} else {
L.Info().
Msg("No contract map provided and no file found, created new one")
}
} else {
L.Debug().Msg("Simulated network, contract map won't be read from file")
L.Info().
Msg("No contract map provided and no file found, created new one")
}
} else {
L.Info().
Int("Size", len(c.ContractAddressToNameMap.addressMap)).
Msg("Contract map was provided")
}
if c.NonceManager != nil {
c.NonceManager.Client = c
if len(c.Cfg.Network.PrivateKeys) > 0 {
if err := c.NonceManager.UpdateNonces(); err != nil {
return nil, err
}
}
}
if cfg.CheckRpcHealthOnStart {
if c.NonceManager == nil {
L.Warn().Msg("Nonce manager is not set, RPC health check will be skipped. Client will most probably fail on first transaction")
} else {
if err := c.checkRPCHealth(); err != nil {
return nil, err
}
}
}
cfg.setEphemeralAddrs()
L.Info().
Str("NetworkName", cfg.Network.Name).
Interface("Addresses", addrs).
Str("RPC", cfg.Network.URLs[0]).
Str("ChainID", cfg.Network.ChainID).
Int64("Ephemeral keys", *cfg.EphemeralAddrs).
Msg("Created new client")
if cfg.ephemeral {
bd, err := c.CalculateSubKeyFunding(*cfg.EphemeralAddrs)
if err != nil {
return nil, err
}
L.Warn().Msg("Ephemeral mode, all funds will be lost!")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
eg, egCtx := errgroup.WithContext(ctx)
// root key is element 0 in ephemeral
for _, addr := range c.Addresses[1:] {
addr := addr
eg.Go(func() error {
return c.TransferETHFromKey(egCtx, 0, addr.Hex(), bd.AddrFunding)
})
}
if err := eg.Wait(); err != nil {
return nil, err
}
}
if c.Cfg.TracingLevel != TracingLevel_None && c.Tracer == nil {
if c.ContractStore == nil {
cs, err := NewContractStore(filepath.Join(cfg.ConfigDir, cfg.ABIDir), filepath.Join(cfg.ConfigDir, cfg.BINDir))
if err != nil {
return nil, errors.Wrap(err, ErrCreateABIStore)
}
c.ContractStore = cs
}
if c.ABIFinder == nil {
abiFinder := NewABIFinder(c.ContractAddressToNameMap, c.ContractStore)
c.ABIFinder = &abiFinder
}
tr, err := NewTracer(cfg.Network.URLs[0], c.ContractStore, c.ABIFinder, cfg, c.ContractAddressToNameMap, addrs)
if err != nil {
return nil, errors.Wrap(err, ErrCreateTracer)
}
c.Tracer = tr
}
now := time.Now().Format("2006-01-02-15-04-05")
c.Cfg.RevertedTransactionsFile = fmt.Sprintf(RevertedTransactionsFilePattern, c.Cfg.Network.Name, now)
if c.Cfg.Network.GasPriceEstimationEnabled {
L.Debug().Msg("Gas estimation is enabled")
L.Debug().Msg("Initialising LFU block header cache")
c.HeaderCache = NewLFUBlockCache(c.Cfg.Network.GasPriceEstimationBlocks)
if c.Cfg.Network.EIP1559DynamicFees {
L.Debug().Msg("Checking if EIP-1559 is supported by the network")
c.CalculateGasEstimations(GasEstimationRequest{
GasEstimationEnabled: true,
FallbackGasPrice: c.Cfg.Network.GasPrice,
FallbackGasFeeCap: c.Cfg.Network.GasFeeCap,
FallbackGasTipCap: c.Cfg.Network.GasTipCap,
Priority: Priority_Standard,
})
}
}
return c, nil
}
func (m *Client) checkRPCHealth() error {
L.Info().Str("RPC node", m.URL).Msg("---------------- !!!!! ----------------> Checking RPC health")
ctx, cancel := context.WithTimeout(context.Background(), m.Cfg.Network.TxnTimeout.Duration())
defer cancel()
err := m.TransferETHFromKey(ctx, 0, m.Addresses[0].Hex(), big.NewInt(10_000))
if err != nil {
return errors.Wrap(err, ErrRpcHealtCheckFailed)
}
L.Info().Msg("RPC health check passed <---------------- !!!!! ----------------")
return nil
}
// Decode waits for transaction to be minted, then decodes transaction inputs, outputs, logs and events and
// depending on 'tracing_level' it either returns immediatelly or if the level matches it traces all calls.
// If 'tracing_to_json' is saved we also save to JSON all that information.
// If transaction was reverted the error return will be revert error, not decoding error (that one if any will be logged).
// It means it can return both error and decoded transaction!
func (m *Client) Decode(tx *types.Transaction, txErr error) (*DecodedTransaction, error) {
if len(m.Errors) > 0 {
return nil, verr.Join(m.Errors...)
}
if txErr != nil {
msg := "Skipping decoding, transaction submission failed. Nothing to decode"
if m.Cfg.Network.GasLimit == 0 {
msg = "Skipping decoding, most probably gas estimation failed. √. You could try to set gas limit manually in config and try again to get decoded transaction"
}
L.Trace().
Msg(msg)
return nil, txErr
}
if tx == nil {
L.Trace().
Msg("Skipping decoding, because transaction is nil. Nothing to decode")
return nil, nil
}
l := L.With().Str("Transaction", tx.Hash().Hex()).Logger()
receipt, err := m.WaitMined(context.Background(), l, m.Client, tx)
if err != nil {
L.Trace().
Err(err).
Msg("Skipping decoding, because transaction was not minted. Nothing to decode")
return nil, err
}
var revertErr error
if receipt.Status == 0 {
revertErr = m.callAndGetRevertReason(tx, receipt)
}
decoded, decodeErr := m.decodeTransaction(l, tx, receipt)
if decodeErr != nil && errors.Is(decodeErr, errors.New(ErrNoABIMethod)) {
if m.Cfg.TraceToJson {
L.Trace().
Err(decodeErr).
Msg("Failed to decode transaction. Saving transaction data hash as JSON")
err = CreateOrAppendToJsonArray(m.Cfg.RevertedTransactionsFile, tx.Hash().Hex())
if err != nil {
l.Warn().
Err(err).
Str("TXHash", tx.Hash().Hex()).
Msg("Failed to save reverted transaction hash to file")
} else {
l.Trace().
Str("TXHash", tx.Hash().Hex()).
Msg("Saved reverted transaction to file")
}
}
return decoded, revertErr
}
if m.Cfg.TracingLevel == TracingLevel_None {
L.Trace().
Str("Transaction Hash", tx.Hash().Hex()).
Msg("Tracing level is NONE, skipping decoding")
return decoded, revertErr
}
if m.Cfg.TracingLevel == TracingLevel_All || (m.Cfg.TracingLevel == TracingLevel_Reverted && revertErr != nil) {
traceErr := m.Tracer.TraceGethTX(decoded.Hash)
if traceErr != nil {
if m.Cfg.TraceToJson {
L.Trace().
Err(traceErr).
Msg("Failed to trace call, but decoding was successful. Saving decoded data as JSON")
path, saveErr := saveAsJson(decoded, "traces", decoded.Hash)
if saveErr != nil {
L.Warn().
Err(saveErr).
Msg("Failed to save decoded call as JSON")
} else {
L.Trace().
Str("Path", path).
Str("Tx hash", decoded.Hash).
Msg("Saved decoded transaction data to JSON")
}
}
if strings.Contains(traceErr.Error(), "debug_traceTransaction does not exist") {
L.Warn().
Err(err).
Msg("Debug API is either disabled or not available on the node. Disabling tracing")
m.Cfg.TracingLevel = TracingLevel_None
}
return decoded, revertErr
}
if m.Cfg.TraceToJson {
path, saveErr := saveAsJson(m.Tracer.DecodedCalls[decoded.Hash], "traces", decoded.Hash)
if saveErr != nil {
L.Warn().
Err(saveErr).
Msg("Failed to save decoded call as JSON")
} else {
L.Trace().
Str("Path", path).
Str("Tx hash", decoded.Hash).
Msg("Saved decoded call data to JSON")
}
}
} else {
L.Trace().
Str("Transaction Hash", tx.Hash().Hex()).
Str("Tracing level", m.Cfg.TracingLevel).
Bool("Was reverted?", revertErr != nil).
Msg("Transaction doesn't match tracing level, skipping decoding")
}
return decoded, revertErr
}
func (m *Client) TransferETHFromKey(ctx context.Context, fromKeyNum int, to string, value *big.Int) error {
if fromKeyNum > len(m.PrivateKeys) || fromKeyNum > len(m.Addresses) {
return errors.Wrap(errors.New(ErrNoKeyLoaded), fmt.Sprintf("requested key: %d", fromKeyNum))
}
toAddr := common.HexToAddress(to)
chainID, err := m.Client.NetworkID(context.Background())
if err != nil {
return errors.Wrap(err, "failed to get network ID")
}
var gasLimit int64
gasLimitRaw, err := m.EstimateGasLimitForFundTransfer(m.Addresses[fromKeyNum], common.HexToAddress(to), value)
if err != nil {
gasLimit = m.Cfg.Network.TransferGasFee
} else {
gasLimit = int64(gasLimitRaw)
}
rawTx := &types.LegacyTx{
Nonce: m.NonceManager.NextNonce(m.Addresses[fromKeyNum]).Uint64(),
To: &toAddr,
Value: value,
Gas: uint64(gasLimit),
GasPrice: big.NewInt(m.Cfg.Network.GasPrice),
}
L.Debug().Interface("TransferTx", rawTx).Send()
signedTx, err := types.SignNewTx(m.PrivateKeys[fromKeyNum], types.NewEIP155Signer(chainID), rawTx)
if err != nil {
return errors.Wrap(err, "failed to sign tx")
}
ctx, cancel := context.WithTimeout(ctx, m.Cfg.Network.TxnTimeout.Duration())
defer cancel()
err = m.Client.SendTransaction(ctx, signedTx)
if err != nil {
return errors.Wrap(err, "failed to send transaction")
}
l := L.With().Str("Transaction", signedTx.Hash().Hex()).Logger()
l.Info().
Int("FromKeyNum", fromKeyNum).
Str("To", to).
Interface("Value", value).
Msg("Send ETH")
_, err = m.WaitMined(ctx, l, m.Client, signedTx)
if err != nil {
return err
}
return err
}
// WaitMined the same as bind.WaitMined, awaits transaction receipt until timeout
func (m *Client) WaitMined(ctx context.Context, l zerolog.Logger, b bind.DeployBackend, tx *types.Transaction) (*types.Receipt, error) {
queryTicker := time.NewTicker(time.Second)
defer queryTicker.Stop()
ctx, cancel := context.WithTimeout(ctx, m.Cfg.Network.TxnTimeout.Duration())
defer cancel()
for {
receipt, err := b.TransactionReceipt(ctx, tx.Hash())
if err == nil {
l.Info().Int64("BlockNumber", receipt.BlockNumber.Int64()).Msg("Transaction accepted")
return receipt, nil
}
if errors.Is(err, ethereum.NotFound) {
l.Debug().Msg("Awaiting transaction")
} else {
l.Warn().Err(err).Msg("Failed to get receipt")
}
select {
case <-ctx.Done():
l.Error().Err(err).Msg("Transaction context is done")
return nil, ctx.Err()
case <-queryTicker.C:
}
}
}
/* ClientOpts client functional options */
// ClientOpt is a client functional option
type ClientOpt func(c *Client)
// WithContractStore ContractStore functional option
func WithContractStore(as *ContractStore) ClientOpt {
return func(c *Client) {
c.ContractStore = as
}
}
// WithContractMap contractAddressToNameMap functional option
func WithContractMap(contractAddressToNameMap ContractMap) ClientOpt {
return func(c *Client) {
c.ContractAddressToNameMap = contractAddressToNameMap
}
}
// WithABIFinder ABIFinder functional option
func WithABIFinder(abiFinder *ABIFinder) ClientOpt {
return func(c *Client) {
c.ABIFinder = abiFinder
}
}
// WithNonceManager NonceManager functional option
func WithNonceManager(nm *NonceManager) ClientOpt {
return func(c *Client) {
c.NonceManager = nm
}
}
// WithTracer Tracer functional option
func WithTracer(t *Tracer) ClientOpt {
return func(c *Client) {
c.Tracer = t
}
}
/* CallOpts function options */
// CallOpt is a functional option for bind.CallOpts
type CallOpt func(o *bind.CallOpts)
// WithPending sets pending option for bind.CallOpts
func WithPending(pending bool) CallOpt {
return func(o *bind.CallOpts) {
o.Pending = pending
}
}
// WithBlockNumber sets blockNumber option for bind.CallOpts
func WithBlockNumber(bn uint64) CallOpt {
return func(o *bind.CallOpts) {
o.BlockNumber = big.NewInt(int64(bn))
}
}
// NewCallOpts returns a new sequential call options wrapper
func (m *Client) NewCallOpts(o ...CallOpt) *bind.CallOpts {
co := &bind.CallOpts{
Pending: false,
From: m.Addresses[0],
}
for _, f := range o {
f(co)
}
return co
}
// NewCallKeyOpts returns a new sequential call options wrapper from the key N
func (m *Client) NewCallKeyOpts(keyNum int, o ...CallOpt) *bind.CallOpts {
co := &bind.CallOpts{
Pending: false,
From: m.Addresses[keyNum],
}
for _, f := range o {
f(co)
}
return co
}
// TransactOpt is a wrapper for bind.TransactOpts
type TransactOpt func(o *bind.TransactOpts)
// WithValue sets value option for bind.TransactOpts
func WithValue(value *big.Int) TransactOpt {
return func(o *bind.TransactOpts) {
o.Value = value
}
}
// WithGasPrice sets gasPrice option for bind.TransactOpts
func WithGasPrice(gasPrice *big.Int) TransactOpt {
return func(o *bind.TransactOpts) {
o.GasPrice = gasPrice
}
}
// WithGasLimit sets gasLimit option for bind.TransactOpts
func WithGasLimit(gasLimit uint64) TransactOpt {
return func(o *bind.TransactOpts) {
o.GasLimit = gasLimit
}
}
// WithNoSend sets noSend option for bind.TransactOpts
func WithNoSend(noSend bool) TransactOpt {
return func(o *bind.TransactOpts) {
o.NoSend = noSend
}
}
// WithNonce sets nonce option for bind.TransactOpts
func WithNonce(nonce *big.Int) TransactOpt {
return func(o *bind.TransactOpts) {
o.Nonce = nonce
}
}
// WithGasFeeCap sets gasFeeCap option for bind.TransactOpts
func WithGasFeeCap(gasFeeCap *big.Int) TransactOpt {
return func(o *bind.TransactOpts) {
o.GasFeeCap = gasFeeCap
}
}
// WithGasTipCap sets gasTipCap option for bind.TransactOpts
func WithGasTipCap(gasTipCap *big.Int) TransactOpt {
return func(o *bind.TransactOpts) {
o.GasTipCap = gasTipCap
}
}
type ContextErrorKey struct{}
// NewTXOpts returns a new transaction options wrapper,
// Sets gas price/fee tip/cap and gas limit either based on TOML config or estimations.
func (m *Client) NewTXOpts(o ...TransactOpt) *bind.TransactOpts {
opts, nonce, estimations := m.getProposedTransactionOptions(0)
m.configureTransactionOpts(opts, nonce.PendingNonce, estimations, o...)
L.Debug().
Interface("Nonce", opts.Nonce).
Interface("Value", opts.Value).
Interface("GasPrice", opts.GasPrice).
Interface("GasFeeCap", opts.GasFeeCap).
Interface("GasTipCap", opts.GasTipCap).
Uint64("GasLimit", opts.GasLimit).
Msg("New transaction options")
return opts
}
// NewTXKeyOpts returns a new transaction options wrapper,
// sets opts.GasPrice and opts.GasLimit from seth.toml or override with options
func (m *Client) NewTXKeyOpts(keyNum int, o ...TransactOpt) *bind.TransactOpts {
if keyNum > len(m.Addresses) || keyNum < 0 {
errText := fmt.Sprintf("keyNum is out of range. Expected %d-%d. Got: %d", 0, len(m.Addresses)-1, keyNum)
if keyNum == TimeoutKeyNum {
errText += " (this is a probably because, we didn't manage to find any synced key before timeout)"
}
err := errors.New(errText)
m.Errors = append(m.Errors, err)
opts := &bind.TransactOpts{}
// can't return nil, otherwise RPC wrapper will panic and we might lose funds on testnets/mainnets, that's why
// error is passed in Context here to avoid panic, whoever is using Seth should make sure that there is no error
// present in Context before using *bind.TransactOpts
opts.Context = context.WithValue(context.Background(), ContextErrorKey{}, err)
return opts
}
L.Debug().
Interface("KeyNum", keyNum).
Interface("Address", m.Addresses[keyNum]).
Msg("Estimating transaction")
opts, nonceStatus, estimations := m.getProposedTransactionOptions(keyNum)
m.configureTransactionOpts(opts, nonceStatus.PendingNonce, estimations, o...)
L.Debug().
Interface("KeyNum", keyNum).
Interface("Nonce", opts.Nonce).
Interface("Value", opts.Value).
Interface("GasPrice", opts.GasPrice).
Interface("GasFeeCap", opts.GasFeeCap).
Interface("GasTipCap", opts.GasTipCap).
Uint64("GasLimit", opts.GasLimit).
Msg("New transaction options")
return opts
}
// AnySyncedKey returns the first synced key
func (m *Client) AnySyncedKey() int {
return m.NonceManager.anySyncedKey()
}
type GasEstimations struct {
GasPrice *big.Int
GasTipCap *big.Int
GasFeeCap *big.Int
}
type NonceStatus struct {
LastNonce uint64
PendingNonce uint64
}
func (m *Client) getNonceStatus(keyNum int) (NonceStatus, error) {
ctx, cancel := context.WithTimeout(context.Background(), m.Cfg.Network.TxnTimeout.Duration())
defer cancel()
pendingNonce, err := m.Client.PendingNonceAt(ctx, m.Addresses[keyNum])
if err != nil {
L.Error().Err(err).Msg("Failed to get pending nonce")
return NonceStatus{}, err
}
lastNonce, err := m.Client.NonceAt(ctx, m.Addresses[keyNum], nil)
if err != nil {
return NonceStatus{}, err
}
return NonceStatus{
LastNonce: lastNonce,
PendingNonce: pendingNonce,
}, nil
}
// getProposedTransactionOptions gets all the tx info that network proposed
func (m *Client) getProposedTransactionOptions(keyNum int) (*bind.TransactOpts, NonceStatus, GasEstimations) {
nonceStatus, err := m.getNonceStatus(keyNum)
if err != nil {
m.Errors = append(m.Errors, err)
// can't return nil, otherwise RPC wrapper will panic
ctx := context.WithValue(context.Background(), ContextErrorKey{}, err)
return &bind.TransactOpts{Context: ctx}, NonceStatus{}, GasEstimations{}
}
var ctx context.Context
if m.Cfg.PendingNonceProtectionEnabled {
if nonceStatus.PendingNonce > nonceStatus.LastNonce {
errMsg := `
pending nonce for key %d is higher than last nonce, there are %d pending transactions.
This issue is caused by one of two things:
1. You are using the same keyNum in multiple goroutines, which is not supported. Each goroutine should use an unique keyNum.
2. You have stuck transaction(s). Speed them up by sending replacement transactions with higher gas price before continuing, otherwise future transactions most probably will also get stuck.
`
err := fmt.Errorf(errMsg, keyNum, nonceStatus.PendingNonce-nonceStatus.LastNonce)
m.Errors = append(m.Errors, err)
// can't return nil, otherwise RPC wrapper will panic and we might lose funds on testnets/mainnets, that's why
// error is passed in Context here to avoid panic, whoever is using Seth should make sure that there is no error
// present in Context before using *bind.TransactOpts
ctx = context.WithValue(context.Background(), ContextErrorKey{}, err)
}
L.Debug().
Msg("Pending nonce protection is enabled. Nonce status is OK")
}
estimations := m.CalculateGasEstimations(m.NewDefaultGasEstimationRequest())
L.Debug().
Interface("KeyNum", keyNum).
Uint64("Nonce", nonceStatus.PendingNonce).
Interface("GasEstimations", estimations).
Msg("Proposed transaction options")
opts, err := bind.NewKeyedTransactorWithChainID(m.PrivateKeys[keyNum], big.NewInt(m.ChainID))
if err != nil {
err = errors.Wrapf(err, "failed to create transactor for key %d", keyNum)
m.Errors = append(m.Errors, err)
// can't return nil, otherwise RPC wrapper will panic and we might lose funds on testnets/mainnets, that's why
// error is passed in Context here to avoid panic, whoever is using Seth should make sure that there is no error
// present in Context before using *bind.TransactOpts
ctx := context.WithValue(context.Background(), ContextErrorKey{}, err)
return &bind.TransactOpts{Context: ctx}, NonceStatus{}, GasEstimations{}
}
if ctx != nil {
opts.Context = ctx
}
return opts, nonceStatus, estimations
}
type GasEstimationRequest struct {
GasEstimationEnabled bool
FallbackGasPrice int64
FallbackGasFeeCap int64
FallbackGasTipCap int64
Priority string
}
// NewDefaultGasEstimationRequest creates a new default gas estimation request based on current network configuration
func (m *Client) NewDefaultGasEstimationRequest() GasEstimationRequest {
return GasEstimationRequest{
GasEstimationEnabled: m.Cfg.Network.GasPriceEstimationEnabled,
FallbackGasPrice: m.Cfg.Network.GasPrice,
FallbackGasFeeCap: m.Cfg.Network.GasFeeCap,
FallbackGasTipCap: m.Cfg.Network.GasTipCap,
Priority: m.Cfg.Network.GasPriceEstimationTxPriority,
}
}
// CalculateGasEstimations calculates gas estimations (price, tip/cap) or uses hardcoded values if estimation is disabled,
// estimation errors or network is a simulated one.
func (m *Client) CalculateGasEstimations(request GasEstimationRequest) GasEstimations {
estimations := GasEstimations{}
if m.Cfg.IsSimulatedNetwork() || !request.GasEstimationEnabled {
estimations.GasPrice = big.NewInt(request.FallbackGasPrice)
estimations.GasFeeCap = big.NewInt(request.FallbackGasFeeCap)
estimations.GasTipCap = big.NewInt(request.FallbackGasTipCap)
return estimations
}
ctx, cancel := context.WithTimeout(context.Background(), m.Cfg.Network.TxnTimeout.Duration())
defer cancel()
var disableEstimationsIfNeeded = func(err error) {
if strings.Contains(err.Error(), ZeroGasSuggestedErr) {
L.Warn().Msg("Received incorrect gas estimations. Disabling them and reverting to hardcoded values. Remember to update your config!")
m.Cfg.Network.GasPriceEstimationEnabled = false
}
}
var calulcateLegacyFees = func() {
gasPrice, err := m.GetSuggestedLegacyFees(ctx, request.Priority)
if err != nil {
disableEstimationsIfNeeded(err)
L.Warn().Err(err).Msg("Failed to get suggested Legacy fees. Using hardcoded values")
estimations.GasPrice = big.NewInt(request.FallbackGasPrice)
} else {
estimations.GasPrice = gasPrice
}
}
if m.Cfg.Network.EIP1559DynamicFees {
maxFee, priorityFee, err := m.GetSuggestedEIP1559Fees(ctx, request.Priority)
if err != nil {
L.Warn().Err(err).Msg("Failed to get suggested EIP1559 fees. Using hardcoded values")
estimations.GasFeeCap = big.NewInt(request.FallbackGasFeeCap)
estimations.GasTipCap = big.NewInt(request.FallbackGasTipCap)
disableEstimationsIfNeeded(err)
if strings.Contains(err.Error(), "method eth_maxPriorityFeePerGas") || strings.Contains(err.Error(), "method eth_maxFeePerGas") || strings.Contains(err.Error(), "method eth_feeHistory") || strings.Contains(err.Error(), "expected input list for types.txdata") {
L.Warn().Msg("EIP1559 fees are not supported by the network. Switching to Legacy fees. Remember to update your config!")
if m.Cfg.Network.GasPrice == 0 {
L.Warn().Msg("Gas price is 0. If Legacy estimations fail, there will no fallback price and transactions will start fail. Set gas price in config and disable EIP1559DynamicFees")
}
m.Cfg.Network.EIP1559DynamicFees = false
calulcateLegacyFees()
}
} else {
estimations.GasFeeCap = maxFee
estimations.GasTipCap = priorityFee
}
} else {
calulcateLegacyFees()
}
return estimations
}
// EstimateGasLimitForFundTransfer estimates gas limit for fund transfer
func (m *Client) EstimateGasLimitForFundTransfer(from, to common.Address, amount *big.Int) (uint64, error) {
ctx, cancel := context.WithTimeout(context.Background(), m.Cfg.Network.TxnTimeout.Duration())
defer cancel()
gasLimit, err := m.Client.EstimateGas(ctx, ethereum.CallMsg{
From: from,
To: &to,
Value: amount,
})
if err != nil {
L.Warn().Err(err).Msg("Failed to estimate gas for fund transfer.")
return 0, errors.Wrapf(err, "failed to estimate gas for fund transfer")
}
return gasLimit, nil
}
// configureTransactionOpts configures transaction for legacy or type-2
func (m *Client) configureTransactionOpts(
opts *bind.TransactOpts,
nonce uint64,
estimations GasEstimations,
o ...TransactOpt,
) *bind.TransactOpts {
opts.Nonce = big.NewInt(int64(nonce))
opts.GasPrice = estimations.GasPrice
opts.GasLimit = m.Cfg.Network.GasLimit
if m.Cfg.Network.EIP1559DynamicFees {
opts.GasPrice = nil
opts.GasTipCap = estimations.GasTipCap
opts.GasFeeCap = estimations.GasFeeCap
}
for _, f := range o {
f(opts)
}
return opts
}
// DeployContract deploys contract using ABI and bytecode passed to it, waits for transaction to be minted and contract really
// available at the address, so that when the method returns it's safe to interact with it. It also saves the contract address and ABI name
// to the contract map, so that we can use that, when tracing transactions. It is suggested to use name identical to the name of the contract Solidity file.
func (m *Client) DeployContract(auth *bind.TransactOpts, name string, abi abi.ABI, bytecode []byte, params ...interface{}) (DeploymentData, error) {
L.Info().
Msgf("Started deploying %s contract", name)
if auth.Context != nil {
if err, ok := auth.Context.Value(ContextErrorKey{}).(error); ok {
return DeploymentData{}, errors.Wrapf(err, "aborted contract deployment for %s, because context passed in transaction options had an error set", name)
}
}
address, tx, contract, err := bind.DeployContract(auth, abi, bytecode, m.Client, params...)
if err != nil {
return DeploymentData{}, wrapErrInMessageWithASuggestion(err)
}
L.Info().
Str("Address", address.Hex()).
Str("TXHash", tx.Hash().Hex()).
Msgf("Waiting for %s contract deployment to finish", name)