forked from okx/xlayer-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
endpoints_zkevm.go
695 lines (605 loc) · 28.2 KB
/
endpoints_zkevm.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
package jsonrpc
import (
"context"
"encoding/json"
"errors"
"fmt"
"math/big"
"time"
"github.com/0xPolygonHermez/zkevm-node/hex"
"github.com/0xPolygonHermez/zkevm-node/jsonrpc/client"
"github.com/0xPolygonHermez/zkevm-node/jsonrpc/types"
"github.com/0xPolygonHermez/zkevm-node/log"
"github.com/0xPolygonHermez/zkevm-node/pool"
"github.com/0xPolygonHermez/zkevm-node/state"
"github.com/0xPolygonHermez/zkevm-node/state/runtime"
"github.com/0xPolygonHermez/zkevm-node/state/runtime/executor"
"github.com/ethereum/go-ethereum/common"
ethTypes "github.com/ethereum/go-ethereum/core/types"
"github.com/jackc/pgx/v4"
)
// ZKEVMEndpoints contains implementations for the "zkevm" RPC endpoints
type ZKEVMEndpoints struct {
cfg Config
pool types.PoolInterface
state types.StateInterface
etherman types.EthermanInterface
txMan DBTxManager
}
// NewZKEVMEndpoints returns ZKEVMEndpoints
func NewZKEVMEndpoints(cfg Config, pool types.PoolInterface, state types.StateInterface, etherman types.EthermanInterface) *ZKEVMEndpoints {
return &ZKEVMEndpoints{
cfg: cfg,
pool: pool,
state: state,
etherman: etherman,
}
}
// ConsolidatedBlockNumber returns last block number related to the last verified batch
func (z *ZKEVMEndpoints) ConsolidatedBlockNumber() (interface{}, types.Error) {
return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
lastBlockNumber, err := z.state.GetLastConsolidatedL2BlockNumber(ctx, dbTx)
if err != nil {
const errorMessage = "failed to get last consolidated block number from state"
log.Errorf("%v:%v", errorMessage, err)
return nil, types.NewRPCError(types.DefaultErrorCode, errorMessage)
}
return hex.EncodeUint64(lastBlockNumber), nil
})
}
// IsBlockConsolidated returns the consolidation status of a provided block number
func (z *ZKEVMEndpoints) IsBlockConsolidated(blockNumber types.ArgUint64) (interface{}, types.Error) {
return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
IsL2BlockConsolidated, err := z.state.IsL2BlockConsolidated(ctx, uint64(blockNumber), dbTx)
if err != nil {
const errorMessage = "failed to check if the block is consolidated"
log.Errorf("%v: %v", errorMessage, err)
return nil, types.NewRPCError(types.DefaultErrorCode, errorMessage)
}
return IsL2BlockConsolidated, nil
})
}
// IsBlockVirtualized returns the virtualization status of a provided block number
func (z *ZKEVMEndpoints) IsBlockVirtualized(blockNumber types.ArgUint64) (interface{}, types.Error) {
return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
IsL2BlockVirtualized, err := z.state.IsL2BlockVirtualized(ctx, uint64(blockNumber), dbTx)
if err != nil {
const errorMessage = "failed to check if the block is virtualized"
log.Errorf("%v: %v", errorMessage, err)
return nil, types.NewRPCError(types.DefaultErrorCode, errorMessage)
}
return IsL2BlockVirtualized, nil
})
}
// BatchNumberByBlockNumber returns the batch number from which the passed block number is created
func (z *ZKEVMEndpoints) BatchNumberByBlockNumber(blockNumber types.ArgUint64) (interface{}, types.Error) {
return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
batchNum, err := z.state.BatchNumberByL2BlockNumber(ctx, uint64(blockNumber), dbTx)
if errors.Is(err, state.ErrNotFound) {
return nil, nil
} else if err != nil {
const errorMessage = "failed to get batch number from block number"
log.Errorf("%v: %v", errorMessage, err.Error())
return nil, types.NewRPCError(types.DefaultErrorCode, errorMessage)
}
return hex.EncodeUint64(batchNum), nil
})
}
// BatchNumber returns the latest trusted batch number
func (z *ZKEVMEndpoints) BatchNumber() (interface{}, types.Error) {
return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
lastBatchNumber, err := z.state.GetLastBatchNumber(ctx, dbTx)
if err != nil {
return "0x0", types.NewRPCError(types.DefaultErrorCode, "failed to get the last batch number from state")
}
return hex.EncodeUint64(lastBatchNumber), nil
})
}
// VirtualBatchNumber returns the latest virtualized batch number
func (z *ZKEVMEndpoints) VirtualBatchNumber() (interface{}, types.Error) {
return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
lastBatchNumber, err := z.state.GetLastVirtualBatchNum(ctx, dbTx)
if err != nil {
return "0x0", types.NewRPCError(types.DefaultErrorCode, "failed to get the last virtual batch number from state")
}
return hex.EncodeUint64(lastBatchNumber), nil
})
}
// VerifiedBatchNumber returns the latest verified batch number
func (z *ZKEVMEndpoints) VerifiedBatchNumber() (interface{}, types.Error) {
return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
lastBatch, err := z.state.GetLastVerifiedBatch(ctx, dbTx)
if err != nil {
return "0x0", types.NewRPCError(types.DefaultErrorCode, "failed to get the last verified batch number from state")
}
return hex.EncodeUint64(lastBatch.BatchNumber), nil
})
}
// GetBatchByNumber returns information about a batch by batch number
func (z *ZKEVMEndpoints) GetBatchByNumber(batchNumber types.BatchNumber, fullTx bool) (interface{}, types.Error) {
return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
var err error
batchNumber, rpcErr := batchNumber.GetNumericBatchNumber(ctx, z.state, z.etherman, dbTx)
if rpcErr != nil {
return nil, rpcErr
}
batch, err := z.state.GetBatchByNumber(ctx, batchNumber, dbTx)
if errors.Is(err, state.ErrNotFound) {
return nil, nil
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, fmt.Sprintf("couldn't load batch from state by number %v", batchNumber), err, true)
}
batchTimestamp, err := z.state.GetBatchTimestamp(ctx, batchNumber, nil, dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, fmt.Sprintf("couldn't load batch timestamp from state by number %v", batchNumber), err, true)
}
if batchTimestamp == nil {
batch.Timestamp = time.Time{}
} else {
batch.Timestamp = *batchTimestamp
}
txs, _, err := z.state.GetTransactionsByBatchNumber(ctx, batchNumber, dbTx)
if !errors.Is(err, state.ErrNotFound) && err != nil {
return RPCErrorResponse(types.DefaultErrorCode, fmt.Sprintf("couldn't load batch txs from state by number %v", batchNumber), err, true)
}
receipts := make([]ethTypes.Receipt, 0, len(txs))
for _, tx := range txs {
receipt, err := z.state.GetTransactionReceipt(ctx, tx.Hash(), dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, fmt.Sprintf("couldn't load receipt for tx %v", tx.Hash().String()), err, true)
}
receipts = append(receipts, *receipt)
}
virtualBatch, err := z.state.GetVirtualBatch(ctx, batchNumber, dbTx)
if err != nil && !errors.Is(err, state.ErrNotFound) {
return RPCErrorResponse(types.DefaultErrorCode, fmt.Sprintf("couldn't load virtual batch from state by number %v", batchNumber), err, true)
}
verifiedBatch, err := z.state.GetVerifiedBatch(ctx, batchNumber, dbTx)
if err != nil && !errors.Is(err, state.ErrNotFound) {
return RPCErrorResponse(types.DefaultErrorCode, fmt.Sprintf("couldn't load virtual batch from state by number %v", batchNumber), err, true)
}
ger, err := z.state.GetExitRootByGlobalExitRoot(ctx, batch.GlobalExitRoot, dbTx)
if err != nil && !errors.Is(err, state.ErrNotFound) {
return RPCErrorResponse(types.DefaultErrorCode, fmt.Sprintf("couldn't load full GER from state by number %v", batchNumber), err, true)
} else if errors.Is(err, state.ErrNotFound) {
ger = &state.GlobalExitRoot{}
}
blocks, err := z.state.GetL2BlocksByBatchNumber(ctx, batchNumber, dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, fmt.Sprintf("couldn't load blocks associated to the batch %v", batchNumber), err, true)
}
batch.Transactions = txs
rpcBatch, err := types.NewBatch(ctx, z.state, batch, virtualBatch, verifiedBatch, blocks, receipts, fullTx, true, ger, dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, fmt.Sprintf("couldn't build the batch %v response", batchNumber), err, true)
}
return rpcBatch, nil
})
}
// GetBatchDataByNumbers returns the batch data for batches by numbers
func (z *ZKEVMEndpoints) GetBatchDataByNumbers(filter types.BatchFilter) (interface{}, types.Error) {
return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
var batchNumbers []uint64
for _, bn := range filter.Numbers {
n, rpcErr := bn.GetNumericBatchNumber(ctx, z.state, z.etherman, dbTx)
if rpcErr != nil {
return nil, rpcErr
}
batchNumbers = append(batchNumbers, n)
}
batchesData, err := z.state.GetBatchL2DataByNumbers(ctx, batchNumbers, dbTx)
if errors.Is(err, state.ErrNotFound) {
return nil, nil
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode,
fmt.Sprintf("couldn't load batch data from state by numbers %v", filter.Numbers), err, true)
}
var ret []*types.BatchData
for _, n := range batchNumbers {
data := &types.BatchData{Number: types.ArgUint64(n)}
if b, ok := batchesData[n]; ok {
data.BatchL2Data = b
data.Empty = false
} else {
data.Empty = true
}
ret = append(ret, data)
}
return types.BatchDataResult{Data: ret}, nil
})
}
// GetFullBlockByNumber returns information about a block by block number
func (z *ZKEVMEndpoints) GetFullBlockByNumber(number types.BlockNumber, fullTx bool) (interface{}, types.Error) {
return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
if number == types.PendingBlockNumber {
lastBlock, err := z.state.GetLastL2Block(ctx, dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "couldn't load last block from state to compute the pending block", err, true)
}
l2Header := state.NewL2Header(ðTypes.Header{
ParentHash: lastBlock.Hash(),
Number: big.NewInt(0).SetUint64(lastBlock.Number().Uint64() + 1),
TxHash: ethTypes.EmptyRootHash,
UncleHash: ethTypes.EmptyUncleHash,
})
l2Block := state.NewL2BlockWithHeader(l2Header)
rpcBlock, err := types.NewBlock(ctx, z.state, nil, l2Block, nil, fullTx, false, state.Ptr(true), dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "couldn't build the pending block response", err, true)
}
// clean fields that are not available for pending block
rpcBlock.Hash = nil
rpcBlock.Miner = nil
rpcBlock.Nonce = nil
rpcBlock.TotalDifficulty = nil
return rpcBlock, nil
}
var err error
blockNumber, rpcErr := number.GetNumericBlockNumber(ctx, z.state, z.etherman, dbTx)
if rpcErr != nil {
return nil, rpcErr
}
l2Block, err := z.state.GetL2BlockByNumber(ctx, blockNumber, dbTx)
if errors.Is(err, state.ErrNotFound) {
return nil, nil
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, fmt.Sprintf("couldn't load block from state by number %v", blockNumber), err, true)
}
txs := l2Block.Transactions()
receipts := make([]ethTypes.Receipt, 0, len(txs))
for _, tx := range txs {
receipt, err := z.state.GetTransactionReceipt(ctx, tx.Hash(), dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, fmt.Sprintf("couldn't load receipt for tx %v", tx.Hash().String()), err, true)
}
receipts = append(receipts, *receipt)
}
rpcBlock, err := types.NewBlock(ctx, z.state, state.Ptr(l2Block.Hash()), l2Block, receipts, fullTx, true, state.Ptr(true), dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, fmt.Sprintf("couldn't build block response for block by number %v", blockNumber), err, true)
}
return rpcBlock, nil
})
}
// GetFullBlockByHash returns information about a block by hash
func (z *ZKEVMEndpoints) GetFullBlockByHash(hash types.ArgHash, fullTx bool) (interface{}, types.Error) {
return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
l2Block, err := z.state.GetL2BlockByHash(ctx, hash.Hash(), dbTx)
if errors.Is(err, state.ErrNotFound) {
return nil, nil
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get block by hash from state", err, true)
}
txs := l2Block.Transactions()
receipts := make([]ethTypes.Receipt, 0, len(txs))
for _, tx := range txs {
receipt, err := z.state.GetTransactionReceipt(ctx, tx.Hash(), dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, fmt.Sprintf("couldn't load receipt for tx %v", tx.Hash().String()), err, true)
}
receipts = append(receipts, *receipt)
}
rpcBlock, err := types.NewBlock(ctx, z.state, state.Ptr(l2Block.Hash()), l2Block, receipts, fullTx, true, state.Ptr(true), dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, fmt.Sprintf("couldn't build block response for block by hash %v", hash.Hash()), err, true)
}
return rpcBlock, nil
})
}
// GetNativeBlockHashesInRange return the state root for the blocks in range
func (z *ZKEVMEndpoints) GetNativeBlockHashesInRange(filter NativeBlockHashBlockRangeFilter) (interface{}, types.Error) {
return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
fromBlockNumber, toBlockNumber, rpcErr := filter.GetNumericBlockNumbers(ctx, z.cfg, z.state, z.etherman, dbTx)
if rpcErr != nil {
return nil, rpcErr
}
nativeBlockHashes, err := z.state.GetNativeBlockHashesInRange(ctx, fromBlockNumber, toBlockNumber, dbTx)
if errors.Is(err, state.ErrNotFound) {
return nil, nil
} else if errors.Is(err, state.ErrMaxNativeBlockHashBlockRangeLimitExceeded) {
errMsg := fmt.Sprintf(state.ErrMaxNativeBlockHashBlockRangeLimitExceeded.Error(), z.cfg.MaxNativeBlockHashBlockRange)
return RPCErrorResponse(types.InvalidParamsErrorCode, errMsg, nil, false)
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get block by hash from state", err, true)
}
return nativeBlockHashes, nil
})
}
// GetTransactionByL2Hash returns a transaction by his l2 hash
func (z *ZKEVMEndpoints) GetTransactionByL2Hash(hash types.ArgHash) (interface{}, types.Error) {
return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
// try to get tx from state
tx, err := z.state.GetTransactionByL2Hash(ctx, hash.Hash(), dbTx)
if err != nil && !errors.Is(err, state.ErrNotFound) {
return RPCErrorResponse(types.DefaultErrorCode, "failed to load transaction by l2 hash from state", err, true)
}
if tx != nil {
receipt, err := z.state.GetTransactionReceipt(ctx, hash.Hash(), dbTx)
if errors.Is(err, state.ErrNotFound) {
return RPCErrorResponse(types.DefaultErrorCode, "transaction receipt not found", err, false)
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to load transaction receipt from state", err, true)
}
l2Hash, err := z.state.GetL2TxHashByTxHash(ctx, tx.Hash(), dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get l2 transaction hash", err, true)
}
res, err := types.NewTransaction(*tx, receipt, false, l2Hash)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to build transaction response", err, true)
}
return res, nil
}
// if the tx does not exist in the state, look for it in the pool
if z.cfg.SequencerNodeURI != "" {
return z.getTransactionByL2HashFromSequencerNode(hash.Hash())
}
poolTx, err := z.pool.GetTransactionByL2Hash(ctx, hash.Hash())
if errors.Is(err, pool.ErrNotFound) {
return nil, nil
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to load transaction by l2 hash from pool", err, true)
}
if poolTx.Status == pool.TxStatusPending {
tx = &poolTx.Transaction
res, err := types.NewTransaction(*tx, nil, false, nil)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to build transaction response", err, true)
}
return res, nil
}
return nil, nil
})
}
// GetTransactionReceiptByL2Hash returns a transaction receipt by his hash
func (z *ZKEVMEndpoints) GetTransactionReceiptByL2Hash(hash types.ArgHash) (interface{}, types.Error) {
return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
tx, err := z.state.GetTransactionByL2Hash(ctx, hash.Hash(), dbTx)
if errors.Is(err, state.ErrNotFound) {
return nil, nil
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get tx from state", err, true)
}
r, err := z.state.GetTransactionReceipt(ctx, hash.Hash(), dbTx)
if errors.Is(err, state.ErrNotFound) {
return nil, nil
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get tx receipt from state", err, true)
}
l2Hash, err := z.state.GetL2TxHashByTxHash(ctx, tx.Hash(), dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get l2 transaction hash", err, true)
}
receipt, err := types.NewReceipt(*tx, r, l2Hash)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to build the receipt response", err, true)
}
return receipt, nil
})
}
func (z *ZKEVMEndpoints) getTransactionByL2HashFromSequencerNode(hash common.Hash) (interface{}, types.Error) {
res, err := client.JSONRPCCall(z.cfg.SequencerNodeURI, "zkevm_getTransactionByL2Hash", hash.String())
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get tx from sequencer node by l2 hash", err, true)
}
if res.Error != nil {
return RPCErrorResponse(res.Error.Code, res.Error.Message, nil, false)
}
var tx *types.Transaction
err = json.Unmarshal(res.Result, &tx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to read tx loaded by l2 hash from sequencer node", err, true)
}
return tx, nil
}
// GetExitRootsByGER returns the exit roots accordingly to the provided Global Exit Root
func (z *ZKEVMEndpoints) GetExitRootsByGER(globalExitRoot common.Hash) (interface{}, types.Error) {
return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
exitRoots, err := z.state.GetExitRootByGlobalExitRoot(ctx, globalExitRoot, dbTx)
if errors.Is(err, state.ErrNotFound) {
return nil, nil
} else if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to get exit roots by global exit root from state", err, true)
}
return types.ExitRoots{
BlockNumber: types.ArgUint64(exitRoots.BlockNumber),
Timestamp: types.ArgUint64(exitRoots.Timestamp.Unix()),
MainnetExitRoot: exitRoots.MainnetExitRoot,
RollupExitRoot: exitRoots.RollupExitRoot,
}, nil
})
}
// EstimateGasPrice returns an estimate gas price for the transaction.
func (z *ZKEVMEndpoints) EstimateGasPrice(arg *types.TxArgs, blockArg *types.BlockNumberOrHash) (interface{}, types.Error) {
return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
gasPrice, _, err := z.internalEstimateGasPriceAndFee(ctx, arg, blockArg, dbTx)
if err != nil {
return nil, err
}
return hex.EncodeBig(gasPrice), nil
})
}
// EstimateFee returns an estimate fee for the transaction.
func (z *ZKEVMEndpoints) EstimateFee(arg *types.TxArgs, blockArg *types.BlockNumberOrHash) (interface{}, types.Error) {
return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
_, fee, err := z.internalEstimateGasPriceAndFee(ctx, arg, blockArg, dbTx)
if err != nil {
return nil, err
}
return hex.EncodeBig(fee), nil
})
}
// internalEstimateGasPriceAndFee computes the estimated gas price and the estimated fee for the transaction
func (z *ZKEVMEndpoints) internalEstimateGasPriceAndFee(ctx context.Context, arg *types.TxArgs, blockArg *types.BlockNumberOrHash, dbTx pgx.Tx) (*big.Int, *big.Int, types.Error) {
if arg == nil {
return nil, nil, types.NewRPCError(types.InvalidParamsErrorCode, "missing value for required argument 0")
}
block, respErr := z.getBlockByArg(ctx, blockArg, dbTx)
if respErr != nil {
return nil, nil, respErr
}
var blockToProcess *uint64
if blockArg != nil {
blockNumArg := blockArg.Number()
if blockNumArg != nil && (*blockArg.Number() == types.LatestBlockNumber || *blockArg.Number() == types.PendingBlockNumber) {
blockToProcess = nil
} else {
n := block.NumberU64()
blockToProcess = &n
}
}
defaultSenderAddress := common.HexToAddress(state.DefaultSenderAddress)
sender, tx, err := arg.ToTransaction(ctx, z.state, z.cfg.MaxCumulativeGasUsed, block.Root(), defaultSenderAddress, dbTx)
if err != nil {
return nil, nil, types.NewRPCError(types.DefaultErrorCode, "failed to convert arguments into an unsigned transaction")
}
gasEstimation, returnValue, err := z.state.EstimateGas(tx, sender, blockToProcess, dbTx)
if errors.Is(err, runtime.ErrExecutionReverted) {
data := make([]byte, len(returnValue))
copy(data, returnValue)
return nil, nil, types.NewRPCErrorWithData(types.RevertedErrorCode, err.Error(), data)
} else if err != nil {
errMsg := fmt.Sprintf("failed to estimate gas: %v", err.Error())
return nil, nil, types.NewRPCError(types.DefaultErrorCode, errMsg)
}
gasPrices, err := z.pool.GetGasPrices(ctx)
if err != nil {
return nil, nil, types.NewRPCError(types.DefaultErrorCode, "failed to get L2 gas price", err, false)
}
txGasPrice := new(big.Int).SetUint64(gasPrices.L2GasPrice) // by default we assume the tx gas price is the current L2 gas price
txEGPPct := state.MaxEffectivePercentage
egpEnabled := z.pool.EffectiveGasPriceEnabled()
if egpEnabled {
rawTx, err := state.EncodeTransactionWithoutEffectivePercentage(*tx)
if err != nil {
return nil, nil, types.NewRPCError(types.DefaultErrorCode, "failed to encode tx", err, false)
}
txEGP, err := z.pool.CalculateEffectiveGasPrice(rawTx, txGasPrice, gasEstimation, gasPrices.L1GasPrice, gasPrices.L2GasPrice)
if err != nil {
return nil, nil, types.NewRPCError(types.DefaultErrorCode, "failed to calculate effective gas price", err, false)
}
if txEGP.Cmp(txGasPrice) == -1 { // txEGP < txGasPrice
// We need to "round" the final effectiveGasPrice to a 256 fraction of the txGasPrice
txEGPPct, err = state.CalculateEffectiveGasPricePercentage(txGasPrice, txEGP)
if err != nil {
return nil, nil, types.NewRPCError(types.DefaultErrorCode, "failed to calculate effective gas price percentage", err, false)
}
// txGasPriceFraction = txGasPrice/256
txGasPriceFraction := new(big.Int).Div(txGasPrice, new(big.Int).SetUint64(256)) //nolint:gomnd
// txGasPrice = txGasPriceFraction*(txEGPPct+1)
txGasPrice = new(big.Int).Mul(txGasPriceFraction, new(big.Int).SetUint64(uint64(txEGPPct+1)))
}
log.Infof("[internalEstimateGasPriceAndFee] finalGasPrice: %d, effectiveGasPrice: %d, egpPct: %d, l2GasPrice: %d, len: %d, gas: %d, l1GasPrice: %d",
txGasPrice, txEGP, txEGPPct, gasPrices.L2GasPrice, len(rawTx), gasEstimation, gasPrices.L1GasPrice)
}
fee := new(big.Int).Mul(txGasPrice, new(big.Int).SetUint64(gasEstimation))
log.Infof("[internalEstimateGasPriceAndFee] egpEnabled: %t, fee: %d, gasPrice: %d, gas: %d", egpEnabled, fee, txGasPrice, gasEstimation)
return txGasPrice, fee, nil
}
// EstimateCounters returns an estimation of the counters that are going to be used while executing
// this transaction.
func (z *ZKEVMEndpoints) EstimateCounters(arg *types.TxArgs, blockArg *types.BlockNumberOrHash) (interface{}, types.Error) {
return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
if arg == nil {
return RPCErrorResponse(types.InvalidParamsErrorCode, "missing value for required argument 0", nil, false)
}
block, respErr := z.getBlockByArg(ctx, blockArg, dbTx)
if respErr != nil {
return nil, respErr
}
var blockToProcess *uint64
if blockArg != nil {
blockNumArg := blockArg.Number()
if blockNumArg != nil && (*blockArg.Number() == types.LatestBlockNumber || *blockArg.Number() == types.PendingBlockNumber) {
blockToProcess = nil
} else {
n := block.NumberU64()
blockToProcess = &n
}
}
defaultSenderAddress := common.HexToAddress(state.DefaultSenderAddress)
sender, tx, err := arg.ToTransaction(ctx, z.state, z.cfg.MaxCumulativeGasUsed, block.Root(), defaultSenderAddress, dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "failed to convert arguments into an unsigned transaction", err, false)
}
var oocErr error
processBatchResponse, err := z.state.PreProcessUnsignedTransaction(ctx, tx, sender, blockToProcess, dbTx)
if err != nil {
if executor.IsROMOutOfCountersError(executor.RomErrorCode(err)) {
oocErr = err
} else {
errMsg := fmt.Sprintf("failed to estimate counters: %v", err.Error())
return nil, types.NewRPCError(types.DefaultErrorCode, errMsg)
}
}
var revert *types.RevertInfo
if len(processBatchResponse.BlockResponses) > 0 && len(processBatchResponse.BlockResponses[0].TransactionResponses) > 0 {
txResponse := processBatchResponse.BlockResponses[0].TransactionResponses[0]
err = txResponse.RomError
if errors.Is(err, runtime.ErrExecutionReverted) {
returnValue := make([]byte, len(txResponse.ReturnValue))
copy(returnValue, txResponse.ReturnValue)
err := state.ConstructErrorFromRevert(err, returnValue)
revert = &types.RevertInfo{
Message: err.Error(),
Data: state.Ptr(types.ArgBytes(returnValue)),
}
}
}
limits := types.ZKCountersLimits{
MaxGasUsed: types.ArgUint64(state.MaxTxGasLimit),
MaxKeccakHashes: types.ArgUint64(z.cfg.ZKCountersLimits.MaxKeccakHashes),
MaxPoseidonHashes: types.ArgUint64(z.cfg.ZKCountersLimits.MaxPoseidonHashes),
MaxPoseidonPaddings: types.ArgUint64(z.cfg.ZKCountersLimits.MaxPoseidonPaddings),
MaxMemAligns: types.ArgUint64(z.cfg.ZKCountersLimits.MaxMemAligns),
MaxArithmetics: types.ArgUint64(z.cfg.ZKCountersLimits.MaxArithmetics),
MaxBinaries: types.ArgUint64(z.cfg.ZKCountersLimits.MaxBinaries),
MaxSteps: types.ArgUint64(z.cfg.ZKCountersLimits.MaxSteps),
MaxSHA256Hashes: types.ArgUint64(z.cfg.ZKCountersLimits.MaxSHA256Hashes),
}
return types.NewZKCountersResponse(processBatchResponse.UsedZkCounters, limits, revert, oocErr), nil
})
}
func (z *ZKEVMEndpoints) getBlockByArg(ctx context.Context, blockArg *types.BlockNumberOrHash, dbTx pgx.Tx) (*state.L2Block, types.Error) {
// If no block argument is provided, return the latest block
if blockArg == nil {
block, err := z.state.GetLastL2Block(ctx, dbTx)
if err != nil {
return nil, types.NewRPCError(types.DefaultErrorCode, "failed to get the last block number from state")
}
return block, nil
}
// If we have a block hash, try to get the block by hash
if blockArg.IsHash() {
block, err := z.state.GetL2BlockByHash(ctx, blockArg.Hash().Hash(), dbTx)
if errors.Is(err, state.ErrNotFound) {
return nil, types.NewRPCError(types.DefaultErrorCode, "header for hash not found")
} else if err != nil {
return nil, types.NewRPCError(types.DefaultErrorCode, fmt.Sprintf("failed to get block by hash %v", blockArg.Hash().Hash()))
}
return block, nil
}
// Otherwise, try to get the block by number
blockNum, rpcErr := blockArg.Number().GetNumericBlockNumber(ctx, z.state, z.etherman, dbTx)
if rpcErr != nil {
return nil, rpcErr
}
block, err := z.state.GetL2BlockByNumber(context.Background(), blockNum, dbTx)
if errors.Is(err, state.ErrNotFound) || block == nil {
return nil, types.NewRPCError(types.DefaultErrorCode, "header not found")
} else if err != nil {
return nil, types.NewRPCError(types.DefaultErrorCode, fmt.Sprintf("failed to get block by number %v", blockNum))
}
return block, nil
}
// GetLatestGlobalExitRoot returns the last global exit root used by l2
func (z *ZKEVMEndpoints) GetLatestGlobalExitRoot() (interface{}, types.Error) {
return z.txMan.NewDbTxScope(z.state, func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) {
var err error
ger, err := z.state.GetLatestBatchGlobalExitRoot(ctx, dbTx)
if err != nil {
return RPCErrorResponse(types.DefaultErrorCode, "couldn't load the last global exit root", err, true)
}
return ger.String(), nil
})
}