-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathapi.go
More file actions
1149 lines (968 loc) · 32.1 KB
/
api.go
File metadata and controls
1149 lines (968 loc) · 32.1 KB
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 api
import (
"context"
"encoding/json"
"fmt"
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/common/lru"
"github.com/ethereum/go-ethereum/common/math"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/eth/filters"
"github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/rpc"
"github.com/rs/zerolog"
evmTypes "github.com/onflow/flow-go/fvm/evm/types"
"github.com/onflow/flow-evm-gateway/config"
ethTypes "github.com/onflow/flow-evm-gateway/eth/types"
"github.com/onflow/flow-evm-gateway/metrics"
"github.com/onflow/flow-evm-gateway/models"
errs "github.com/onflow/flow-evm-gateway/models/errors"
"github.com/onflow/flow-evm-gateway/services/logs"
"github.com/onflow/flow-evm-gateway/services/requester"
"github.com/onflow/flow-evm-gateway/storage"
)
const BlockGasLimit uint64 = 120_000_000
const maxFeeHistoryBlockCount = 1024
var latestBlockNumberOrHash = rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber)
func SupportedAPIs(
blockChainAPI *BlockChainAPI,
streamAPI *StreamAPI,
pullAPI *PullAPI,
debugAPI *DebugAPI,
walletAPI *WalletAPI,
config config.Config,
) []rpc.API {
apis := []rpc.API{{
Namespace: "eth",
Service: blockChainAPI,
}, {
Namespace: "eth",
Service: streamAPI,
}, {
Namespace: "eth",
Service: pullAPI,
}, {
Namespace: "web3",
Service: &Web3API{},
}, {
Namespace: "net",
Service: NewNetAPI(config),
}, {
Namespace: "txpool",
Service: NewTxPoolAPI(),
}}
// optional debug api
if debugAPI != nil {
apis = append(apis, rpc.API{
Namespace: "debug",
Service: debugAPI,
})
}
if walletAPI != nil {
apis = append(apis, rpc.API{
Namespace: "eth",
Service: walletAPI,
})
}
return apis
}
type BlockChainAPI struct {
logger zerolog.Logger
config config.Config
evm requester.Requester
blocks storage.BlockIndexer
transactions storage.TransactionIndexer
receipts storage.ReceiptIndexer
indexingResumedHeight uint64
rateLimiter RateLimiter
collector metrics.Collector
blockByNumberCache *lru.Cache[uint64, *ethTypes.Block]
}
func NewBlockChainAPI(
logger zerolog.Logger,
config config.Config,
evm requester.Requester,
blocks storage.BlockIndexer,
transactions storage.TransactionIndexer,
receipts storage.ReceiptIndexer,
rateLimiter RateLimiter,
collector metrics.Collector,
indexingResumedHeight uint64,
blockByNumberCacheSize int,
) *BlockChainAPI {
return &BlockChainAPI{
logger: logger,
config: config,
evm: evm,
blocks: blocks,
transactions: transactions,
receipts: receipts,
indexingResumedHeight: indexingResumedHeight,
rateLimiter: rateLimiter,
collector: collector,
blockByNumberCache: lru.NewCache[uint64, *ethTypes.Block](blockByNumberCacheSize),
}
}
// BlockNumber returns the block number of the chain head.
func (b *BlockChainAPI) BlockNumber(ctx context.Context) (hexutil.Uint64, error) {
if err := b.rateLimiter.Apply(ctx, EthBlockNumber); err != nil {
return 0, err
}
latestBlockHeight, err := b.blocks.LatestEVMHeight()
if err != nil {
return handleError[hexutil.Uint64](err, b.logger, b.collector)
}
return hexutil.Uint64(latestBlockHeight), nil
}
// Syncing returns false in case the node is currently not syncing with the network.
// It can be up-to-date or has not yet received the latest block headers from its peers.
// In case it is synchronizing:
// - startingBlock: block number this node started to synchronize from
// - currentBlock: block number this node is currently importing
// - highestBlock: block number of the highest block header this node has received from peers
func (b *BlockChainAPI) Syncing(ctx context.Context) (any, error) {
if err := b.rateLimiter.Apply(ctx, EthSyncing); err != nil {
return nil, err
}
currentBlock, err := b.blocks.LatestEVMHeight()
if err != nil {
return handleError[any](err, b.logger, b.collector)
}
highestBlock, err := b.evm.GetLatestEVMHeight(ctx)
if err != nil {
return handleError[any](err, b.logger, b.collector)
}
if currentBlock >= highestBlock {
return false, nil
}
return ethTypes.SyncStatus{
StartingBlock: hexutil.Uint64(b.indexingResumedHeight),
CurrentBlock: hexutil.Uint64(currentBlock),
HighestBlock: hexutil.Uint64(highestBlock),
}, nil
}
// SendRawTransaction will add the signed transaction to the transaction pool.
// The sender is responsible for signing the transaction and using the correct nonce.
func (b *BlockChainAPI) SendRawTransaction(
ctx context.Context,
input hexutil.Bytes,
) (common.Hash, error) {
if b.config.IndexOnly {
return common.Hash{}, errs.ErrIndexOnlyMode
}
l := b.logger.With().
Str("endpoint", EthSendRawTransaction).
Str("input", input.String()).
Logger()
if err := b.rateLimiter.Apply(ctx, EthSendRawTransaction); err != nil {
return common.Hash{}, err
}
id, err := b.evm.SendRawTransaction(ctx, input)
if err != nil {
return handleError[common.Hash](err, l, b.collector)
}
return id, nil
}
// GetBalance returns the amount of wei for the given address in the state of the
// given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
// block numbers are also allowed.
func (b *BlockChainAPI) GetBalance(
ctx context.Context,
address common.Address,
blockNumberOrHash rpc.BlockNumberOrHash,
) (*hexutil.Big, error) {
l := b.logger.With().
Str("endpoint", EthGetBalance).
Str("address", address.String()).
Logger()
if err := b.rateLimiter.Apply(ctx, EthGetBalance); err != nil {
return nil, err
}
height, err := resolveBlockTag(&blockNumberOrHash, b.blocks, b.logger)
if err != nil {
return handleError[*hexutil.Big](err, l, b.collector)
}
balance, err := b.evm.GetBalance(address, height)
if err != nil {
return handleError[*hexutil.Big](err, l, b.collector)
}
return (*hexutil.Big)(balance), nil
}
// GetTransactionByHash returns the transaction for the given hash
func (b *BlockChainAPI) GetTransactionByHash(
ctx context.Context,
hash common.Hash,
) (*ethTypes.Transaction, error) {
l := b.logger.With().
Str("endpoint", EthGetTransactionByHash).
Str("hash", hash.String()).
Logger()
if err := b.rateLimiter.Apply(ctx, EthGetTransactionByHash); err != nil {
return nil, err
}
tx, err := b.transactions.Get(hash)
if err != nil {
return handleError[*ethTypes.Transaction](err, l, b.collector)
}
rcp, err := b.receipts.GetByTransactionID(hash)
if err != nil {
return handleError[*ethTypes.Transaction](err, l, b.collector)
}
return ethTypes.NewTransactionResult(tx, *rcp, b.config.EVMNetworkID)
}
// GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
func (b *BlockChainAPI) GetTransactionByBlockHashAndIndex(
ctx context.Context,
blockHash common.Hash,
index hexutil.Uint,
) (*ethTypes.Transaction, error) {
l := b.logger.With().
Str("endpoint", EthGetTransactionByBlockHashAndIndex).
Str("hash", blockHash.String()).
Str("index", index.String()).
Logger()
if err := b.rateLimiter.Apply(ctx, EthGetTransactionByBlockHashAndIndex); err != nil {
return nil, err
}
block, err := b.blocks.GetByID(blockHash)
if err != nil {
return handleError[*ethTypes.Transaction](err, l, b.collector)
}
if int(index) >= len(block.TransactionHashes) {
return nil, nil
}
txHash := block.TransactionHashes[index]
tx, err := b.prepareTransactionResponse(txHash)
if err != nil {
return handleError[*ethTypes.Transaction](err, l, b.collector)
}
return tx, nil
}
// GetTransactionByBlockNumberAndIndex returns the transaction
// for the given block number and index.
func (b *BlockChainAPI) GetTransactionByBlockNumberAndIndex(
ctx context.Context,
blockNumber rpc.BlockNumber,
index hexutil.Uint,
) (*ethTypes.Transaction, error) {
l := b.logger.With().
Str("endpoint", EthGetTransactionByBlockNumberAndIndex).
Str("number", blockNumber.String()).
Str("index", index.String()).
Logger()
if err := b.rateLimiter.Apply(ctx, EthGetTransactionByBlockNumberAndIndex); err != nil {
return nil, err
}
height, err := resolveBlockNumber(blockNumber, b.blocks)
if err != nil {
return handleError[*ethTypes.Transaction](err, l, b.collector)
}
block, err := b.blocks.GetByHeight(height)
if err != nil {
return handleError[*ethTypes.Transaction](err, l, b.collector)
}
if int(index) >= len(block.TransactionHashes) {
return nil, nil
}
txHash := block.TransactionHashes[index]
tx, err := b.prepareTransactionResponse(txHash)
if err != nil {
return handleError[*ethTypes.Transaction](err, l, b.collector)
}
return tx, nil
}
// GetTransactionReceipt returns the transaction receipt for the given transaction hash.
func (b *BlockChainAPI) GetTransactionReceipt(
ctx context.Context,
hash common.Hash,
) (map[string]any, error) {
l := b.logger.With().
Str("endpoint", EthGetTransactionReceipt).
Str("hash", hash.String()).
Logger()
if err := b.rateLimiter.Apply(ctx, EthGetTransactionReceipt); err != nil {
return nil, err
}
tx, err := b.transactions.Get(hash)
if err != nil {
return handleError[map[string]any](err, l, b.collector)
}
receipt, err := b.receipts.GetByTransactionID(hash)
if err != nil {
return handleError[map[string]any](err, l, b.collector)
}
txReceipt, err := ethTypes.MarshalReceipt(receipt, tx)
if err != nil {
return handleError[map[string]any](err, l, b.collector)
}
return txReceipt, nil
}
// GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full
// detail, otherwise only the transaction hash is returned.
func (b *BlockChainAPI) GetBlockByHash(
ctx context.Context,
hash common.Hash,
fullTx bool,
) (*ethTypes.Block, error) {
l := b.logger.With().
Str("endpoint", EthGetBlockByHash).
Str("hash", hash.String()).
Logger()
if err := b.rateLimiter.Apply(ctx, EthGetBlockByHash); err != nil {
return nil, err
}
block, err := b.blocks.GetByID(hash)
if err != nil {
return handleError[*ethTypes.Block](err, l, b.collector)
}
apiBlock, err := b.prepareBlockResponse(block, fullTx)
if err != nil {
return handleError[*ethTypes.Block](err, l, b.collector)
}
return apiBlock, nil
}
// GetBlockByNumber returns the requested canonical block.
// - When blockNr is -1 the chain pending block is returned.
// - When blockNr is -2 the chain latest block is returned.
// - When blockNr is -3 the chain finalized block is returned.
// - When blockNr is -4 the chain safe block is returned.
// - When blockNr is -5 the chain earliest block is returned.
// - When fullTx is true all transactions in the block are returned, otherwise
// only the transaction hash is returned.
func (b *BlockChainAPI) GetBlockByNumber(
ctx context.Context,
blockNumber rpc.BlockNumber,
fullTx bool,
) (*ethTypes.Block, error) {
l := b.logger.With().
Str("endpoint", EthGetBlockByNumber).
Str("blockNumber", blockNumber.String()).
Logger()
if err := b.rateLimiter.Apply(ctx, EthGetBlockByNumber); err != nil {
return nil, err
}
height, err := resolveBlockNumber(blockNumber, b.blocks)
if err != nil {
return handleError[*ethTypes.Block](err, l, b.collector)
}
if block, ok := b.blockByNumberCache.Get(height); ok {
return block, nil
}
block, err := b.blocks.GetByHeight(height)
if err != nil {
return handleError[*ethTypes.Block](err, l, b.collector)
}
apiBlock, err := b.prepareBlockResponse(block, fullTx)
if err != nil {
return handleError[*ethTypes.Block](err, l, b.collector)
}
_ = b.blockByNumberCache.Add(height, apiBlock)
return apiBlock, nil
}
// GetBlockReceipts returns the block receipts for the given block hash or number or tag.
func (b *BlockChainAPI) GetBlockReceipts(
ctx context.Context,
blockNumberOrHash rpc.BlockNumberOrHash,
) ([]map[string]any, error) {
l := b.logger.With().
Str("endpoint", EthGetBlockReceipts).
Str("hash", blockNumberOrHash.String()).
Logger()
if err := b.rateLimiter.Apply(ctx, EthGetBlockReceipts); err != nil {
return nil, err
}
height, err := resolveBlockTag(&blockNumberOrHash, b.blocks, b.logger)
if err != nil {
return handleError[[]map[string]any](err, l, b.collector)
}
block, err := b.blocks.GetByHeight(height)
if err != nil {
return handleError[[]map[string]any](err, l, b.collector)
}
receipts := make([]map[string]any, len(block.TransactionHashes))
for i, hash := range block.TransactionHashes {
tx, err := b.transactions.Get(hash)
if err != nil {
return handleError[[]map[string]any](err, l, b.collector)
}
receipt, err := b.receipts.GetByTransactionID(hash)
if err != nil {
return handleError[[]map[string]any](err, l, b.collector)
}
receipts[i], err = ethTypes.MarshalReceipt(receipt, tx)
if err != nil {
return handleError[[]map[string]any](err, l, b.collector)
}
}
return receipts, nil
}
// GetBlockTransactionCountByHash returns the number of transactions
// in the block with the given hash.
func (b *BlockChainAPI) GetBlockTransactionCountByHash(
ctx context.Context,
blockHash common.Hash,
) (*hexutil.Uint, error) {
l := b.logger.With().
Str("endpoint", EthGetBlockTransactionCountByHash).
Str("hash", blockHash.String()).
Logger()
if err := b.rateLimiter.Apply(ctx, EthGetBlockTransactionCountByHash); err != nil {
return nil, err
}
block, err := b.blocks.GetByID(blockHash)
if err != nil {
return handleError[*hexutil.Uint](err, l, b.collector)
}
count := hexutil.Uint(len(block.TransactionHashes))
return &count, nil
}
// GetBlockTransactionCountByNumber returns the number of transactions
// in the block with the given block number.
func (b *BlockChainAPI) GetBlockTransactionCountByNumber(
ctx context.Context,
blockNumber rpc.BlockNumber,
) (*hexutil.Uint, error) {
l := b.logger.With().
Str("endpoint", EthGetBlockTransactionCountByNumber).
Str("number", blockNumber.String()).
Logger()
if err := b.rateLimiter.Apply(ctx, EthGetBlockTransactionCountByNumber); err != nil {
return nil, err
}
height, err := resolveBlockNumber(blockNumber, b.blocks)
if err != nil {
return handleError[*hexutil.Uint](err, l, b.collector)
}
block, err := b.blocks.GetByHeight(height)
if err != nil {
return handleError[*hexutil.Uint](err, l, b.collector)
}
count := hexutil.Uint(len(block.TransactionHashes))
return &count, nil
}
// Call executes the given transaction on the state for the given block number.
// Additionally, the caller can specify a batch of contract for fields overriding.
// Note, this function doesn't make and changes in the state/blockchain and is
// useful to execute and retrieve values.
func (b *BlockChainAPI) Call(
ctx context.Context,
args ethTypes.TransactionArgs,
blockNumberOrHash *rpc.BlockNumberOrHash,
stateOverrides *ethTypes.StateOverride,
blockOverrides *ethTypes.BlockOverrides,
) (hexutil.Bytes, error) {
// Default to "latest" block tag
if blockNumberOrHash == nil {
blockNumberOrHash = &latestBlockNumberOrHash
}
stateOverridesArgs, err := json.Marshal(stateOverrides)
if err != nil {
return handleError[hexutil.Bytes](err, b.logger, b.collector)
}
blockOverridesArgs, err := json.Marshal(blockOverrides)
if err != nil {
return handleError[hexutil.Bytes](err, b.logger, b.collector)
}
txArgs, err := json.Marshal(args)
if err != nil {
return handleError[hexutil.Bytes](err, b.logger, b.collector)
}
l := b.logger.With().
Str("endpoint", EthCall).
RawJSON("args", txArgs).
Str("blockTag", fmt.Sprintf("%v", blockNumberOrHash)).
RawJSON("stateOverrides", stateOverridesArgs).
RawJSON("blockOverrides", blockOverridesArgs).
Logger()
if err := b.rateLimiter.Apply(ctx, EthCall); err != nil {
return nil, err
}
if err := args.Validate(); err != nil {
return handleError[hexutil.Bytes](err, l, b.collector)
}
height, err := resolveBlockTag(blockNumberOrHash, b.blocks, b.logger)
if err != nil {
return handleError[hexutil.Bytes](err, l, b.collector)
}
// Default address in case user does not provide one
from := b.config.Coinbase
if args.From != nil {
from = *args.From
}
res, err := b.evm.Call(args, from, height, stateOverrides, blockOverrides)
if err != nil {
return handleError[hexutil.Bytes](err, l, b.collector)
}
return res, nil
}
// GetLogs returns logs matching the given argument that are stored within the state.
func (b *BlockChainAPI) GetLogs(
ctx context.Context,
criteria filters.FilterCriteria,
) ([]*types.Log, error) {
l := b.logger.With().
Str("endpoint", EthGetLogs).
Str("criteria", fmt.Sprintf("%v", criteria)).
Logger()
if err := b.rateLimiter.Apply(ctx, EthGetLogs); err != nil {
return nil, err
}
// if filter provided specific block ID
if criteria.BlockHash != nil {
// Check if the block exists, and return an error if not.
block, err := b.blocks.GetByID(*criteria.BlockHash)
if err != nil {
return nil, err
}
// If the block has no transactions, we can simply return an empty Logs array.
if len(block.TransactionHashes) == 0 {
return []*types.Log{}, nil
}
f, err := logs.NewIDFilter(criteria, b.blocks, b.receipts)
if err != nil {
return handleError[[]*types.Log](err, l, b.collector)
}
res, err := f.Match()
if err != nil {
return handleError[[]*types.Log](err, l, b.collector)
}
return res, nil
}
// otherwise we use the block range as the filter
// assign default values to latest block number, unless provided
from := models.LatestBlockNumber
if criteria.FromBlock != nil {
from = criteria.FromBlock
}
to := models.LatestBlockNumber
if criteria.ToBlock != nil {
to = criteria.ToBlock
}
h, err := b.blocks.LatestEVMHeight()
if err != nil {
return handleError[[]*types.Log](err, l, b.collector)
}
latest := big.NewInt(int64(h))
// if special value, use latest block number
if from.Cmp(models.EarliestBlockNumber) == 0 {
from = big.NewInt(0)
} else if from.Cmp(models.PendingBlockNumber) < 0 {
from = latest
}
if to.Cmp(models.EarliestBlockNumber) == 0 {
to = big.NewInt(0)
} else if to.Cmp(models.PendingBlockNumber) < 0 {
to = latest
}
f, err := logs.NewRangeFilter(from.Uint64(), to.Uint64(), criteria, b.receipts)
if err != nil {
return handleError[[]*types.Log](err, l, b.collector)
}
res, err := f.Match()
if err != nil {
return handleError[[]*types.Log](err, l, b.collector)
}
// makes sure the response is correctly serialized
if res == nil {
return []*types.Log{}, nil
}
return res, nil
}
// GetTransactionCount returns the number of transactions the given address
// has sent for the given block number.
func (b *BlockChainAPI) GetTransactionCount(
ctx context.Context,
address common.Address,
blockNumberOrHash rpc.BlockNumberOrHash,
) (*hexutil.Uint64, error) {
l := b.logger.With().
Str("endpoint", EthGetTransactionCount).
Str("address", address.String()).
Logger()
if err := b.rateLimiter.Apply(ctx, EthGetTransactionCount); err != nil {
return nil, err
}
height, err := resolveBlockTag(&blockNumberOrHash, b.blocks, b.logger)
if err != nil {
return handleError[*hexutil.Uint64](err, l, b.collector)
}
networkNonce, err := b.evm.GetNonce(address, height)
if err != nil {
return handleError[*hexutil.Uint64](err, l, b.collector)
}
return (*hexutil.Uint64)(&networkNonce), nil
}
// EstimateGas returns the lowest possible gas limit that allows the transaction to run
// successfully at block `blockNrOrHash`, or the latest block if `blockNrOrHash` is unspecified. It
// returns error if the transaction would revert or if there are unexpected failures. The returned
// value is capped by both `args.Gas` (if non-nil & non-zero) and the backend's RPCGasCap
// configuration (if non-zero).
func (b *BlockChainAPI) EstimateGas(
ctx context.Context,
args ethTypes.TransactionArgs,
blockNumberOrHash *rpc.BlockNumberOrHash,
stateOverrides *ethTypes.StateOverride,
blockOverrides *ethTypes.BlockOverrides,
) (hexutil.Uint64, error) {
// Default to "latest" block tag
if blockNumberOrHash == nil {
blockNumberOrHash = &latestBlockNumberOrHash
}
stateOverridesArgs, err := json.Marshal(stateOverrides)
if err != nil {
return handleError[hexutil.Uint64](err, b.logger, b.collector)
}
blockOverridesArgs, err := json.Marshal(blockOverrides)
if err != nil {
return handleError[hexutil.Uint64](err, b.logger, b.collector)
}
txArgs, err := json.Marshal(args)
if err != nil {
return handleError[hexutil.Uint64](err, b.logger, b.collector)
}
l := b.logger.With().
Str("endpoint", EthEstimateGas).
RawJSON("args", txArgs).
Str("blockTag", fmt.Sprintf("%v", blockNumberOrHash)).
RawJSON("stateOverrides", stateOverridesArgs).
RawJSON("blockOverrides", blockOverridesArgs).
Logger()
if err := b.rateLimiter.Apply(ctx, EthEstimateGas); err != nil {
return 0, err
}
if err := args.Validate(); err != nil {
return handleError[hexutil.Uint64](err, l, b.collector)
}
// Default address in case user does not provide one
from := b.config.Coinbase
if args.From != nil {
from = *args.From
}
height, err := resolveBlockTag(blockNumberOrHash, b.blocks, b.logger)
if err != nil {
return handleError[hexutil.Uint64](err, l, b.collector)
}
estimatedGas, err := b.evm.EstimateGas(
args,
from,
height,
stateOverrides,
blockOverrides,
)
if err != nil {
return handleError[hexutil.Uint64](err, l, b.collector)
}
return hexutil.Uint64(estimatedGas), nil
}
// GetCode returns the code stored at the given address in
// the state for the given block number.
func (b *BlockChainAPI) GetCode(
ctx context.Context,
address common.Address,
blockNumberOrHash rpc.BlockNumberOrHash,
) (hexutil.Bytes, error) {
l := b.logger.With().
Str("endpoint", EthGetCode).
Str("address", address.String()).
Logger()
if err := b.rateLimiter.Apply(ctx, EthGetCode); err != nil {
return nil, err
}
height, err := resolveBlockTag(&blockNumberOrHash, b.blocks, b.logger)
if err != nil {
return handleError[hexutil.Bytes](err, l, b.collector)
}
code, err := b.evm.GetCode(address, height)
if err != nil {
return handleError[hexutil.Bytes](err, l, b.collector)
}
return code, nil
}
// FeeHistory returns transaction base fee per gas and effective priority fee
// per gas for the requested/supported block range.
// blockCount: Requested range of blocks. Clients will return less than the
// requested range if not all blocks are available.
// lastBlock: Highest block of the requested range.
// rewardPercentiles: A monotonically increasing list of percentile values.
// For each block in the requested range, the transactions will be sorted in
// ascending order by effective tip per gas and the coresponding effective tip
// for the percentile will be determined, accounting for gas consumed.
func (b *BlockChainAPI) FeeHistory(
ctx context.Context,
blockCount math.HexOrDecimal64,
lastBlock rpc.BlockNumber,
rewardPercentiles []float64,
) (*ethTypes.FeeHistoryResult, error) {
l := b.logger.With().
Str("endpoint", EthFeeHistory).
Str("block", lastBlock.String()).
Logger()
if err := b.rateLimiter.Apply(ctx, EthFeeHistory); err != nil {
return nil, err
}
if blockCount > maxFeeHistoryBlockCount {
return handleError[*ethTypes.FeeHistoryResult](
fmt.Errorf("block count has to be between 1 and %d, got: %d", maxFeeHistoryBlockCount, blockCount),
l,
b.collector,
)
}
lastBlockNumber, err := resolveBlockNumber(lastBlock, b.blocks)
if err != nil {
return handleError[*ethTypes.FeeHistoryResult](err, l, b.collector)
}
var (
oldestBlock *hexutil.Big
baseFees []*hexutil.Big
rewards [][]*hexutil.Big
gasUsedRatios []float64
)
maxCount := min(uint64(blockCount), lastBlockNumber)
blockRewards := make([]*hexutil.Big, len(rewardPercentiles))
for i := range rewardPercentiles {
blockRewards[i] = (*hexutil.Big)(b.config.GasPrice)
}
for i := maxCount; i >= uint64(1); i-- {
// If the requested block count is 5, and the last block number
// is 20, then we need the blocks [16, 17, 18, 19, 20] in this
// specific order. The first block we fetch is 20 - 5 + 1 = 16.
blockHeight := lastBlockNumber - i + 1
block, err := b.blocks.GetByHeight(blockHeight)
if err != nil {
continue
}
if i == maxCount {
oldestBlock = (*hexutil.Big)(big.NewInt(int64(block.Height)))
}
baseFees = append(baseFees, (*hexutil.Big)(models.BaseFeePerGas))
rewards = append(rewards, blockRewards)
gasUsedRatio := float64(block.TotalGasUsed) / float64(BlockGasLimit)
gasUsedRatios = append(gasUsedRatios, gasUsedRatio)
}
return ðTypes.FeeHistoryResult{
OldestBlock: oldestBlock,
Reward: rewards,
BaseFee: baseFees,
GasUsedRatio: gasUsedRatios,
}, nil
}
// GetStorageAt returns the storage from the state at the given address, key and
// block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block
// numbers are also allowed.
func (b *BlockChainAPI) GetStorageAt(
ctx context.Context,
address common.Address,
storageSlot string,
blockNumberOrHash rpc.BlockNumberOrHash,
) (hexutil.Bytes, error) {
l := b.logger.With().
Str("endpoint", EthGetStorageAt).
Str("address", address.String()).
Logger()
if err := b.rateLimiter.Apply(ctx, EthGetStorageAt); err != nil {
return nil, err
}
key, err := decodeHash(storageSlot)
if err != nil {
return handleError[hexutil.Bytes](
fmt.Errorf("%w: %w", errs.ErrInvalid, err),
l,
b.collector,
)
}
height, err := resolveBlockTag(&blockNumberOrHash, b.blocks, b.logger)
if err != nil {
return handleError[hexutil.Bytes](err, l, b.collector)
}
result, err := b.evm.GetStorageAt(address, key, height)
if err != nil {
return handleError[hexutil.Bytes](err, l, b.collector)
}
return result[:], nil
}
func (b *BlockChainAPI) fetchBlockTransactions(
block *models.Block,
) ([]*ethTypes.Transaction, error) {
transactions := make([]*ethTypes.Transaction, 0)
for _, txHash := range block.TransactionHashes {
transaction, err := b.prepareTransactionResponse(txHash)
if err != nil {
return nil, err
}
if transaction == nil {
b.logger.Error().
Str("tx-hash", txHash.String()).
Uint64("evm-height", block.Height).
Msg("not found a transaction the block references")
continue
}
transactions = append(transactions, transaction)
}
return transactions, nil
}
func (b *BlockChainAPI) prepareTransactionResponse(
txHash common.Hash,
) (*ethTypes.Transaction, error) {
tx, err := b.transactions.Get(txHash)
if err != nil {
return nil, err
}
receipt, err := b.receipts.GetByTransactionID(txHash)
if err != nil {
return nil, err
}
return ethTypes.NewTransactionResult(tx, *receipt, b.config.EVMNetworkID)
}
func (b *BlockChainAPI) prepareBlockResponse(
block *models.Block,
fullTx bool,
) (*ethTypes.Block, error) {
h, err := block.Hash()
if err != nil {
b.logger.Error().Err(err).Msg("failed to calculate hash for block by number")
return nil, err
}
blockResponse := ðTypes.Block{
Hash: h,
Number: hexutil.Uint64(block.Height),
ParentHash: block.ParentBlockHash,
ReceiptsRoot: block.ReceiptRoot,
TransactionsRoot: block.TransactionHashRoot,
Transactions: block.TransactionHashes,
Uncles: []common.Hash{},
GasLimit: hexutil.Uint64(BlockGasLimit),
Nonce: types.BlockNonce{0x1},
Timestamp: hexutil.Uint64(block.Timestamp),
BaseFeePerGas: hexutil.Big(*models.BaseFeePerGas),
LogsBloom: types.CreateBloom(&types.Receipt{}).Bytes(),
Miner: evmTypes.CoinbaseAddress.ToCommon(),