forked from ethereumjs/ethereumjs-monorepo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheth.ts
1483 lines (1335 loc) · 51.4 KB
/
eth.ts
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
import { createBlock } from '@ethereumjs/block'
import { Hardfork } from '@ethereumjs/common'
import {
MerkleStateManager,
StatelessVerkleStateManager,
getMerkleStateProof,
getVerkleStateProof,
} from '@ethereumjs/statemanager'
import {
Capability,
createBlob4844TxFromSerializedNetworkWrapper,
createTx,
createTxFromRLP,
} from '@ethereumjs/tx'
import {
BIGINT_0,
BIGINT_1,
BIGINT_100,
BIGINT_NEG1,
TypeOutput,
bigIntMax,
bigIntToHex,
bytesToHex,
createAddressFromString,
createZeroAddress,
equalsBytes,
hexToBytes,
intToHex,
isHexString,
setLengthLeft,
toType,
} from '@ethereumjs/util'
import {
type EIP4844BlobTxReceipt,
type PostByzantiumTxReceipt,
type PreByzantiumTxReceipt,
type TxReceipt,
type VM,
runBlock,
runTx,
} from '@ethereumjs/vm'
import { INTERNAL_ERROR, INVALID_HEX_STRING, INVALID_PARAMS, PARSE_ERROR } from '../error-code.js'
import { callWithStackTrace, getBlockByOption, toJSONRPCTx } from '../helpers.js'
import { middleware, validators } from '../validation.js'
import type { Chain } from '../../blockchain/index.js'
import type { ReceiptsManager } from '../../execution/receipt.js'
import type { EthereumClient } from '../../index.js'
import type { EthProtocol } from '../../net/protocol/index.js'
import type { FullEthereumService, Service } from '../../service/index.js'
import type { RPCTx } from '../types.js'
import type { Block, JSONRPCBlock } from '@ethereumjs/block'
import type { Log } from '@ethereumjs/evm'
import type { Proof } from '@ethereumjs/statemanager'
import type { FeeMarket1559Tx, LegacyTx, TypedTransaction } from '@ethereumjs/tx'
import type { Address, PrefixedHexString } from '@ethereumjs/util'
const EMPTY_SLOT = `0x${'00'.repeat(32)}`
type GetLogsParams = {
fromBlock?: string // QUANTITY, block number or "earliest" or "latest" (default: "latest")
toBlock?: string // QUANTITY, block number or "latest" (default: "latest")
address?: PrefixedHexString // DATA, 20 Bytes, contract address from which logs should originate
topics?: PrefixedHexString[] // DATA, array, topics are order-dependent
blockHash?: PrefixedHexString // DATA, 32 Bytes. With the addition of EIP-234,
// blockHash restricts the logs returned to the single block with
// the 32-byte hash blockHash. Using blockHash is equivalent to
// fromBlock = toBlock = the block number with hash blockHash.
// If blockHash is present in in the filter criteria, then
// neither fromBlock nor toBlock are allowed.
}
type JSONRPCReceipt = {
transactionHash: string // DATA, 32 Bytes - hash of the transaction.
transactionIndex: string // QUANTITY - integer of the transactions index position in the block.
blockHash: string // DATA, 32 Bytes - hash of the block where this transaction was in.
blockNumber: string // QUANTITY - block number where this transaction was in.
from: string // DATA, 20 Bytes - address of the sender.
to: string | null // DATA, 20 Bytes - address of the receiver. null when it's a contract creation transaction.
cumulativeGasUsed: string // QUANTITY - The total amount of gas used when this transaction was executed in the block.
effectiveGasPrice: string // QUANTITY - The final gas price per gas paid by the sender in wei.
gasUsed: string // QUANTITY - The amount of gas used by this specific transaction alone.
contractAddress: string | null // DATA, 20 Bytes - The contract address created, if the transaction was a contract creation, otherwise null.
logs: JSONRPCLog[] // Array - Array of log objects, which this transaction generated.
logsBloom: string // DATA, 256 Bytes - Bloom filter for light clients to quickly retrieve related logs.
// It also returns either:
root?: string // DATA, 32 bytes of post-transaction stateroot (pre Byzantium)
status?: string // QUANTITY, either 1 (success) or 0 (failure)
blobGasUsed?: string // QUANTITY, blob gas consumed by transaction (if blob transaction)
blobGasPrice?: string // QUAntity, blob gas price for block including this transaction (if blob transaction)
type: string // QUANTITY, transaction type
}
type JSONRPCLog = {
removed: boolean // TAG - true when the log was removed, due to a chain reorganization. false if it's a valid log.
logIndex: string | null // QUANTITY - integer of the log index position in the block. null when it's pending.
transactionIndex: string | null // QUANTITY - integer of the transactions index position log was created from. null when it's pending.
transactionHash: string | null // DATA, 32 Bytes - hash of the transactions this log was created from. null when it's pending.
blockHash: string | null // DATA, 32 Bytes - hash of the block where this log was in. null when it's pending.
blockNumber: string | null // QUANTITY - the block number where this log was in. null when it's pending.
address: string // DATA, 20 Bytes - address from which this log originated.
data: string // DATA - contains one or more 32 Bytes non-indexed arguments of the log.
topics: string[] // Array of DATA - Array of 0 to 4 32 Bytes DATA of indexed log arguments.
// (In solidity: The first topic is the hash of the signature of the event
// (e.g. Deposit(address,bytes32,uint256)), except you declared the event with the anonymous specifier.)
}
/**
* Returns block formatted to the standard JSON-RPC fields
*/
const toJSONRPCBlock = async (
block: Block,
chain: Chain,
includeTransactions: boolean,
): Promise<JSONRPCBlock> => {
const json = block.toJSON()
const header = json!.header!
const transactions = block.transactions.map((tx, txIndex) =>
includeTransactions ? toJSONRPCTx(tx, block, txIndex) : bytesToHex(tx.hash()),
)
const withdrawalsAttr =
header.withdrawalsRoot !== undefined
? {
withdrawalsRoot: header.withdrawalsRoot!,
withdrawals: json.withdrawals,
}
: {}
const td = await chain.getTd(block.hash(), block.header.number)
return {
number: header.number!,
hash: bytesToHex(block.hash()),
parentHash: header.parentHash!,
mixHash: header.mixHash,
nonce: header.nonce!,
sha3Uncles: header.uncleHash!,
logsBloom: header.logsBloom!,
transactionsRoot: header.transactionsTrie!,
stateRoot: header.stateRoot!,
receiptsRoot: header.receiptTrie!,
miner: header.coinbase!,
difficulty: header.difficulty!,
totalDifficulty: bigIntToHex(td),
extraData: header.extraData!,
size: intToHex(block.serialize().length),
gasLimit: header.gasLimit!,
gasUsed: header.gasUsed!,
timestamp: header.timestamp!,
transactions,
uncles: block.uncleHeaders.map((uh) => bytesToHex(uh.hash())),
baseFeePerGas: header.baseFeePerGas,
...withdrawalsAttr,
blobGasUsed: header.blobGasUsed,
excessBlobGas: header.excessBlobGas,
parentBeaconBlockRoot: header.parentBeaconBlockRoot,
requestsRoot: header.requestsRoot,
requests: block.requests?.map((req) => bytesToHex(req.serialize())),
}
}
/**
* Returns log formatted to the standard JSON-RPC fields
*/
const toJSONRPCLog = async (
log: Log,
block?: Block,
tx?: TypedTransaction,
txIndex?: number,
logIndex?: number,
): Promise<JSONRPCLog> => ({
removed: false, // TODO implement
logIndex: logIndex !== undefined ? intToHex(logIndex) : null,
transactionIndex: txIndex !== undefined ? intToHex(txIndex) : null,
transactionHash: tx !== undefined ? bytesToHex(tx.hash()) : null,
blockHash: block ? bytesToHex(block.hash()) : null,
blockNumber: block ? bigIntToHex(block.header.number) : null,
address: bytesToHex(log[0]),
topics: log[1].map(bytesToHex),
data: bytesToHex(log[2]),
})
/**
* Returns receipt formatted to the standard JSON-RPC fields
*/
const toJSONRPCReceipt = async (
receipt: TxReceipt,
gasUsed: bigint,
effectiveGasPrice: bigint,
block: Block,
tx: TypedTransaction,
txIndex: number,
logIndex: number,
contractAddress?: Address,
blobGasUsed?: bigint,
blobGasPrice?: bigint,
): Promise<JSONRPCReceipt> => ({
transactionHash: bytesToHex(tx.hash()),
transactionIndex: intToHex(txIndex),
blockHash: bytesToHex(block.hash()),
blockNumber: bigIntToHex(block.header.number),
from: tx.getSenderAddress().toString(),
to: tx.to?.toString() ?? null,
cumulativeGasUsed: bigIntToHex(receipt.cumulativeBlockGasUsed),
effectiveGasPrice: bigIntToHex(effectiveGasPrice),
gasUsed: bigIntToHex(gasUsed),
contractAddress: contractAddress?.toString() ?? null,
logs: await Promise.all(
receipt.logs.map((l, i) => toJSONRPCLog(l, block, tx, txIndex, logIndex + i)),
),
logsBloom: bytesToHex(receipt.bitvector),
root:
(receipt as PreByzantiumTxReceipt).stateRoot instanceof Uint8Array
? bytesToHex((receipt as PreByzantiumTxReceipt).stateRoot)
: undefined,
status:
(receipt as PostByzantiumTxReceipt).status !== undefined
? intToHex((receipt as PostByzantiumTxReceipt).status)
: undefined,
blobGasUsed: blobGasUsed !== undefined ? bigIntToHex(blobGasUsed) : undefined,
blobGasPrice: blobGasPrice !== undefined ? bigIntToHex(blobGasPrice) : undefined,
type: intToHex(tx.type),
})
const calculateRewards = async (
block: Block,
receiptsManager: ReceiptsManager,
priorityFeePercentiles: number[],
) => {
if (priorityFeePercentiles.length === 0) {
return []
}
if (block.transactions.length === 0) {
return Array.from({ length: priorityFeePercentiles.length }, () => BIGINT_0)
}
const blockRewards: bigint[] = []
const txGasUsed: bigint[] = []
const baseFee = block.header.baseFeePerGas
const receipts = await receiptsManager.getReceipts(block.hash())
if (receipts.length > 0) {
txGasUsed.push(receipts[0].cumulativeBlockGasUsed)
for (let i = 1; i < receipts.length; i++) {
txGasUsed.push(receipts[i].cumulativeBlockGasUsed - receipts[i - 1].cumulativeBlockGasUsed)
}
}
const txs = block.transactions
const txsWithGasUsed = txs.map((tx, i) => ({
txGasUsed: txGasUsed[i],
// Can assume baseFee exists, since if EIP1559/EIP4844 txs are included, this is a post-EIP-1559 block.
effectivePriorityFee: tx.getEffectivePriorityFee(baseFee!),
}))
// Sort array based upon the effectivePriorityFee
txsWithGasUsed.sort((a, b) => Number(a.effectivePriorityFee - b.effectivePriorityFee))
let priorityFeeIndex = 0
// Loop over all txs ...
let targetCumulativeGasUsed =
(block.header.gasUsed * BigInt(priorityFeePercentiles[0])) / BIGINT_100
let cumulativeGasUsed = BIGINT_0
for (let txIndex = 0; txIndex < txsWithGasUsed.length; txIndex++) {
cumulativeGasUsed += txsWithGasUsed[txIndex].txGasUsed
while (
cumulativeGasUsed >= targetCumulativeGasUsed &&
priorityFeeIndex < priorityFeePercentiles.length
) {
/*
Idea: keep adding the premium fee to the priority fee percentile until we actually get above the threshold
For instance, take the priority fees [0,1,2,100]
The gas used in the block is 1.05 million
The first tx takes 1 million gas with prio fee A, the second the remainder over 0.05M with prio fee B
Then it is clear that the priority fees should be [A,A,A,B]
-> So A should be added three times
Note: in this case A < B so the priority fees were "sorted" by default
*/
blockRewards.push(txsWithGasUsed[txIndex].effectivePriorityFee)
priorityFeeIndex++
if (priorityFeeIndex >= priorityFeePercentiles.length) {
// prevent out-of-bounds read
break
}
const priorityFeePercentile = priorityFeePercentiles[priorityFeeIndex]
targetCumulativeGasUsed = (block.header.gasUsed * BigInt(priorityFeePercentile)) / BIGINT_100
}
}
return blockRewards
}
/**
* eth_* RPC module
* @memberof module:rpc/modules
*/
export class Eth {
private client: EthereumClient
private service: Service
private receiptsManager: ReceiptsManager | undefined
private _chain: Chain
private _vm: VM | undefined
private _rpcDebug: boolean
public ethVersion: number
/**
* Create eth_* RPC module
* @param client Client to which the module binds
*/
constructor(client: EthereumClient, rpcDebug: boolean) {
this.client = client
this.service = client.service
this._chain = this.service.chain
this._vm = (this.service as FullEthereumService).execution?.vm
this.receiptsManager = (this.service as FullEthereumService).execution?.receiptsManager
this._rpcDebug = rpcDebug
const ethProtocol = this.service.protocols.find((p) => p.name === 'eth') as EthProtocol
this.ethVersion = Math.max(...ethProtocol.versions)
this.blockNumber = middleware(
callWithStackTrace(this.blockNumber.bind(this), this._rpcDebug),
0,
)
this.call = middleware(callWithStackTrace(this.call.bind(this), this._rpcDebug), 2, [
[validators.transaction()],
[validators.blockOption],
])
this.chainId = middleware(callWithStackTrace(this.chainId.bind(this), this._rpcDebug), 0, [])
this.estimateGas = middleware(
callWithStackTrace(this.estimateGas.bind(this), this._rpcDebug),
1,
[[validators.transaction()], [validators.blockOption]],
)
this.getBalance = middleware(
callWithStackTrace(this.getBalance.bind(this), this._rpcDebug),
2,
[[validators.address], [validators.blockOption]],
)
this.coinbase = middleware(callWithStackTrace(this.coinbase.bind(this), this._rpcDebug), 0, [])
this.getBlockByNumber = middleware(
callWithStackTrace(this.getBlockByNumber.bind(this), this._rpcDebug),
2,
[[validators.blockOption], [validators.bool]],
)
this.getBlockByHash = middleware(
callWithStackTrace(this.getBlockByHash.bind(this), this._rpcDebug),
2,
[[validators.hex, validators.blockHash], [validators.bool]],
)
this.getBlockTransactionCountByHash = middleware(
callWithStackTrace(this.getBlockTransactionCountByHash.bind(this), this._rpcDebug),
1,
[[validators.hex, validators.blockHash]],
)
this.getCode = middleware(callWithStackTrace(this.getCode.bind(this), this._rpcDebug), 2, [
[validators.address],
[validators.blockOption],
])
this.getUncleCountByBlockNumber = middleware(
callWithStackTrace(this.getUncleCountByBlockNumber.bind(this), this._rpcDebug),
1,
[[validators.hex]],
)
this.getStorageAt = middleware(
callWithStackTrace(this.getStorageAt.bind(this), this._rpcDebug),
3,
[[validators.address], [validators.hex], [validators.blockOption]],
)
this.getTransactionByBlockHashAndIndex = middleware(
callWithStackTrace(this.getTransactionByBlockHashAndIndex.bind(this), this._rpcDebug),
2,
[[validators.hex, validators.blockHash], [validators.hex]],
)
this.getTransactionByBlockNumberAndIndex = middleware(
callWithStackTrace(this.getTransactionByBlockNumberAndIndex.bind(this), this._rpcDebug),
2,
[[validators.hex, validators.blockOption], [validators.hex]],
)
this.getTransactionByHash = middleware(
callWithStackTrace(this.getTransactionByHash.bind(this), this._rpcDebug),
1,
[[validators.hex]],
)
this.getTransactionCount = middleware(
callWithStackTrace(this.getTransactionCount.bind(this), this._rpcDebug),
2,
[[validators.address], [validators.blockOption]],
)
this.getBlockReceipts = middleware(
callWithStackTrace(this.getBlockReceipts.bind(this), this._rpcDebug),
1,
[[validators.blockOption]],
)
this.getTransactionReceipt = middleware(
callWithStackTrace(this.getTransactionReceipt.bind(this), this._rpcDebug),
1,
[[validators.hex]],
)
this.getUncleCountByBlockNumber = middleware(
callWithStackTrace(this.getUncleCountByBlockNumber.bind(this), this._rpcDebug),
1,
[[validators.hex]],
)
this.getLogs = middleware(callWithStackTrace(this.getLogs.bind(this), this._rpcDebug), 1, [
[
validators.object({
fromBlock: validators.optional(validators.blockOption),
toBlock: validators.optional(validators.blockOption),
address: validators.optional(
validators.either(validators.array(validators.address), validators.address),
),
topics: validators.optional(
validators.array(
validators.optional(
validators.either(validators.hex, validators.array(validators.hex)),
),
),
),
blockHash: validators.optional(validators.blockHash),
}),
],
])
this.sendRawTransaction = middleware(
callWithStackTrace(this.sendRawTransaction.bind(this), this._rpcDebug),
1,
[[validators.hex]],
)
this.protocolVersion = middleware(
callWithStackTrace(this.protocolVersion.bind(this), this._rpcDebug),
0,
[],
)
this.syncing = middleware(callWithStackTrace(this.syncing.bind(this), this._rpcDebug), 0, [])
this.getProof = middleware(callWithStackTrace(this.getProof.bind(this), this._rpcDebug), 3, [
[validators.address],
[validators.array(validators.hex)],
[validators.blockOption],
])
this.getBlockTransactionCountByNumber = middleware(
callWithStackTrace(this.getBlockTransactionCountByNumber.bind(this), this._rpcDebug),
1,
[[validators.blockOption]],
)
this.gasPrice = middleware(callWithStackTrace(this.gasPrice.bind(this), this._rpcDebug), 0, [])
this.feeHistory = middleware(
callWithStackTrace(this.feeHistory.bind(this), this._rpcDebug),
2,
[
[validators.either(validators.hex, validators.integer)],
[validators.either(validators.hex, validators.blockOption)],
[validators.rewardPercentiles],
],
)
this.blobBaseFee = middleware(
callWithStackTrace(this.blobBaseFee.bind(this), this._rpcDebug),
0,
[],
)
}
/**
* Returns number of the most recent block.
* @param params An empty array
*/
async blockNumber(_params = []) {
return bigIntToHex(this._chain.headers.latest?.number ?? BIGINT_0)
}
/**
* Executes a new message call immediately without creating a transaction on the block chain.
* @param params An array of two parameters:
* 1. The transaction object
* * from (optional) - The address the transaction is sent from
* * to - The address the transaction is directed to
* * gas (optional) - Integer of the gas provided for the transaction execution
* * gasPrice (optional) - Integer of the gasPrice used for each paid gas
* * value (optional) - Integer of the value sent with this transaction
* * data (optional) - Hash of the method signature and encoded parameters.
* 2. integer block number, or the string "latest", "earliest" or "pending"
* @returns The return value of the executed contract.
*/
async call(params: [RPCTx, string]) {
const [transaction, blockOpt] = params
const block = await getBlockByOption(blockOpt, this._chain)
if (this._vm === undefined) {
throw new Error('missing vm')
}
const vm = await this._vm.shallowCopy()
await vm.stateManager.setStateRoot(block.header.stateRoot)
const { from, to, gas: gasLimit, gasPrice, value } = transaction
const data = transaction.data ?? transaction.input
const runCallOpts = {
caller: from !== undefined ? createAddressFromString(from) : undefined,
to: to !== undefined ? createAddressFromString(to) : undefined,
gasLimit: toType(gasLimit, TypeOutput.BigInt),
gasPrice: toType(gasPrice, TypeOutput.BigInt),
value: toType(value, TypeOutput.BigInt),
data: data !== undefined ? hexToBytes(data) : undefined,
block,
}
const { execResult } = await vm.evm.runCall(runCallOpts)
if (execResult.exceptionError !== undefined) {
throw {
code: 3,
data: bytesToHex(execResult.returnValue),
message: execResult.exceptionError.error,
}
}
return bytesToHex(execResult.returnValue)
}
/**
* Returns the currently configured chain id, a value used in replay-protected transaction signing as introduced by EIP-155.
* @param _params An empty array
* @returns The chain ID.
*/
async chainId(_params = []) {
const chainId = this._chain.config.chainCommon.chainId()
return bigIntToHex(chainId)
}
/**
* Generates and returns an estimate of how much gas is necessary to allow the transaction to complete.
* The transaction will not be added to the blockchain.
* Note that the estimate may be significantly more than the amount of gas actually used by the transaction,
* for a variety of reasons including EVM mechanics and node performance.
* @param params An array of two parameters:
* 1. The transaction object
* * from (optional) - The address the transaction is sent from
* * to - The address the transaction is directed to
* * gas (optional) - Integer of the gas provided for the transaction execution
* * gasPrice (optional) - Integer of the gasPrice used for each paid gas
* * value (optional) - Integer of the value sent with this transaction
* * data (optional) - Hash of the method signature and encoded parameters.
* 2. integer block number, or the string "latest", "earliest" or "pending" (optional)
* @returns The amount of gas used.
*/
async estimateGas(params: [RPCTx, string?]) {
const [transaction, blockOpt] = params
const block = await getBlockByOption(blockOpt ?? 'latest', this._chain)
if (this._vm === undefined) {
throw new Error('missing vm')
}
const vm = await this._vm.shallowCopy()
await vm.stateManager.setStateRoot(block.header.stateRoot)
if (transaction.gas === undefined) {
// If no gas limit is specified use the last block gas limit as an upper bound.
const latest = await this._chain.getCanonicalHeadHeader()
transaction.gas = latest.gasLimit as any
}
if (transaction.gasPrice === undefined && transaction.maxFeePerGas === undefined) {
// If no gas price or maxFeePerGas provided, set maxFeePerGas to the next base fee
if (transaction.type !== undefined && parseInt(transaction.type) === 2) {
transaction.maxFeePerGas = `0x${block.header.calcNextBaseFee()?.toString(16)}`
} else if (block.header.baseFeePerGas !== undefined) {
transaction.gasPrice = `0x${block.header.calcNextBaseFee()?.toString(16)}`
}
}
const txData = {
...transaction,
gasLimit: transaction.gas,
}
const blockToRunOn = createBlock(
{
header: {
parentHash: block.hash(),
number: block.header.number + BIGINT_1,
timestamp: block.header.timestamp + BIGINT_1,
baseFeePerGas: block.common.isActivatedEIP(1559)
? block.header.calcNextBaseFee()
: undefined,
},
},
{ common: vm.common, setHardfork: true },
)
vm.common.setHardforkBy({
timestamp: blockToRunOn.header.timestamp,
blockNumber: blockToRunOn.header.number,
})
const tx = createTx(txData, { common: vm.common, freeze: false })
// set from address
const from =
transaction.from !== undefined
? createAddressFromString(transaction.from)
: createZeroAddress()
tx.getSenderAddress = () => {
return from
}
const { totalGasSpent } = await runTx(vm, {
tx,
skipNonce: true,
skipBalance: true,
skipBlockGasLimitValidation: true,
block: blockToRunOn,
})
return `0x${totalGasSpent.toString(16)}`
}
/**
* Returns the balance of the account at the given address.
* @param params An array of two parameters:
* 1. address of the account
* 2. integer block number, or the string "latest", "earliest" or "pending"
*/
async getBalance(params: [string, string]) {
const [addressHex, blockOpt] = params
const address = createAddressFromString(addressHex)
const block = await getBlockByOption(blockOpt, this._chain)
if (this._vm === undefined) {
throw new Error('missing vm')
}
const vm = await this._vm.shallowCopy()
await vm.stateManager.setStateRoot(block.header.stateRoot)
const account = await vm.stateManager.getAccount(address)
if (account === undefined) {
return '0x0'
}
return bigIntToHex(account.balance)
}
/**
* Returns the currently configured coinbase address.
* @param _params An empty array
* @returns The chain ID.
*/
async coinbase(_params = []) {
const cb = this.client.config.minerCoinbase
if (cb === undefined) {
throw {
code: INTERNAL_ERROR,
message: 'Coinbase must be explicitly specified',
}
}
return cb.toString()
}
/**
* Returns information about a block by hash.
* @param params An array of two parameters:
* 1. a block hash
* 2. boolean - if true returns the full transaction objects, if false only the hashes of the transactions.
*/
async getBlockByHash(params: [PrefixedHexString, boolean]) {
const [blockHash, includeTransactions] = params
try {
const block = await this._chain.getBlock(hexToBytes(blockHash))
return await toJSONRPCBlock(block, this._chain, includeTransactions)
} catch (error) {
return null
}
}
/**
* Returns information about a block by block number.
* @param params An array of two parameters:
* 1. integer of a block number, or the string "latest", "earliest" or "pending"
* 2. boolean - if true returns the full transaction objects, if false only the hashes of the transactions.
*/
async getBlockByNumber(params: [string, boolean]) {
const [blockOpt, includeTransactions] = params
if (blockOpt === 'pending') {
throw {
code: INVALID_PARAMS,
message: `"pending" is not yet supported`,
}
}
try {
const block = await getBlockByOption(blockOpt, this._chain)
const response = await toJSONRPCBlock(block, this._chain, includeTransactions)
return response
} catch {
return null
}
}
/**
* Returns the transaction count for a block given by the block hash.
* @param params An array of one parameter: A block hash
*/
async getBlockTransactionCountByHash(params: [PrefixedHexString]) {
const [blockHash] = params
try {
const block = await this._chain.getBlock(hexToBytes(blockHash))
return intToHex(block.transactions.length)
} catch (error) {
throw {
code: INVALID_PARAMS,
message: 'Unknown block',
}
}
}
/**
* Returns code of the account at the given address.
* @param params An array of two parameters:
* 1. address of the account
* 2. integer block number, or the string "latest", "earliest" or "pending"
*/
async getCode(params: [string, string]) {
const [addressHex, blockOpt] = params
const block = await getBlockByOption(blockOpt, this._chain)
if (this._vm === undefined) {
throw new Error('missing vm')
}
const vm = await this._vm.shallowCopy()
await vm.stateManager.setStateRoot(block.header.stateRoot)
const address = createAddressFromString(addressHex)
const code = await vm.stateManager.getCode(address)
return bytesToHex(code)
}
/**
* Returns the value from a storage position at a given address.
* @param params An array of three parameters:
* 1. address of the storage
* 2. integer of the position in the storage
* 3. integer block number, or the string "latest", "earliest" or "pending"
*/
async getStorageAt(params: [string, PrefixedHexString, string]) {
const [addressHex, keyHex, blockOpt] = params
if (!/^[0-9a-fA-F]+$/.test(keyHex.slice(2))) {
throw {
code: INVALID_HEX_STRING,
message: `unable to decode storage key: hex string invalid`,
}
}
if (keyHex.length > 66) {
throw {
code: INVALID_HEX_STRING,
message: `unable to decode storage key: hex string too long, want at most 32 bytes`,
}
}
if (blockOpt === 'pending') {
throw {
code: INVALID_PARAMS,
message: '"pending" is not yet supported',
}
}
if (this._vm === undefined) {
throw new Error('missing vm')
}
const vm = await this._vm.shallowCopy()
// TODO: this needs more thought, keep on latest for now
const block = await getBlockByOption(blockOpt, this._chain)
await vm.stateManager.setStateRoot(block.header.stateRoot)
const address = createAddressFromString(addressHex)
const account = await vm.stateManager.getAccount(address)
if (account === undefined) {
return EMPTY_SLOT
}
const key = setLengthLeft(hexToBytes(keyHex), 32)
const storage = await vm.stateManager.getStorage(address, key)
return storage !== null && storage !== undefined
? bytesToHex(setLengthLeft(Uint8Array.from(storage) as Uint8Array, 32))
: EMPTY_SLOT
}
/**
* Returns information about a transaction given a block hash and a transaction's index position.
* @param params An array of two parameter:
* 1. a block hash
* 2. an integer of the transaction index position encoded as a hexadecimal.
*/
async getTransactionByBlockHashAndIndex(params: [PrefixedHexString, string]) {
try {
const [blockHash, txIndexHex] = params
const txIndex = parseInt(txIndexHex, 16)
const block = await this._chain.getBlock(hexToBytes(blockHash))
if (block.transactions.length <= txIndex) {
return null
}
const tx = block.transactions[txIndex]
return toJSONRPCTx(tx, block, txIndex)
} catch (error: any) {
throw {
code: INVALID_PARAMS,
message: error.message.toString(),
}
}
}
/**
* Returns information about a transaction given a block hash and a transaction's index position.
* @param params An array of two parameter:
* 1. a block number
* 2. an integer of the transaction index position encoded as a hexadecimal.
*/
async getTransactionByBlockNumberAndIndex(params: [PrefixedHexString, string]) {
try {
const [blockNumber, txIndexHex] = params
const txIndex = parseInt(txIndexHex, 16)
const block = await getBlockByOption(blockNumber, this._chain)
if (block.transactions.length <= txIndex) {
return null
}
const tx = block.transactions[txIndex]
return toJSONRPCTx(tx, block, txIndex)
} catch (error: any) {
throw {
code: INVALID_PARAMS,
message: error.message.toString(),
}
}
}
/**
* Returns the transaction by hash when available within `--txLookupLimit`
* @param params An array of one parameter:
* 1. hash of the transaction
*/
async getTransactionByHash(params: [PrefixedHexString]) {
const [txHash] = params
if (!this.receiptsManager) throw new Error('missing receiptsManager')
const result = await this.receiptsManager.getReceiptByTxHash(hexToBytes(txHash))
if (!result) return null
const [_receipt, blockHash, txIndex] = result
const block = await this._chain.getBlock(blockHash)
const tx = block.transactions[txIndex]
return toJSONRPCTx(tx, block, txIndex)
}
/**
* Returns the number of transactions sent from an address.
* @param params An array of two parameters:
* 1. address of the account
* 2. integer block number, or the string "latest", "earliest" or "pending"
*/
async getTransactionCount(params: [string, string]) {
const [addressHex, blockOpt] = params
let block
if (blockOpt !== 'pending') block = await getBlockByOption(blockOpt, this._chain)
else block = await getBlockByOption('latest', this._chain)
if (this._vm === undefined) {
throw new Error('missing vm')
}
const vm = await this._vm.shallowCopy()
await vm.stateManager.setStateRoot(block.header.stateRoot)
const address = createAddressFromString(addressHex)
const account = await vm.stateManager.getAccount(address)
if (account === undefined) {
return '0x0'
}
let pendingTxsCount = BIGINT_0
// Add pending txns to nonce if blockOpt is 'pending'
if (blockOpt === 'pending') {
pendingTxsCount = BigInt(
(this.service as FullEthereumService).txPool.pool.get(addressHex.slice(2))?.length ?? 0,
)
}
return bigIntToHex(account.nonce + pendingTxsCount)
}
/**
* Returns the current ethereum protocol version as a hex-encoded string
* @param params An empty array
*/
protocolVersion(_params = []) {
return intToHex(this.ethVersion)
}
/**
* Returns the number of uncles in a block from a block matching the given block number
* @param params An array of one parameter:
* 1: hexadecimal representation of a block number
*/
async getUncleCountByBlockNumber(params: [string]) {
const [blockNumberHex] = params
const blockNumber = BigInt(blockNumberHex)
const latest =
this._chain.headers.latest?.number ?? (await this._chain.getCanonicalHeadHeader()).number
if (blockNumber > latest) {
throw {
code: INVALID_PARAMS,
message: 'specified block greater than current height',
}
}
const block = await this._chain.getBlock(blockNumber)
return block.uncleHeaders.length
}
async getBlockReceipts(params: [string]) {
const [blockOpt] = params
let block: Block
try {
if (isHexString(blockOpt, 64)) {
block = await this._chain.getBlock(hexToBytes(blockOpt))
} else {
block = await getBlockByOption(blockOpt, this._chain)
}
} catch {
return null
}
const blockHash = block.hash()
if (!this.receiptsManager) throw new Error('missing receiptsManager')
const result = await this.receiptsManager.getReceipts(blockHash, true, true)
if (result.length === 0) return []
const parentBlock = await this._chain.getBlock(block.header.parentHash)
const vmCopy = await this._vm!.shallowCopy()
vmCopy.common.setHardfork(block.common.hardfork())
// Run tx through copied vm to get tx gasUsed and createdAddress
const runBlockResult = await runBlock(vmCopy, {
block,
root: parentBlock.header.stateRoot,
skipBlockValidation: true,
})
const receipts = await Promise.all(
result.map(async (r, i) => {
const tx = block.transactions[i]
const { totalGasSpent, createdAddress } = runBlockResult.results[i]
const { blobGasPrice, blobGasUsed } = runBlockResult.receipts[i] as EIP4844BlobTxReceipt
const effectiveGasPrice =
tx.supports(Capability.EIP1559FeeMarket) === true
? (tx as FeeMarket1559Tx).maxPriorityFeePerGas <
(tx as FeeMarket1559Tx).maxFeePerGas - block.header.baseFeePerGas!
? (tx as FeeMarket1559Tx).maxPriorityFeePerGas
: (tx as FeeMarket1559Tx).maxFeePerGas -
block.header.baseFeePerGas! +
block.header.baseFeePerGas!
: (tx as LegacyTx).gasPrice
return toJSONRPCReceipt(
r,
totalGasSpent,
effectiveGasPrice,
block,
tx,
i,
i,
createdAddress,
blobGasUsed,
blobGasPrice,
)
}),
)
return receipts
}
/**
* Returns the receipt of a transaction by transaction hash.
* *Note* That the receipt is not available for pending transactions.
* Only available with `--saveReceipts` enabled
* Will return empty if tx is past set `--txLookupLimit`
* (default = 2350000 = about one year, 0 = entire chain)