-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathclient.go
591 lines (498 loc) · 18.9 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
package client
import (
"context"
"fmt"
"github.com/ethereum/go-ethereum"
"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/ethereum/go-ethereum/rpc"
"github.com/lmittmann/w3"
"github.com/lmittmann/w3/w3types"
"github.com/synapsecns/sanguine/core/metrics"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"math/big"
"reflect"
)
// EVM is the set of functions that the scribe needs from a client.
//
//go:generate go run github.com/vektra/mockery/v2 --name=EVM --output=mocks --case=underscore
type EVM interface {
// ContractBackend defines the methods needed to work with contracts on a read-write basis.
// this is used for deploying an interacting with contracts
bind.ContractBackend
// ChainReader ethereum.ChainReader for getting transactions
ethereum.ChainReader
// TransactionReader is used for reading txes by hash
ethereum.TransactionReader
// ChainStateReader gets the chain state reader
ethereum.ChainStateReader
// PendingStateReader handles pending state calls
ethereum.PendingStateReader
// ChainSyncReader tracks state head
ethereum.ChainSyncReader
// PendingContractCaller tracks pending contract calls
ethereum.PendingContractCaller
// FeeHistory gets the fee history for a given block
FeeHistory(ctx context.Context, blockCount uint64, lastBlock *big.Int, rewardPercentiles []float64) (*ethereum.FeeHistory, error)
// NetworkID returns the network ID (also known as the chain ID) for this chain.
NetworkID(ctx context.Context) (*big.Int, error)
// ChainID gets the chain id from the rpc server
ChainID(ctx context.Context) (*big.Int, error)
// CallContext is used for manual overrides
CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error
// BatchCallContext is used for manual overrides
BatchCallContext(ctx context.Context, b []rpc.BatchElem) error
// BlockNumber gets the latest block number
BlockNumber(ctx context.Context) (uint64, error)
// BatchWithContext batches multiple w3type calls
BatchWithContext(ctx context.Context, calls ...w3types.Caller) error
// Web3Version gets the web3 version
Web3Version(ctx context.Context) (version string, err error)
}
type clientImpl struct {
tracing metrics.Handler
captureClient *captureClient
endpoint string
captureRequestRes bool
rpcClient *rpc.Client
// TODO: consider using sync.Pool for capture clients to improve performance
}
// DialBackend returns a scribe backend.
func DialBackend(ctx context.Context, url string, handler metrics.Handler, opts ...Options) (_ EVM, err error) {
client := &clientImpl{
endpoint: url,
tracing: handler,
}
for _, opt := range opts {
opt(client)
}
// TODO: port to master wether or not pr gets merged
client.captureClient, err = newCaptureClient(ctx, url, handler, client.captureRequestRes)
if err != nil {
return nil, fmt.Errorf("could not create capture client: %w", err)
}
client.rpcClient = client.captureClient.rpcClient
return client, nil
}
const (
batchAttribute = "batch"
methodsAttribute = "methods"
endpointAttribute = "endpoint"
)
func (c *clientImpl) getEthClient() *ethclient.Client {
return c.captureClient.ethClient
}
func (c *clientImpl) getW3Client() *w3.Client {
return c.captureClient.w3Client
}
// BatchWithContext batches multiple w3 calls.
func (c *clientImpl) BatchWithContext(ctx context.Context, calls ...w3types.Caller) (err error) {
ctx, span := c.tracing.Tracer().Start(ctx, batchAttribute)
span.SetAttributes(parseCalls(calls))
span.SetAttributes(attribute.String(endpointAttribute, c.endpoint))
defer func() {
metrics.EndSpanWithErr(span, err)
}()
//nolint: wrapcheck
return c.getW3Client().CallCtx(ctx, calls...)
}
// BatchCallContext calls BatchCallContext on the underlying client. Note: this will bypass the rate-limiter.
//
//nolint:wrapcheck
func (c *clientImpl) BatchCallContext(ctx context.Context, b []rpc.BatchElem) (err error) {
requestCtx, span := c.startSpan(ctx, NetVersionMethod)
span.SetAttributes(parseBatch(b))
span.SetAttributes(attribute.String(endpointAttribute, c.endpoint))
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.captureClient.rpcClient.BatchCallContext(requestCtx, b)
}
func (c *clientImpl) startSpan(parentCtx context.Context, method RPCMethod, opts ...trace.SpanStartOption) (context.Context, trace.Span) {
ctx, span := c.tracing.Tracer().Start(parentCtx, method.String(), opts...)
span.SetAttributes(attribute.String("endpoint", c.endpoint))
return ctx, span
}
// CallContract calls contract on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) (contractResponse []byte, err error) {
requestCtx, span := c.startSpan(ctx, CallMethod, trace.WithAttributes(attribute.String(metrics.ContractAddress, nillableToString(call.To)), attribute.String("data", common.Bytes2Hex(call.Data)), attribute.Bool("pending", false)))
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().CallContract(requestCtx, call, blockNumber)
}
// toStrings converts a slice of any type that satisfies the Stringer interface into a slice of strings.
func toStrings[T fmt.Stringer](items []T) (res []string) {
for _, item := range items {
res = append(res, item.String())
}
return res
}
func nillableToString(nillable fmt.Stringer) string {
if nillable == nil {
return ""
}
// Use reflection to check if the interface's underlying value is nil.
val := reflect.ValueOf(nillable)
if val.Kind() == reflect.Ptr && val.IsNil() {
return ""
}
return nillable.String()
}
// PendingCallContract calls contract on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) PendingCallContract(ctx context.Context, call ethereum.CallMsg) (contractResponse []byte, err error) {
requestCtx, span := c.startSpan(ctx, CallMethod, trace.WithAttributes(attribute.String(metrics.ContractAddress, nillableToString(call.To)), attribute.String("data", common.Bytes2Hex(call.Data)), attribute.Bool("pending", true)))
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().PendingCallContract(requestCtx, call)
}
// PendingCodeAt calls PendingCodeAt on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) PendingCodeAt(ctx context.Context, account common.Address) (codeResponse []byte, err error) {
requestCtx, span := c.startSpan(ctx, GetCodeMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().PendingCodeAt(requestCtx, account)
}
// PendingBalanceAt calls PendingBalanceAt on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) PendingBalanceAt(ctx context.Context, account common.Address) (pendingBalance *big.Int, err error) {
requestCtx, span := c.startSpan(ctx, GetBalanceMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().PendingBalanceAt(requestCtx, account)
}
// PendingStorageAt calls PendingStorageAt on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) PendingStorageAt(ctx context.Context, account common.Address, key common.Hash) (pendingStorage []byte, err error) {
requestCtx, span := c.startSpan(ctx, StorageAtMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().PendingStorageAt(requestCtx, account, key)
}
// PendingNonceAt calls PendingNonceAt on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) PendingNonceAt(ctx context.Context, account common.Address) (pendingNonce uint64, err error) {
requestCtx, span := c.startSpan(ctx, TransactionCountMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().PendingNonceAt(requestCtx, account)
}
// PendingTransactionCount calls PendingTransactionCount on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) PendingTransactionCount(ctx context.Context) (count uint, err error) {
requestCtx, span := c.startSpan(ctx, PendingTransactionCountMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().PendingTransactionCount(requestCtx)
}
// NetworkID calls NetworkID on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) NetworkID(ctx context.Context) (id *big.Int, err error) {
requestCtx, span := c.startSpan(ctx, NetVersionMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().NetworkID(requestCtx)
}
// Web3Version calls Web3Version on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) Web3Version(ctx context.Context) (version string, err error) {
requestCtx, span := c.startSpan(ctx, Web3VersionMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
var ver string
if err := c.rpcClient.CallContext(requestCtx, &ver, Web3VersionMethod.String()); err != nil {
return "", err
}
return ver, nil
}
// SyncProgress calls SyncProgress on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) SyncProgress(ctx context.Context) (syncProgress *ethereum.SyncProgress, err error) {
requestCtx, span := c.startSpan(ctx, SyncProgressMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().SyncProgress(requestCtx)
}
// SuggestGasPrice calls SuggestGasPrice on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) SuggestGasPrice(ctx context.Context) (gasPrice *big.Int, err error) {
requestCtx, span := c.startSpan(ctx, GasPriceMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().SuggestGasPrice(requestCtx)
}
// EstimateGas calls EstimateGas on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) EstimateGas(ctx context.Context, call ethereum.CallMsg) (gas uint64, err error) {
requestCtx, span := c.startSpan(ctx, EstimateGasMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().EstimateGas(requestCtx, call)
}
// SendTransaction calls SendTransaction on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) SendTransaction(ctx context.Context, tx *types.Transaction) (err error) {
requestCtx, span := c.startSpan(ctx, SendRawTransactionMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().SendTransaction(requestCtx, tx)
}
func queryToTraceParams(query ethereum.FilterQuery) (res []attribute.KeyValue) {
res = append(res, attribute.String(metrics.BlockHash, nillableToString(query.BlockHash)))
res = append(res, attribute.String(metrics.FromBlock, nillableToString(query.FromBlock)))
res = append(res, attribute.String(metrics.ToBlock, nillableToString(query.ToBlock)))
res = append(res, attribute.StringSlice("addresses", toStrings(query.Addresses)))
// TODO: add topics
return res
}
// FilterLogs calls FilterLogs on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) FilterLogs(ctx context.Context, query ethereum.FilterQuery) (logs []types.Log, err error) {
requestCtx, span := c.startSpan(ctx, GetLogsMethod, trace.WithAttributes(queryToTraceParams(query)...))
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().FilterLogs(requestCtx, query)
}
// SubscribeFilterLogs calls SubscribeFilterLogs on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) SubscribeFilterLogs(ctx context.Context, query ethereum.FilterQuery, ch chan<- types.Log) (sub ethereum.Subscription, err error) {
requestCtx, span := c.startSpan(ctx, SubscribeMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().SubscribeFilterLogs(requestCtx, query, ch)
}
// BlockByHash calls BlockByHash on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) BlockByHash(ctx context.Context, hash common.Hash) (block *types.Block, err error) {
requestCtx, span := c.startSpan(ctx, BlockByHashMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().BlockByHash(requestCtx, hash)
}
// BlockByNumber calls BlockByNumber on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) BlockByNumber(ctx context.Context, number *big.Int) (block *types.Block, err error) {
requestCtx, span := c.startSpan(ctx, BlockByNumberMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().BlockByNumber(requestCtx, number)
}
// HeaderByHash calls HeaderByHash on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) HeaderByHash(ctx context.Context, hash common.Hash) (header *types.Header, err error) {
requestCtx, span := c.startSpan(ctx, BlockByHashMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().HeaderByHash(requestCtx, hash)
}
// HeaderByNumber calls HeaderByNumber on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) HeaderByNumber(ctx context.Context, number *big.Int) (header *types.Header, err error) {
requestCtx, span := c.startSpan(ctx, BlockByNumberMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().HeaderByNumber(requestCtx, number)
}
// TransactionCount calls TransactionCount on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) TransactionCount(ctx context.Context, blockHash common.Hash) (txCount uint, err error) {
requestCtx, span := c.startSpan(ctx, TransactionCountByHashMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().TransactionCount(requestCtx, blockHash)
}
// TransactionInBlock calls TransactionInBlock on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) TransactionInBlock(ctx context.Context, blockHash common.Hash, index uint) (tx *types.Transaction, err error) {
requestCtx, span := c.startSpan(ctx, TransactionByBlockHashAndIndexMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().TransactionInBlock(requestCtx, blockHash, index)
}
// SubscribeNewHead calls SubscribeNewHead on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (sub ethereum.Subscription, err error) {
requestCtx, span := c.startSpan(ctx, SubscribeMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().SubscribeNewHead(requestCtx, ch)
}
// TransactionByHash calls TransactionByHash on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) TransactionByHash(ctx context.Context, txHash common.Hash) (tx *types.Transaction, isPending bool, err error) {
requestCtx, span := c.startSpan(ctx, TransactionByHashMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().TransactionByHash(requestCtx, txHash)
}
// TransactionReceipt calls TransactionReceipt on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) TransactionReceipt(ctx context.Context, txHash common.Hash) (receipt *types.Receipt, err error) {
requestCtx, span := c.startSpan(ctx, TransactionReceiptByHashMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().TransactionReceipt(requestCtx, txHash)
}
// BalanceAt calls BalanceAt on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) BalanceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (balance *big.Int, err error) {
requestCtx, span := c.startSpan(ctx, GetBalanceMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().BalanceAt(requestCtx, account, blockNumber)
}
// StorageAt calls StorageAt on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) StorageAt(ctx context.Context, account common.Address, key common.Hash, blockNumber *big.Int) (storage []byte, err error) {
requestCtx, span := c.startSpan(ctx, StorageAtMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().StorageAt(requestCtx, account, key, blockNumber)
}
// BlockNumber gets the latest block number
//
//nolint:wrapcheck
func (c *clientImpl) BlockNumber(ctx context.Context) (_ uint64, err error) {
requestCtx, span := c.startSpan(ctx, BlockNumberMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().BlockNumber(requestCtx)
}
// CodeAt calls CodeAt on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) (codeAt []byte, err error) {
requestCtx, span := c.startSpan(ctx, GetCodeMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().CodeAt(requestCtx, account, blockNumber)
}
// SuggestGasTipCap gets the suggested gas tip for a chain.
//
//nolint:wrapcheck
func (c *clientImpl) SuggestGasTipCap(ctx context.Context) (tip *big.Int, err error) {
requestCtx, span := c.startSpan(ctx, MaxPriorityMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().SuggestGasTipCap(requestCtx)
}
// CallContext calls CallContext on the underlying client. Note: this will bypass the rate-limiter.
//
//nolint:wrapcheck
func (c *clientImpl) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) (err error) {
requestCtx, span := c.startSpan(ctx, RPCMethod(method))
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.captureClient.rpcClient.CallContext(requestCtx, result, method, args...)
}
// NonceAt calls NonceAt on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) NonceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (nonce uint64, err error) {
requestCtx, span := c.startSpan(ctx, TransactionCountMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().NonceAt(requestCtx, account, blockNumber)
}
// ChainID calls ChainID on the underlying client.
//
//nolint:wrapcheck
func (c *clientImpl) ChainID(ctx context.Context) (chainID *big.Int, err error) {
requestCtx, span := c.startSpan(ctx, ChainIDMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().ChainID(requestCtx)
}
// FeeHistory calls FeeHistory on the underlying client
//
//nolint:wrapcheck
func (c *clientImpl) FeeHistory(ctx context.Context, blockCount uint64, lastBlock *big.Int, rewardPercentiles []float64) (_ *ethereum.FeeHistory, err error) {
requestCtx, span := c.startSpan(ctx, FeeHistoryMethod)
defer func() {
metrics.EndSpanWithErr(span, err)
}()
return c.getEthClient().FeeHistory(requestCtx, blockCount, lastBlock, rewardPercentiles)
}
// parseCalls parses out calls from w3types.Caller.
func parseCalls(calls []w3types.Caller) attribute.KeyValue {
res := make([]string, len(calls))
for i, call := range calls {
req, err := call.CreateRequest()
if err != nil {
res[i] = fmt.Sprintf("unknown: %v", err)
continue
}
res[i] = req.Method
}
return attribute.StringSlice(methodsAttribute, res)
}
func parseBatch(batchElem []rpc.BatchElem) attribute.KeyValue {
res := make([]string, len(batchElem))
for i, elem := range batchElem {
res[i] = elem.Method
}
return attribute.StringSlice(methodsAttribute, res)
}