webevm 0.9.1 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +94 -12
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/intrinsic-gas.d.ts +70 -14
- package/dist/intrinsic-gas.d.ts.map +1 -1
- package/dist/intrinsic-gas.js +65 -0
- package/dist/intrinsic-gas.js.map +1 -1
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +686 -41
- package/dist/node.js.map +1 -1
- package/dist/revm.d.ts +18 -17
- package/dist/revm.d.ts.map +1 -1
- package/dist/revm.js +80 -40
- package/dist/revm.js.map +1 -1
- package/dist/state-manager.d.ts +19 -0
- package/dist/state-manager.d.ts.map +1 -1
- package/dist/state-manager.js +32 -0
- package/dist/state-manager.js.map +1 -1
- package/dist/types.d.ts +39 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/worker-host.d.ts +30 -0
- package/dist/worker-host.d.ts.map +1 -1
- package/dist/worker-host.js +42 -5
- package/dist/worker-host.js.map +1 -1
- package/package.json +2 -2
- package/src/index.ts +1 -0
- package/src/intrinsic-gas.ts +92 -14
- package/src/node.ts +864 -44
- package/src/revm.ts +103 -47
- package/src/state-manager.ts +35 -0
- package/src/types.ts +40 -0
- package/src/worker-host.ts +79 -7
package/src/node.ts
CHANGED
|
@@ -65,6 +65,9 @@ import {
|
|
|
65
65
|
setLengthLeft,
|
|
66
66
|
bigIntToBytes,
|
|
67
67
|
unpadBytes,
|
|
68
|
+
concatBytes,
|
|
69
|
+
equalsBytes,
|
|
70
|
+
eoaCode7702RecoverAuthority,
|
|
68
71
|
} from '@ethereumjs/util';
|
|
69
72
|
|
|
70
73
|
// `@ethereumjs/util`'s hexToBytes is typed to require a `0x${string}` literal.
|
|
@@ -90,10 +93,15 @@ import {serveProvider, type ServedProvider} from '@eip-1193/over-port';
|
|
|
90
93
|
// so it has exactly one home. See ./intrinsic-gas.ts.
|
|
91
94
|
import {
|
|
92
95
|
accessListGas,
|
|
96
|
+
authorizationListGas,
|
|
97
|
+
calldataFloorGas,
|
|
93
98
|
intrinsicGas as intrinsicGasOf,
|
|
99
|
+
transactionGasLimitCap,
|
|
94
100
|
} from './intrinsic-gas.js';
|
|
101
|
+
import {RLP} from '@ethereumjs/rlp';
|
|
95
102
|
import {
|
|
96
103
|
RpcError,
|
|
104
|
+
type NodeHardfork,
|
|
97
105
|
type NodeOptions,
|
|
98
106
|
type ReadCallResult,
|
|
99
107
|
type Engine,
|
|
@@ -110,6 +118,11 @@ import {
|
|
|
110
118
|
|
|
111
119
|
const ZERO_HASH = '0x' + '00'.repeat(32);
|
|
112
120
|
const ZERO_ADDRESS = '0x' + '00'.repeat(20);
|
|
121
|
+
/** EIP-7702: the code an authority holds once delegated is this, then 20 bytes. */
|
|
122
|
+
const DELEGATION_PREFIX = Uint8Array.of(0xef, 0x01, 0x00);
|
|
123
|
+
/** secp256k1's group order over two: EIP-2's bound on a signature's `s`. */
|
|
124
|
+
const SECP256K1_N_DIV_2 =
|
|
125
|
+
0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0n;
|
|
113
126
|
/**
|
|
114
127
|
* What a block's `logsBloom` reads as when it admits nothing: a block with no
|
|
115
128
|
* logs, and the defensive fallback for a stored header carrying none at all
|
|
@@ -292,6 +305,29 @@ function txHashOf(tx: TypedTransaction): string {
|
|
|
292
305
|
return hex(tx.hash());
|
|
293
306
|
}
|
|
294
307
|
|
|
308
|
+
/**
|
|
309
|
+
* The GAS LIMIT field of a raw transaction, read off its RLP without building
|
|
310
|
+
* the transaction, or `undefined` for bytes this cannot decode (the parser then
|
|
311
|
+
* produces the error it always has). Its position differs by envelope: a legacy
|
|
312
|
+
* transaction is `[nonce, gasPrice, gasLimit, ...]`, EIP-2930 (type 1) is
|
|
313
|
+
* `[chainId, nonce, gasPrice, gasLimit, ...]`, and every 1559-family envelope
|
|
314
|
+
* (types 2, 3 and 4) is `[chainId, nonce, maxPriorityFee, maxFee, gasLimit, ...]`.
|
|
315
|
+
*/
|
|
316
|
+
function wireGasLimit(raw: Uint8Array): bigint | undefined {
|
|
317
|
+
try {
|
|
318
|
+
if (raw.length === 0) return undefined;
|
|
319
|
+
const type = raw[0] >= 0xc0 ? 0 : raw[0];
|
|
320
|
+
if (type > 4) return undefined;
|
|
321
|
+
const fields = RLP.decode(type === 0 ? raw : raw.subarray(1));
|
|
322
|
+
if (!Array.isArray(fields)) return undefined;
|
|
323
|
+
const index = type === 0 ? 2 : type === 1 ? 3 : 4;
|
|
324
|
+
const field = fields[index];
|
|
325
|
+
return field instanceof Uint8Array ? bytesToBigInt(field) : undefined;
|
|
326
|
+
} catch {
|
|
327
|
+
return undefined;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
295
331
|
/**
|
|
296
332
|
* Intrinsic gas: 21000 base (+32000 create) + calldata (16/non-zero, 4/zero) +
|
|
297
333
|
* the EIP-3860 initcode word cost (2 gas per 32-byte word) for creates, from
|
|
@@ -519,6 +555,45 @@ function validateGenesisTimestamp(options: NodeOptions): bigint | undefined {
|
|
|
519
555
|
return value;
|
|
520
556
|
}
|
|
521
557
|
|
|
558
|
+
/**
|
|
559
|
+
* The `@ethereumjs/common` hardfork each {@link NodeHardfork} runs on. ALSO the
|
|
560
|
+
* list of what the option accepts: a fork is here because the node's own gas
|
|
561
|
+
* rules (`./intrinsic-gas.ts`, the read admission in `evmCall`, the estimate's
|
|
562
|
+
* bounds, the submit-time refusals) are implemented and tested for it on BOTH
|
|
563
|
+
* engines, not because `@ethereumjs/common` or revm has a name for it.
|
|
564
|
+
*/
|
|
565
|
+
const HARDFORK_OF: Readonly<Record<NodeHardfork, Hardfork>> = Object.freeze({
|
|
566
|
+
cancun: Hardfork.Cancun,
|
|
567
|
+
prague: Hardfork.Prague,
|
|
568
|
+
osaka: Hardfork.Osaka,
|
|
569
|
+
});
|
|
570
|
+
/** What a node runs when `hardfork` is absent: the latest fork it can cost. */
|
|
571
|
+
const DEFAULT_HARDFORK: NodeHardfork = 'osaka';
|
|
572
|
+
/** What a dump that predates `SerializedState.hardfork` was taken on. */
|
|
573
|
+
const HARDFORK_OF_AN_UNLABELLED_DUMP: NodeHardfork = 'cancun';
|
|
574
|
+
|
|
575
|
+
/**
|
|
576
|
+
* The node's hardfork, or a throw naming the option. A typo (`'Osaka'`,
|
|
577
|
+
* `'pectra'`) must not silently become the default: the fork decides what every
|
|
578
|
+
* transaction costs, and a node on a fork its caller did not ask for computes
|
|
579
|
+
* plausible numbers for the wrong chain.
|
|
580
|
+
*/
|
|
581
|
+
function validateHardfork(options: NodeOptions): NodeHardfork {
|
|
582
|
+
const value = options.hardfork as unknown;
|
|
583
|
+
if (value === undefined) return DEFAULT_HARDFORK;
|
|
584
|
+
if (typeof value === 'string' && Object.hasOwn(HARDFORK_OF, value))
|
|
585
|
+
return value as NodeHardfork;
|
|
586
|
+
throw new Error(
|
|
587
|
+
`webevm: hardfork must be one of ${Object.keys(HARDFORK_OF)
|
|
588
|
+
.map((h) => `'${h}'`)
|
|
589
|
+
.join(
|
|
590
|
+
', ',
|
|
591
|
+
)} (default '${DEFAULT_HARDFORK}'), got ${describeOption(value)}. ` +
|
|
592
|
+
`Those are the forks whose gas rules this node implements on every engine; ` +
|
|
593
|
+
`an earlier one is not offered, and a later one is not costed yet.`,
|
|
594
|
+
);
|
|
595
|
+
}
|
|
596
|
+
|
|
522
597
|
function describeOption(value: unknown): string {
|
|
523
598
|
try {
|
|
524
599
|
const s = JSON.stringify(value);
|
|
@@ -552,10 +627,11 @@ export async function createNodeWithInternals(
|
|
|
552
627
|
* root. Only `true` turns it on (see {@link NodeOptions.computeStateRoot}).
|
|
553
628
|
*/
|
|
554
629
|
const computeStateRoot = options.computeStateRoot === true;
|
|
630
|
+
const hardfork = validateHardfork(options);
|
|
555
631
|
|
|
556
632
|
const common = new Common({
|
|
557
633
|
chain: {...Mainnet, chainId, name: 'webevm'},
|
|
558
|
-
hardfork:
|
|
634
|
+
hardfork: HARDFORK_OF[hardfork],
|
|
559
635
|
customCrypto: {keccak256: (m: Uint8Array) => keccak_256(m)},
|
|
560
636
|
});
|
|
561
637
|
|
|
@@ -948,6 +1024,141 @@ export async function createNodeWithInternals(
|
|
|
948
1024
|
// cover, so the timer starts after the node is fully built instead.
|
|
949
1025
|
let intervalTimer: ReturnType<typeof setInterval> | undefined;
|
|
950
1026
|
|
|
1027
|
+
/**
|
|
1028
|
+
* THE NODE'S CLOCK: the timestamp a mined block is stamped with, and the time
|
|
1029
|
+
* cheats that move it. They are the methods (and the wire shapes) anvil,
|
|
1030
|
+
* hardhat and ganache already share, so viem's test actions drive them
|
|
1031
|
+
* unchanged: `evm_setNextBlockTimestamp`, `evm_increaseTime`, `evm_mine`,
|
|
1032
|
+
* `anvil_mine` (alias `hardhat_mine`, as anvil has it), and anvil's
|
|
1033
|
+
* `anvil_setBlockTimestampInterval` / `anvil_removeBlockTimestampInterval`,
|
|
1034
|
+
* which no other dev node defines and so keep anvil's names.
|
|
1035
|
+
*
|
|
1036
|
+
* WITH NO CHEAT ISSUED IT IS EXACTLY WHAT IT WAS: `blockEnv.timestamp` when
|
|
1037
|
+
* pinned, else the wall clock in whole seconds, with no reference to the parent.
|
|
1038
|
+
* Whether that default should become strictly increasing is a separate question
|
|
1039
|
+
* (work/notes/observations/2026-09-28-mined-block-timestamps-are-not-strictly-increasing.md)
|
|
1040
|
+
* which this does not decide. A block reads the cheats in this order:
|
|
1041
|
+
*
|
|
1042
|
+
* 1. a NEXT TIMESTAMP, set once and used by the next block mined; it must be
|
|
1043
|
+
* later than the head's (hardhat's rule, and post-Merge consensus; anvil
|
|
1044
|
+
* also admits an equal one), and once a block carries it the OFFSET moves
|
|
1045
|
+
* so that the clock carries on from there, as on anvil and hardhat;
|
|
1046
|
+
* 2. an INTERVAL: the parent's timestamp plus this many seconds (0 repeats
|
|
1047
|
+
* the parent's), the wall clock not consulted, so a chain's timestamps do
|
|
1048
|
+
* not depend on when or how fast it ran;
|
|
1049
|
+
* 3. the BASE (`blockEnv.timestamp`, else the wall clock) plus the OFFSET,
|
|
1050
|
+
* which `evm_increaseTime` adds to.
|
|
1051
|
+
*
|
|
1052
|
+
* NODE SETTINGS, NOT CHAIN STATE: none of it is in `dumpState`. `loadState`
|
|
1053
|
+
* clears a pending next timestamp (the loaded head may already be past it);
|
|
1054
|
+
* the offset and the interval belong to this node and survive it.
|
|
1055
|
+
*/
|
|
1056
|
+
let nextTimestamp: bigint | undefined;
|
|
1057
|
+
let timeOffset = 0n;
|
|
1058
|
+
let timestampInterval: bigint | undefined;
|
|
1059
|
+
const clockBase = () =>
|
|
1060
|
+
blockEnv?.timestamp ?? BigInt(Math.floor(Date.now() / 1000));
|
|
1061
|
+
const headTimestamp = () =>
|
|
1062
|
+
blockStore.get(latestNumber)?.block.header.timestamp ?? 0n;
|
|
1063
|
+
function plannedTimestamp(): bigint {
|
|
1064
|
+
if (nextTimestamp !== undefined) return nextTimestamp;
|
|
1065
|
+
if (timestampInterval !== undefined)
|
|
1066
|
+
return headTimestamp() + timestampInterval;
|
|
1067
|
+
return clockBase() + timeOffset;
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
/**
|
|
1071
|
+
* A time cheat's integer: a JSON number or a quantity string (hex `0x…` or
|
|
1072
|
+
* decimal), the shapes anvil accepts; at most a uint64, a header timestamp's
|
|
1073
|
+
* width, unless the caller names another (`bits`: 256 for a balance or a slot).
|
|
1074
|
+
* Anything else is `-32602`, naming the method, rather than a guess.
|
|
1075
|
+
*/
|
|
1076
|
+
function quantity(
|
|
1077
|
+
value: unknown,
|
|
1078
|
+
method: string,
|
|
1079
|
+
what = 'seconds',
|
|
1080
|
+
bits = 64n,
|
|
1081
|
+
): bigint {
|
|
1082
|
+
let s: bigint | undefined;
|
|
1083
|
+
if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0)
|
|
1084
|
+
s = BigInt(value);
|
|
1085
|
+
else if (
|
|
1086
|
+
typeof value === 'string' &&
|
|
1087
|
+
(/^0x[0-9a-fA-F]+$/.test(value) || /^[0-9]+$/.test(value))
|
|
1088
|
+
)
|
|
1089
|
+
s = BigInt(value);
|
|
1090
|
+
if (s === undefined || s >= 2n ** bits)
|
|
1091
|
+
throw new RpcError(
|
|
1092
|
+
-32602,
|
|
1093
|
+
`${method}: expected a non-negative integer number of ${what} below 2^${bits}, got ${JSON.stringify(value)}`,
|
|
1094
|
+
);
|
|
1095
|
+
return s;
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
/**
|
|
1099
|
+
* A `hardhat_*` / `anvil_*` state cheat's hex parameter: `0x` and whole bytes,
|
|
1100
|
+
* exactly `bytes` of them when given (20 for an address, 32 for a storage
|
|
1101
|
+
* value). Anything else is `-32602`, naming the method and what it expected.
|
|
1102
|
+
*/
|
|
1103
|
+
function cheatHex(
|
|
1104
|
+
value: unknown,
|
|
1105
|
+
method: string,
|
|
1106
|
+
what: string,
|
|
1107
|
+
bytes?: number,
|
|
1108
|
+
): string {
|
|
1109
|
+
const ok =
|
|
1110
|
+
typeof value === 'string' &&
|
|
1111
|
+
/^0x([0-9a-fA-F]{2})*$/.test(value) &&
|
|
1112
|
+
(bytes === undefined || value.length === 2 + 2 * bytes);
|
|
1113
|
+
if (!ok)
|
|
1114
|
+
throw new RpcError(
|
|
1115
|
+
-32602,
|
|
1116
|
+
`${method}: expected ${what} as 0x-prefixed hex of ${bytes === undefined ? 'whole' : `exactly ${bytes}`} bytes, got ${JSON.stringify(value)}`,
|
|
1117
|
+
);
|
|
1118
|
+
return value;
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
/**
|
|
1122
|
+
* A next timestamp must be later than the head's: post-Merge blocks are, and
|
|
1123
|
+
* hardhat refuses an equal one in the same words.
|
|
1124
|
+
*/
|
|
1125
|
+
function laterThanHead(value: unknown, method: string): bigint {
|
|
1126
|
+
const t = quantity(value, method);
|
|
1127
|
+
const head = headTimestamp();
|
|
1128
|
+
if (t <= head)
|
|
1129
|
+
throw new RpcError(
|
|
1130
|
+
-32000,
|
|
1131
|
+
`${method}: timestamp ${t} is lower than or equal to previous block's timestamp ${head}`,
|
|
1132
|
+
);
|
|
1133
|
+
return t;
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
/**
|
|
1137
|
+
* Mine `blocks` blocks now, with whatever is pending in the first (nothing
|
|
1138
|
+
* under auto mining), as anvil's `anvil_mine` does. Without an `interval` the
|
|
1139
|
+
* clock stamps each. With one, it first moves the clock on by `interval`
|
|
1140
|
+
* seconds and stamps the later of the clock and the parent plus `interval`:
|
|
1141
|
+
* 0 lets a block repeat its parent's timestamp (what viem's `mine()` sends by
|
|
1142
|
+
* default). A pending next timestamp still stamps the first block, and an
|
|
1143
|
+
* interval set by `anvil_setBlockTimestampInterval` still stamps every one,
|
|
1144
|
+
* as on anvil. The clock carries on from the last block.
|
|
1145
|
+
*/
|
|
1146
|
+
async function mineBlocks(blocks: bigint, interval?: bigint): Promise<void> {
|
|
1147
|
+
for (let i = 0n; i < blocks; i++) {
|
|
1148
|
+
if (
|
|
1149
|
+
interval !== undefined &&
|
|
1150
|
+
nextTimestamp === undefined &&
|
|
1151
|
+
timestampInterval === undefined
|
|
1152
|
+
) {
|
|
1153
|
+
timeOffset += interval;
|
|
1154
|
+
const clock = clockBase() + timeOffset;
|
|
1155
|
+
const floor = headTimestamp() + interval;
|
|
1156
|
+
nextTimestamp = clock > floor ? clock : floor;
|
|
1157
|
+
}
|
|
1158
|
+
await mineBlock();
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
|
|
951
1162
|
/**
|
|
952
1163
|
* THE BLOCK'S LOGS BLOOM: the OR of its receipts' own blooms, which is what a
|
|
953
1164
|
* block bloom IS. Derived here rather than carried out of the mining loop so
|
|
@@ -1009,6 +1220,12 @@ export async function createNodeWithInternals(
|
|
|
1009
1220
|
): Promise<{blockNumber: number; blockHash: string; txHashes: string[]}> {
|
|
1010
1221
|
const number = blockEnv?.number ?? BigInt(latestNumber + 1);
|
|
1011
1222
|
const blockBaseFee = blockEnv?.baseFeePerGas ?? baseFeePerGas;
|
|
1223
|
+
// THE NODE'S CLOCK (above): unchanged from the wall clock or
|
|
1224
|
+
// `blockEnv.timestamp` until a time cheat is issued. A next timestamp is
|
|
1225
|
+
// spent only once the block is stored, so a refused transaction leaves it
|
|
1226
|
+
// for the block that does get mined.
|
|
1227
|
+
const timestamp = plannedTimestamp();
|
|
1228
|
+
const spendsNextTimestamp = nextTimestamp !== undefined;
|
|
1012
1229
|
const block = createBlock(
|
|
1013
1230
|
{
|
|
1014
1231
|
header: {
|
|
@@ -1016,8 +1233,7 @@ export async function createNodeWithInternals(
|
|
|
1016
1233
|
gasLimit: minedBlockGasLimit,
|
|
1017
1234
|
baseFeePerGas: blockBaseFee,
|
|
1018
1235
|
parentHash,
|
|
1019
|
-
timestamp
|
|
1020
|
-
blockEnv?.timestamp ?? BigInt(Math.floor(Date.now() / 1000)),
|
|
1236
|
+
timestamp,
|
|
1021
1237
|
...(blockEnv?.coinbase
|
|
1022
1238
|
? {coinbase: createAddressFromString(blockEnv.coinbase)}
|
|
1023
1239
|
: {}),
|
|
@@ -1130,6 +1346,10 @@ export async function createNodeWithInternals(
|
|
|
1130
1346
|
// The root BEFORE the record is taken below: `currentStateRoot` applies the
|
|
1131
1347
|
// open record, which at this point is exactly what this block changed.
|
|
1132
1348
|
storeBlock(block, txHashes, blockLogs, await currentStateRoot());
|
|
1349
|
+
if (spendsNextTimestamp) {
|
|
1350
|
+
nextTimestamp = undefined;
|
|
1351
|
+
timeOffset = timestamp - clockBase();
|
|
1352
|
+
}
|
|
1133
1353
|
// THE BLOCK'S CHANGE SET is everything written since the previous head was
|
|
1134
1354
|
// mined: this block's transactions AND any `evm_set*` cheat issued between
|
|
1135
1355
|
// the two blocks, which belongs to this block (the first one that can see
|
|
@@ -1255,6 +1475,8 @@ export async function createNodeWithInternals(
|
|
|
1255
1475
|
*/
|
|
1256
1476
|
function parseTx(rawHex: unknown, claimedFrom?: unknown): SubmittedTx {
|
|
1257
1477
|
const raw = hexToBytes(String(rawHex));
|
|
1478
|
+
refuseIfTypeBeforeItsFork(raw);
|
|
1479
|
+
refuseIfOverTransactionGasCap(raw);
|
|
1258
1480
|
if (claimedFrom === undefined) {
|
|
1259
1481
|
const tx = createTxFromRLP(raw, {common});
|
|
1260
1482
|
// THE CURVE STEP, ON THE ENGINE WHEN THE ENGINE HAS ONE. The DECISION
|
|
@@ -1290,6 +1512,61 @@ export async function createNodeWithInternals(
|
|
|
1290
1512
|
return {tx, raw, sender: from};
|
|
1291
1513
|
}
|
|
1292
1514
|
|
|
1515
|
+
function refuseIfTypeBeforeItsFork(raw: Uint8Array): void {
|
|
1516
|
+
// A TYPE-4 (EIP-7702) TRANSACTION ON A FORK BEFORE PRAGUE is refused in
|
|
1517
|
+
// geth's words rather than reaching the caller as `@ethereumjs/tx`'s own
|
|
1518
|
+
// "EIP-7702 not enabled on Common", with no RPC code. Same reason, and same
|
|
1519
|
+
// place, as the cap refusal below: the parser throws before the node holds a
|
|
1520
|
+
// transaction it could refuse in its own voice.
|
|
1521
|
+
if (raw[0] === 4 && !common.isActivatedEIP(7702))
|
|
1522
|
+
throw new RpcError(
|
|
1523
|
+
-32000,
|
|
1524
|
+
`transaction type not supported: a type-4 (EIP-7702) transaction needs Prague or later, ` +
|
|
1525
|
+
`and this node runs '${hardfork}'. Create the node with hardfork: 'prague' or later to send one.`,
|
|
1526
|
+
);
|
|
1527
|
+
}
|
|
1528
|
+
|
|
1529
|
+
/**
|
|
1530
|
+
* REFUSE A TRANSACTION ABOVE EIP-7825's PER-TRANSACTION GAS CAP (Osaka on),
|
|
1531
|
+
* in geth's words, from its WIRE BYTES, before it is parsed.
|
|
1532
|
+
*
|
|
1533
|
+
* WHY BEFORE PARSING. `@ethereumjs/tx` enforces the cap in its constructor, so
|
|
1534
|
+
* a transaction above it never becomes a `TypedTransaction` the other refusals
|
|
1535
|
+
* could read: it would reach the caller as that library's own exception, with
|
|
1536
|
+
* no RPC error code and no mention of the node, which is the failure the
|
|
1537
|
+
* sibling refusals below exist to remove. So the gas limit is read off the RLP
|
|
1538
|
+
* here (the one field this needs, at its position for each envelope) and a
|
|
1539
|
+
* transaction over the cap is refused as a `-32000` naming both numbers. The
|
|
1540
|
+
* parser's own check stays as the backstop underneath, and revm's
|
|
1541
|
+
* `TxGasLimitGreaterThanCap` under that.
|
|
1542
|
+
*
|
|
1543
|
+
* A MALFORMED ENVELOPE IS LEFT TO THE PARSER: this reads only what it can read,
|
|
1544
|
+
* and anything it cannot decode falls through to `createTxFromRLP`, whose error
|
|
1545
|
+
* is the one such bytes have always produced.
|
|
1546
|
+
*/
|
|
1547
|
+
function refuseIfOverTransactionGasCap(raw: Uint8Array): void {
|
|
1548
|
+
const gasLimit = wireGasLimit(raw);
|
|
1549
|
+
if (gasLimit !== undefined) refuseGasLimitOverTheCap(gasLimit);
|
|
1550
|
+
}
|
|
1551
|
+
|
|
1552
|
+
/**
|
|
1553
|
+
* The EIP-7825 refusal itself, for a gas limit the node already holds as a
|
|
1554
|
+
* number: a raw transaction's (above) and the `gas` a caller hands
|
|
1555
|
+
* `eth_fillTransaction`, which would otherwise reach `createTx` and come back
|
|
1556
|
+
* as that library's own exception rather than an RPC error.
|
|
1557
|
+
*/
|
|
1558
|
+
function refuseGasLimitOverTheCap(gasLimit: bigint): void {
|
|
1559
|
+
const cap = transactionGasLimitCap(common);
|
|
1560
|
+
if (cap === undefined || gasLimit <= cap) return;
|
|
1561
|
+
throw new RpcError(
|
|
1562
|
+
-32000,
|
|
1563
|
+
`transaction gas limit too high (cap: ${cap}, tx: ${gasLimit}). ` +
|
|
1564
|
+
`From Osaka on, EIP-7825 caps the gas limit of a single transaction at ${cap}, whatever the block gas limit is, ` +
|
|
1565
|
+
`so this transaction is REFUSED rather than mined. Sign it again with a gas limit of at most ${cap}; ` +
|
|
1566
|
+
`eth_estimateGas never recommends more. To run without the cap, create the node with hardfork: 'prague'.`,
|
|
1567
|
+
);
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1293
1570
|
/**
|
|
1294
1571
|
* REFUSE A TRANSACTION NO BLOCK THIS NODE BUILDS COULD CONTAIN, in the node's
|
|
1295
1572
|
* own words, before any engine sees it.
|
|
@@ -1449,6 +1726,22 @@ export async function createNodeWithInternals(
|
|
|
1449
1726
|
function refuseIfBelowIntrinsicGas(tx: TypedTransaction): void {
|
|
1450
1727
|
const gasLimit = tx.gasLimit;
|
|
1451
1728
|
const minimum = tx.getIntrinsicGas();
|
|
1729
|
+
// EIP-7623 (Prague on): the calldata floor is a SECOND lower bound on the
|
|
1730
|
+
// limit, independent of the intrinsic one (`max(intrinsic, floor)` is what
|
|
1731
|
+
// `runTx` validates against, and revm refuses with `GasFloorMoreThanGasLimit`).
|
|
1732
|
+
// Checked AFTER the intrinsic bound so a limit below both is reported in the
|
|
1733
|
+
// vocabulary it has always been, and in geth's words for the floor itself.
|
|
1734
|
+
const floor = calldataFloorGas(tx.data, common);
|
|
1735
|
+
if (gasLimit >= minimum && gasLimit < floor) {
|
|
1736
|
+
throw new RpcError(
|
|
1737
|
+
-32000,
|
|
1738
|
+
`insufficient gas for floor data gas cost: have ${gasLimit}, want ${floor}. ` +
|
|
1739
|
+
`From Prague on, EIP-7623 makes a transaction pay at least 21000 plus 10 gas per calldata token ` +
|
|
1740
|
+
`(a zero byte is one token, a non-zero byte four), whatever it executes, so a gas limit below that ` +
|
|
1741
|
+
`could not be charged and no block this node builds could contain it. Raise the gas limit to at least ` +
|
|
1742
|
+
`${floor}; eth_estimateGas never recommends less.`,
|
|
1743
|
+
);
|
|
1744
|
+
}
|
|
1452
1745
|
if (gasLimit >= minimum) return;
|
|
1453
1746
|
throw new RpcError(
|
|
1454
1747
|
-32000,
|
|
@@ -2268,13 +2561,12 @@ export async function createNodeWithInternals(
|
|
|
2268
2561
|
// `createNode({blockGasLimit: 10_000_000_000n})` silently buys every
|
|
2269
2562
|
// unbudgeted `eth_call` a 300x longer runaway, and the browser tab that
|
|
2270
2563
|
// locks up is nowhere near the option that caused it.
|
|
2271
|
-
// - The constant is also QUOTED as a fixed number by the revm engine's
|
|
2272
|
-
// hardfork refusals (`REVM_REFUSED_HARDFORKS.osaka` compares it against
|
|
2273
|
-
// EIP-7825's 16,777,216 cap in src/revm.ts), which a per-node value would
|
|
2274
|
-
// make wrong for some nodes and right for others.
|
|
2275
2564
|
// A caller who wants a bigger budget passes `gas` on the call itself, which is
|
|
2276
2565
|
// the standard `eth_call` field for exactly this and needs no configuration.
|
|
2277
2566
|
//
|
|
2567
|
+
// THE SAME ON EVERY FORK, Osaka included: EIP-7825's cap is a rule about
|
|
2568
|
+
// transactions, and geth's `eth_call` skips it too (see the refusal below).
|
|
2569
|
+
//
|
|
2278
2570
|
// `budget` OVERRIDES BOTH, and exactly one caller passes it: the
|
|
2279
2571
|
// `estimateGas` search below, which is asking a different question from
|
|
2280
2572
|
// "how long may this call run". It probes a candidate gas LIMIT, and the
|
|
@@ -2284,6 +2576,10 @@ export async function createNodeWithInternals(
|
|
|
2284
2576
|
// which for `eth_estimateGas` is a CAP on the limit rather than a budget.
|
|
2285
2577
|
const gasLimit =
|
|
2286
2578
|
budget ?? (params.gas ? BigInt(params.gas) : DEFAULT_READ_BUDGET);
|
|
2579
|
+
refuseReadBelowTheFloor(
|
|
2580
|
+
gasLimit + intrinsicGasOf(data, to === undefined, common),
|
|
2581
|
+
data,
|
|
2582
|
+
);
|
|
2287
2583
|
return engine.call({
|
|
2288
2584
|
from,
|
|
2289
2585
|
to,
|
|
@@ -2294,6 +2590,174 @@ export async function createNodeWithInternals(
|
|
|
2294
2590
|
});
|
|
2295
2591
|
}
|
|
2296
2592
|
|
|
2593
|
+
/**
|
|
2594
|
+
* RUN A READ WITH ITS EIP-7702 AUTHORIZATION LIST APPLIED, the way the mined
|
|
2595
|
+
* transaction would apply it before its first opcode, so that `eth_call` and
|
|
2596
|
+
* `eth_estimateGas` execute the DELEGATED code a type-4 transaction runs.
|
|
2597
|
+
*
|
|
2598
|
+
* WHY THE NODE DOES IT, ABOVE THE SEAM. A read request carries no authorization
|
|
2599
|
+
* list (`ReadCallRequest` has none, exactly as it has no access list), so an
|
|
2600
|
+
* engine cannot apply one. Leaving the list out is not a small error: the usual
|
|
2601
|
+
* type-4 transaction is sent to its own authority, which holds NO code until the
|
|
2602
|
+
* list delegates it, so the read would execute nothing and the estimate would
|
|
2603
|
+
* come back as a bare transfer, a gas limit at which the real transaction runs
|
|
2604
|
+
* out of gas. So the delegations are written into a checkpoint the read runs
|
|
2605
|
+
* in and reverts, through the same state the overrides use, which makes them
|
|
2606
|
+
* identical on every engine.
|
|
2607
|
+
*
|
|
2608
|
+
* THE RULES ARE EIP-7702's, as `@ethereumjs/vm`'s `runTx` applies them, in list
|
|
2609
|
+
* order: an entry is SKIPPED (never an error) when its chain id is neither 0 nor
|
|
2610
|
+
* this chain's, its nonce cannot be bumped, its `s` is high or its `yParity` is
|
|
2611
|
+
* not 0/1, it does not recover, the authority holds code that is not a
|
|
2612
|
+
* delegation, or the authority's nonce is not the entry's (one more than the
|
|
2613
|
+
* account's when the authority is the caller, whose own nonce the transaction
|
|
2614
|
+
* bumps first). A valid entry bumps the authority's nonce and sets its code to
|
|
2615
|
+
* `0xef0100 || address`, or clears it for the zero address.
|
|
2616
|
+
*
|
|
2617
|
+
* WHAT IT DOES NOT MODEL, both in the safe direction for an estimate: the
|
|
2618
|
+
* 12,500 refunded per authority that already existed (the charge in
|
|
2619
|
+
* {@link authorizationListGas} is the full 25,000), and the warming of each
|
|
2620
|
+
* authority (a read touching one pays the cold price the mined transaction does
|
|
2621
|
+
* not).
|
|
2622
|
+
*/
|
|
2623
|
+
async function withAuthorizations<T>(
|
|
2624
|
+
p: any,
|
|
2625
|
+
method: string,
|
|
2626
|
+
read: () => Promise<T>,
|
|
2627
|
+
): Promise<T> {
|
|
2628
|
+
const list = p.authorizationList;
|
|
2629
|
+
if (list == null) return read();
|
|
2630
|
+
if (!Array.isArray(list))
|
|
2631
|
+
throw new RpcError(
|
|
2632
|
+
-32602,
|
|
2633
|
+
`invalid authorizationList for ${method}: expected an array of {chainId, address, nonce, yParity, r, s}.`,
|
|
2634
|
+
);
|
|
2635
|
+
if (!common.isActivatedEIP(7702))
|
|
2636
|
+
throw new RpcError(
|
|
2637
|
+
-32602,
|
|
2638
|
+
`authorizationList is an EIP-7702 field, and this node runs '${hardfork}', which predates it. ` +
|
|
2639
|
+
`Create the node with hardfork: 'prague' or later, or omit the field.`,
|
|
2640
|
+
);
|
|
2641
|
+
if (!p.to)
|
|
2642
|
+
throw new RpcError(
|
|
2643
|
+
-32000,
|
|
2644
|
+
`EIP-7702 transaction cannot be used to create contract: a request carrying an authorizationList must name a \`to\`.`,
|
|
2645
|
+
);
|
|
2646
|
+
if (list.length === 0) return read();
|
|
2647
|
+
const caller = p.from
|
|
2648
|
+
? createAddressFromString(p.from)
|
|
2649
|
+
: createAddressFromString(ZERO_ADDRESS);
|
|
2650
|
+
const quantity = (v: unknown, what: string): bigint => {
|
|
2651
|
+
if (typeof v !== 'string' || !/^0x[0-9a-fA-F]*$/.test(v))
|
|
2652
|
+
throw new RpcError(
|
|
2653
|
+
-32602,
|
|
2654
|
+
`invalid authorizationList entry for ${method}: ${what} must be a hex quantity, got ${JSON.stringify(v)}.`,
|
|
2655
|
+
);
|
|
2656
|
+
return v === '0x' ? 0n : BigInt(v);
|
|
2657
|
+
};
|
|
2658
|
+
await sm.checkpoint();
|
|
2659
|
+
try {
|
|
2660
|
+
for (const entry of list) {
|
|
2661
|
+
if (entry === null || typeof entry !== 'object')
|
|
2662
|
+
throw new RpcError(
|
|
2663
|
+
-32602,
|
|
2664
|
+
`invalid authorizationList entry for ${method}: expected {chainId, address, nonce, yParity, r, s}.`,
|
|
2665
|
+
);
|
|
2666
|
+
const e = entry as Record<string, unknown>;
|
|
2667
|
+
const entryChainId = quantity(e.chainId, 'chainId');
|
|
2668
|
+
const entryNonce = quantity(e.nonce, 'nonce');
|
|
2669
|
+
// viem sends `yParity`; an older shape carries `v` (27/28 or 0/1).
|
|
2670
|
+
const parityRaw =
|
|
2671
|
+
e.yParity !== undefined
|
|
2672
|
+
? quantity(e.yParity, 'yParity')
|
|
2673
|
+
: quantity(e.v, 'yParity');
|
|
2674
|
+
const yParity = parityRaw >= 27n ? parityRaw - 27n : parityRaw;
|
|
2675
|
+
const r = quantity(e.r, 'r');
|
|
2676
|
+
const s = quantity(e.s, 's');
|
|
2677
|
+
if (typeof e.address !== 'string')
|
|
2678
|
+
throw new RpcError(
|
|
2679
|
+
-32602,
|
|
2680
|
+
`invalid authorizationList entry for ${method}: address must be a 20-byte hex string.`,
|
|
2681
|
+
);
|
|
2682
|
+
const target = createAddressFromString(e.address);
|
|
2683
|
+
if (entryChainId !== 0n && entryChainId !== BigInt(chainId)) continue;
|
|
2684
|
+
if (entryNonce >= 2n ** 64n - 1n) continue;
|
|
2685
|
+
if (s > SECP256K1_N_DIV_2 || yParity > 1n) continue;
|
|
2686
|
+
let authority: Address;
|
|
2687
|
+
try {
|
|
2688
|
+
authority = eoaCode7702RecoverAuthority([
|
|
2689
|
+
bigIntToBytes(entryChainId),
|
|
2690
|
+
target.bytes,
|
|
2691
|
+
bigIntToBytes(entryNonce),
|
|
2692
|
+
bigIntToBytes(yParity),
|
|
2693
|
+
bigIntToBytes(r),
|
|
2694
|
+
bigIntToBytes(s),
|
|
2695
|
+
]);
|
|
2696
|
+
} catch {
|
|
2697
|
+
continue;
|
|
2698
|
+
}
|
|
2699
|
+
const account = (await sm.getAccount(authority)) ?? new Account();
|
|
2700
|
+
if (account.isContract()) {
|
|
2701
|
+
const code = await sm.getCode(authority);
|
|
2702
|
+
if (!equalsBytes(code.subarray(0, 3), DELEGATION_PREFIX)) continue;
|
|
2703
|
+
}
|
|
2704
|
+
const expected = authority.equals(caller)
|
|
2705
|
+
? account.nonce + 1n
|
|
2706
|
+
: account.nonce;
|
|
2707
|
+
if (entryNonce !== expected) continue;
|
|
2708
|
+
account.nonce += 1n;
|
|
2709
|
+
await sm.putAccount(authority, account);
|
|
2710
|
+
await sm.putCode(
|
|
2711
|
+
authority,
|
|
2712
|
+
target.isZero()
|
|
2713
|
+
? new Uint8Array()
|
|
2714
|
+
: concatBytes(DELEGATION_PREFIX, target.bytes),
|
|
2715
|
+
);
|
|
2716
|
+
}
|
|
2717
|
+
return await read();
|
|
2718
|
+
} finally {
|
|
2719
|
+
await sm.revert();
|
|
2720
|
+
}
|
|
2721
|
+
}
|
|
2722
|
+
|
|
2723
|
+
/**
|
|
2724
|
+
* A READ BELOW EIP-7623's CALLDATA FLOOR (Prague on) IS REFUSED here, in geth's
|
|
2725
|
+
* words, before any engine sees it.
|
|
2726
|
+
*
|
|
2727
|
+
* `total` is what the read would carry as a transaction's gas limit: the
|
|
2728
|
+
* execution budget plus the intrinsic gas an engine that charges it (revm)
|
|
2729
|
+
* adds back. revm ENFORCES the floor on a read (`GasFloorMoreThanGasLimit`)
|
|
2730
|
+
* and `runCall` on the default engine does not, so without this the same read
|
|
2731
|
+
* would run on one engine and be refused on the other. geth refuses it too
|
|
2732
|
+
* (`insufficient gas for floor data gas cost`, also for `eth_call`). The node
|
|
2733
|
+
* therefore answers it for both, the same move it makes for a transaction's
|
|
2734
|
+
* validity (`refuseIfBelowIntrinsicGas` and friends), and the reason the floor
|
|
2735
|
+
* never crosses the engine seam: see
|
|
2736
|
+
* `docs/adr/0015-the-forks-gas-rules-on-the-read-path-are-the-nodes-admission-and-intrinsic-gas-stays-off-the-seam.md`.
|
|
2737
|
+
*
|
|
2738
|
+
* EIP-7825's CAP IS DELIBERATELY NOT CHECKED HERE: geth skips it for
|
|
2739
|
+
* `eth_call`, `runCall` never enforced it, and the revm engine lifts it on its
|
|
2740
|
+
* reads (`disableTxGasLimitCap`, `revm-wasm@0.5.0`), so a read may run with the
|
|
2741
|
+
* node's default 30,000,000 budget or more on every fork. The cap binds what
|
|
2742
|
+
* the node ADMITS and RECOMMENDS: transactions at submit, and the upper bound
|
|
2743
|
+
* of the `eth_estimateGas` search.
|
|
2744
|
+
*
|
|
2745
|
+
* `eth_estimateGas` never trips the floor: its search only probes limits at or
|
|
2746
|
+
* above it (see {@link estimateGas}).
|
|
2747
|
+
*/
|
|
2748
|
+
function refuseReadBelowTheFloor(total: bigint, data: Uint8Array): void {
|
|
2749
|
+
const floor = calldataFloorGas(data, common);
|
|
2750
|
+
if (total < floor)
|
|
2751
|
+
throw new RpcError(
|
|
2752
|
+
-32000,
|
|
2753
|
+
`insufficient gas for floor data gas cost: have ${total}, want ${floor}. ` +
|
|
2754
|
+
`From Prague on, EIP-7623 makes a transaction pay at least 21000 plus 10 gas per calldata token, ` +
|
|
2755
|
+
`so a call carrying this calldata needs a gas limit of at least ${floor} ` +
|
|
2756
|
+
`(the figure is the call's gas plus the intrinsic gas a transaction with its calldata pays). ` +
|
|
2757
|
+
`Pass a larger \`gas\`, or omit it.`,
|
|
2758
|
+
);
|
|
2759
|
+
}
|
|
2760
|
+
|
|
2297
2761
|
/**
|
|
2298
2762
|
* THE SMALLEST GAS LIMIT AT WHICH THIS REQUEST SUCCEEDS — a SEARCH, not a
|
|
2299
2763
|
* measurement, and the difference is the whole point of this function.
|
|
@@ -2368,8 +2832,27 @@ export async function createNodeWithInternals(
|
|
|
2368
2832
|
async function estimateGas(p: any, block: Block): Promise<bigint> {
|
|
2369
2833
|
const dataHex: string = p.data ?? p.input ?? '0x';
|
|
2370
2834
|
const isCreate = !p.to;
|
|
2371
|
-
const
|
|
2372
|
-
|
|
2835
|
+
const intrinsic = intrinsicGas(dataHex, isCreate, common);
|
|
2836
|
+
// Everything the transaction pays before its first opcode that the engine's
|
|
2837
|
+
// read does NOT: the request's EIP-2930 access list and its EIP-7702
|
|
2838
|
+
// authorization list, charged here because the read request carries neither.
|
|
2839
|
+
const lists =
|
|
2840
|
+
accessListGas(p.accessList) + authorizationListGas(p.authorizationList);
|
|
2841
|
+
const overhead = intrinsic + lists;
|
|
2842
|
+
// THE LOWEST LIMIT WORTH PROBING, and why it can sit above `overhead` (Prague
|
|
2843
|
+
// on). EIP-7623's floor is a bound on the limit, so no limit below it is a
|
|
2844
|
+
// transaction at all. And the read underneath carries no lists, so its own
|
|
2845
|
+
// total is `limit - lists`, which must ALSO reach the floor or revm refuses
|
|
2846
|
+
// the read (`GasFloorMoreThanGasLimit`) where the default engine would run it.
|
|
2847
|
+
// So the search starts at `floor + lists`: exact without lists, and with them
|
|
2848
|
+
// at most `lists` above the protocol's `max(overhead, floor)`, the same on both
|
|
2849
|
+
// engines and in the safe direction. ADR 0015 records the trade.
|
|
2850
|
+
const floor = calldataFloorGas(
|
|
2851
|
+
hexToBytes(dataHex.startsWith('0x') ? dataHex : '0x' + dataHex),
|
|
2852
|
+
common,
|
|
2853
|
+
);
|
|
2854
|
+
const minimum =
|
|
2855
|
+
floor === 0n || floor + lists <= overhead ? overhead : floor + lists;
|
|
2373
2856
|
|
|
2374
2857
|
// THE UPPER BOUND, and why it is capped at the block gas limit even when the
|
|
2375
2858
|
// caller named a larger `gas`: a limit above it is REFUSED at submit by
|
|
@@ -2382,26 +2865,41 @@ export async function createNodeWithInternals(
|
|
|
2382
2865
|
// deliberately (historical-eth-call): the number is for a transaction to be
|
|
2383
2866
|
// SUBMITTED now, and what it meets is the limit of the blocks this node
|
|
2384
2867
|
// mines, whatever K's was. `block` only decides what the probes execute in.
|
|
2868
|
+
//
|
|
2869
|
+
// FROM OSAKA ON IT IS CAPPED AGAIN, at EIP-7825's per-transaction limit, for
|
|
2870
|
+
// the same reason: a transaction above it is refused at submit
|
|
2871
|
+
// (`refuseIfOverTransactionGasCap`). geth's estimator applies the same cap.
|
|
2385
2872
|
const supplied = p.gas != null ? BigInt(p.gas) : undefined;
|
|
2873
|
+
const txCap = transactionGasLimitCap(common);
|
|
2874
|
+
const ceiling =
|
|
2875
|
+
txCap !== undefined && txCap < minedBlockGasLimit
|
|
2876
|
+
? txCap
|
|
2877
|
+
: minedBlockGasLimit;
|
|
2386
2878
|
const cap =
|
|
2387
|
-
supplied === undefined || supplied >
|
|
2388
|
-
? minedBlockGasLimit
|
|
2389
|
-
: supplied;
|
|
2879
|
+
supplied === undefined || supplied > ceiling ? ceiling : supplied;
|
|
2390
2880
|
|
|
2391
2881
|
// Nothing to search: the cap cannot pay for the transaction's own bytes, so
|
|
2392
2882
|
// no limit within it reaches an opcode. Said in the vocabulary of the refusal
|
|
2393
2883
|
// that would meet such a limit at submit, and NOT as `execution reverted`:
|
|
2394
2884
|
// nothing executed, and a client reading a revert here would look for return
|
|
2395
2885
|
// data that does not exist.
|
|
2396
|
-
|
|
2886
|
+
// WHICH ALLOWANCE IT WAS, for the two refusals below: the caller's `gas`, the
|
|
2887
|
+
// block gas limit (a node option), or EIP-7825's cap (the fork's rule, which
|
|
2888
|
+
// no option raises short of choosing another fork).
|
|
2889
|
+
const allowanceWasSupplied = supplied !== undefined && supplied <= ceiling;
|
|
2890
|
+
const allowanceIsTheTxCap =
|
|
2891
|
+
!allowanceWasSupplied && txCap !== undefined && ceiling === txCap;
|
|
2892
|
+
if (cap < minimum) {
|
|
2397
2893
|
throw new RpcError(
|
|
2398
2894
|
-32000,
|
|
2399
|
-
`gas required exceeds allowance (${cap}): this transaction pays ${
|
|
2895
|
+
`gas required exceeds allowance (${cap}): this transaction pays ${minimum} gas ` +
|
|
2400
2896
|
`for its 21000 base, its calldata and its access list before its first opcode ` +
|
|
2401
2897
|
`runs, so no gas limit within the allowance could start it. ` +
|
|
2402
|
-
(
|
|
2898
|
+
(allowanceWasSupplied
|
|
2403
2899
|
? `The allowance is the \`gas\` you passed on the request; raise it or omit it.`
|
|
2404
|
-
:
|
|
2900
|
+
: allowanceIsTheTxCap
|
|
2901
|
+
? `The allowance is EIP-7825's per-transaction gas cap, which this fork enforces on every transaction; no node option raises it.`
|
|
2902
|
+
: `The allowance is this node's block gas limit; raise it with createNode({blockGasLimit: ...}).`),
|
|
2405
2903
|
);
|
|
2406
2904
|
}
|
|
2407
2905
|
|
|
@@ -2445,10 +2943,12 @@ export async function createNodeWithInternals(
|
|
|
2445
2943
|
`allowance and still did not succeed, so it needs more gas than the allowance ` +
|
|
2446
2944
|
`permits (or it cannot succeed at all — an invalid opcode also spends everything). ` +
|
|
2447
2945
|
`Nothing reverted, so there is no revert reason to decode. ` +
|
|
2448
|
-
(
|
|
2946
|
+
(allowanceWasSupplied
|
|
2449
2947
|
? `The allowance is the \`gas\` you passed on the request; raise it or omit it.`
|
|
2450
|
-
:
|
|
2451
|
-
`
|
|
2948
|
+
: allowanceIsTheTxCap
|
|
2949
|
+
? `The allowance is EIP-7825's per-transaction gas cap, which this fork enforces on every transaction; no node option raises it. `
|
|
2950
|
+
: `The allowance is this node's block gas limit, which is also the most a transaction ` +
|
|
2951
|
+
`it mines may ask for; raise it with createNode({blockGasLimit: ...}). `) +
|
|
2452
2952
|
`The engine reported: ${String(top.error)}.`,
|
|
2453
2953
|
);
|
|
2454
2954
|
}
|
|
@@ -2477,7 +2977,11 @@ export async function createNodeWithInternals(
|
|
|
2477
2977
|
// 2) WHAT IT CONSUMED, and the probe that tests whether consumption is also a
|
|
2478
2978
|
// workable limit. `consumed >= cap` means the request needs everything the
|
|
2479
2979
|
// cap allows, and the cap has just been proven to work, so it IS the answer.
|
|
2480
|
-
|
|
2980
|
+
// RAISED TO THE SEARCH'S `minimum` when the floor binds (Prague on): a request
|
|
2981
|
+
// whose execution is cheap next to its calldata is charged the floor, not its
|
|
2982
|
+
// consumption, and a limit below the floor is no transaction at all.
|
|
2983
|
+
const measured = top.executionGasUsed + overhead;
|
|
2984
|
+
const consumed = measured < minimum ? minimum : measured;
|
|
2481
2985
|
if (consumed >= cap) return cap;
|
|
2482
2986
|
if (!(await probe(consumed)).error) return consumed;
|
|
2483
2987
|
|
|
@@ -2556,7 +3060,11 @@ export async function createNodeWithInternals(
|
|
|
2556
3060
|
];
|
|
2557
3061
|
const block = blockStore.get(k ?? latestNumber)!.block;
|
|
2558
3062
|
const r = await pureRead(() =>
|
|
2559
|
-
withStateEntries(entries, () =>
|
|
3063
|
+
withStateEntries(entries, () =>
|
|
3064
|
+
withAuthorizations(params[0] ?? {}, 'eth_call', () =>
|
|
3065
|
+
evmCall(params[0] ?? {}, block),
|
|
3066
|
+
),
|
|
3067
|
+
),
|
|
2560
3068
|
);
|
|
2561
3069
|
if (r.error)
|
|
2562
3070
|
throw new RpcError(3, 'execution reverted', hex(r.returnValue));
|
|
@@ -2578,7 +3086,9 @@ export async function createNodeWithInternals(
|
|
|
2578
3086
|
return numHex(
|
|
2579
3087
|
await pureRead(() =>
|
|
2580
3088
|
withStateEntries(entries, () =>
|
|
2581
|
-
|
|
3089
|
+
withAuthorizations(params[0] ?? {}, 'eth_estimateGas', () =>
|
|
3090
|
+
estimateGas(params[0] ?? {}, block),
|
|
3091
|
+
),
|
|
2582
3092
|
),
|
|
2583
3093
|
),
|
|
2584
3094
|
);
|
|
@@ -2614,12 +3124,20 @@ export async function createNodeWithInternals(
|
|
|
2614
3124
|
// and drops the field), so charging for a list its own answer does not
|
|
2615
3125
|
// contain would hand back a gas limit for a different transaction. See
|
|
2616
3126
|
// `accessListGas` in ./intrinsic-gas.ts.
|
|
3127
|
+
// A caller-supplied `gas` above EIP-7825's cap (Osaka on) is refused here,
|
|
3128
|
+
// in the same words as at submit, rather than by `createTx` below.
|
|
3129
|
+
if (p.gas != null) refuseGasLimitOverTheCap(BigInt(p.gas));
|
|
2617
3130
|
const gas: bigint =
|
|
2618
3131
|
p.gas != null
|
|
2619
3132
|
? BigInt(p.gas)
|
|
2620
3133
|
: await pureRead(() =>
|
|
2621
3134
|
estimateGas(
|
|
2622
|
-
{
|
|
3135
|
+
{
|
|
3136
|
+
...p,
|
|
3137
|
+
gas: undefined,
|
|
3138
|
+
accessList: undefined,
|
|
3139
|
+
authorizationList: undefined,
|
|
3140
|
+
},
|
|
2623
3141
|
blockStore.get(latestNumber)!.block,
|
|
2624
3142
|
),
|
|
2625
3143
|
);
|
|
@@ -2733,37 +3251,108 @@ export async function createNodeWithInternals(
|
|
|
2733
3251
|
// are `evm_*`-namespaced. They write the flat state only; on a `computeStateRoot` node the
|
|
2734
3252
|
// open record names what they wrote, so the next getStateRoot() (or mined
|
|
2735
3253
|
// block) rehashes it into the derived trie.
|
|
2736
|
-
|
|
3254
|
+
//
|
|
3255
|
+
// UNDER HARDHAT'S AND ANVIL'S NAMES TOO (`hardhat_setBalance`,
|
|
3256
|
+
// `anvil_setBalance`, and so on for nonce, code and storage), per ADR 0016's
|
|
3257
|
+
// principle: a cheat answers under the names the other dev nodes give it,
|
|
3258
|
+
// so viem's test actions in `hardhat` and `anvil` mode, and tooling such as
|
|
3259
|
+
// rocketh's `fundImpersonatedAccounts`, reach it unchanged. An alias has
|
|
3260
|
+
// EXACTLY the `evm_*` cheat's effect (the same write, below); what differs
|
|
3261
|
+
// is what it answers and what it refuses, which follow the two nodes:
|
|
3262
|
+
//
|
|
3263
|
+
// - RESULTS ARE ANVIL'S, under both names, as ADR 0016 set for
|
|
3264
|
+
// `hardhat_mine`: `null` for balance, nonce and code, `true` for
|
|
3265
|
+
// storage. anvil serves the `hardhat_*` names as serde aliases of its own
|
|
3266
|
+
// requests (foundry crates/anvil/core/src/eth/mod.rs, `SetBalance`,
|
|
3267
|
+
// `SetNonce`, `SetCode`, `SetStorageAt`) whose handlers return `()`,
|
|
3268
|
+
// `()`, `()` and `true` (crates/anvil/src/eth/api.rs,
|
|
3269
|
+
// `anvil_set_balance` .. `anvil_set_storage_at`), read at foundry
|
|
3270
|
+
// 875cf548. Hardhat answers `true` for all four (EDR ee0dece6,
|
|
3271
|
+
// crates/edr_provider/src/requests/hardhat/state.rs), so a caller that
|
|
3272
|
+
// tests a `hardhat_*` result for `=== true` sees `null` here, as it does
|
|
3273
|
+
// on anvil. viem's test actions discard the result. The `evm_*` names
|
|
3274
|
+
// keep answering `true`.
|
|
3275
|
+
// - VALIDATION IS WHERE BOTH NODES AGREE: an address of 20 bytes; a
|
|
3276
|
+
// balance and a slot below 2^256, a nonce below 2^64 (anvil's U256
|
|
3277
|
+
// narrowed to u64, Hardhat's u64), each a JSON number or a hex or
|
|
3278
|
+
// decimal string as anvil's `deserialize_number` takes it; code as whole
|
|
3279
|
+
// hex bytes; and a storage VALUE of EXACTLY 32 bytes (anvil's `B256`,
|
|
3280
|
+
// Hardhat's reference: "the value to write must be exactly 32 bytes
|
|
3281
|
+
// long"), where `evm_setStorageAt` left-pads a shorter one. Anything
|
|
3282
|
+
// else is `-32602` naming the method, before anything is written.
|
|
3283
|
+
// - THE ONE DIFFERENCE FROM HARDHAT: a nonce LOWER than the account's is
|
|
3284
|
+
// accepted, as anvil (and `evm_setNonce`) accepts it. Hardhat refuses it
|
|
3285
|
+
// (`New nonce (..) must not be smaller than the existing nonce (..)`)
|
|
3286
|
+
// and also refuses any nonce while its pool holds a transaction (EDR
|
|
3287
|
+
// crates/edr_provider/src/data.rs, `set_nonce`); neither is done here.
|
|
3288
|
+
case 'evm_setBalance':
|
|
3289
|
+
case 'hardhat_setBalance':
|
|
3290
|
+
case 'anvil_setBalance': {
|
|
2737
3291
|
// params: [address, valueHex]
|
|
2738
|
-
const
|
|
3292
|
+
const m = args.method;
|
|
3293
|
+
const alias = m !== 'evm_setBalance';
|
|
3294
|
+
const addr = createAddressFromString(
|
|
3295
|
+
alias ? cheatHex(params[0], m, 'an address', 20) : params[0],
|
|
3296
|
+
);
|
|
3297
|
+
const balance = alias
|
|
3298
|
+
? quantity(params[1], m, 'wei', 256n)
|
|
3299
|
+
: BigInt(params[1]);
|
|
2739
3300
|
await mutateAccount(addr, (acc) => {
|
|
2740
|
-
acc.balance =
|
|
3301
|
+
acc.balance = balance;
|
|
2741
3302
|
});
|
|
2742
|
-
return true;
|
|
3303
|
+
return alias ? null : true;
|
|
2743
3304
|
}
|
|
2744
|
-
case 'evm_setNonce':
|
|
3305
|
+
case 'evm_setNonce':
|
|
3306
|
+
case 'hardhat_setNonce':
|
|
3307
|
+
case 'anvil_setNonce': {
|
|
2745
3308
|
// params: [address, nonceHex]
|
|
2746
|
-
const
|
|
3309
|
+
const m = args.method;
|
|
3310
|
+
const alias = m !== 'evm_setNonce';
|
|
3311
|
+
const addr = createAddressFromString(
|
|
3312
|
+
alias ? cheatHex(params[0], m, 'an address', 20) : params[0],
|
|
3313
|
+
);
|
|
3314
|
+
const nonce = alias
|
|
3315
|
+
? quantity(params[1], m, 'transactions')
|
|
3316
|
+
: BigInt(params[1]);
|
|
2747
3317
|
await mutateAccount(addr, (acc) => {
|
|
2748
|
-
acc.nonce =
|
|
3318
|
+
acc.nonce = nonce;
|
|
2749
3319
|
});
|
|
2750
|
-
return true;
|
|
3320
|
+
return alias ? null : true;
|
|
2751
3321
|
}
|
|
2752
|
-
case 'evm_setCode':
|
|
3322
|
+
case 'evm_setCode':
|
|
3323
|
+
case 'hardhat_setCode':
|
|
3324
|
+
case 'anvil_setCode': {
|
|
2753
3325
|
// params: [address, codeHex]
|
|
2754
|
-
const
|
|
2755
|
-
|
|
2756
|
-
|
|
3326
|
+
const m = args.method;
|
|
3327
|
+
const alias = m !== 'evm_setCode';
|
|
3328
|
+
const addr = createAddressFromString(
|
|
3329
|
+
alias ? cheatHex(params[0], m, 'an address', 20) : params[0],
|
|
3330
|
+
);
|
|
3331
|
+
const code = hexToBytes(
|
|
3332
|
+
alias ? cheatHex(params[1], m, 'code') : params[1],
|
|
3333
|
+
);
|
|
3334
|
+
await sm.putCode(addr, code);
|
|
3335
|
+
return alias ? null : true;
|
|
2757
3336
|
}
|
|
2758
|
-
case 'evm_setStorageAt':
|
|
3337
|
+
case 'evm_setStorageAt':
|
|
3338
|
+
case 'hardhat_setStorageAt':
|
|
3339
|
+
case 'anvil_setStorageAt': {
|
|
2759
3340
|
// params: [address, slotHex, valueHex(32-byte)]
|
|
2760
|
-
const
|
|
2761
|
-
const
|
|
2762
|
-
|
|
2763
|
-
|
|
2764
|
-
slot,
|
|
2765
|
-
setLengthLeft(hexToBytes(params[2]), 32),
|
|
3341
|
+
const m = args.method;
|
|
3342
|
+
const alias = m !== 'evm_setStorageAt';
|
|
3343
|
+
const addr = createAddressFromString(
|
|
3344
|
+
alias ? cheatHex(params[0], m, 'an address', 20) : params[0],
|
|
2766
3345
|
);
|
|
3346
|
+
const slot = setLengthLeft(
|
|
3347
|
+
bigIntToBytes(
|
|
3348
|
+
alias ? quantity(params[1], m, 'slot', 256n) : BigInt(params[1]),
|
|
3349
|
+
),
|
|
3350
|
+
32,
|
|
3351
|
+
);
|
|
3352
|
+
const value = alias
|
|
3353
|
+
? hexToBytes(cheatHex(params[2], m, 'a storage value', 32))
|
|
3354
|
+
: setLengthLeft(hexToBytes(params[2]), 32);
|
|
3355
|
+
await sm.putStorage(addr, slot, value);
|
|
2767
3356
|
return true;
|
|
2768
3357
|
}
|
|
2769
3358
|
case 'evm_setAccount': {
|
|
@@ -2786,6 +3375,92 @@ export async function createNodeWithInternals(
|
|
|
2786
3375
|
return true;
|
|
2787
3376
|
}
|
|
2788
3377
|
|
|
3378
|
+
// ---- Time cheats: move THE NODE'S CLOCK ----
|
|
3379
|
+
// They change what the NEXT mined block is stamped with and nothing
|
|
3380
|
+
// already mined; see the clock's own comment for the order a block reads
|
|
3381
|
+
// them in. Names, parameters and results are anvil's (hardhat and
|
|
3382
|
+
// ganache share the `evm_*` ones), so viem's test actions reach them;
|
|
3383
|
+
// mining goes through `mineBlock`, already inside the serialisation point.
|
|
3384
|
+
case 'evm_setNextBlockTimestamp': {
|
|
3385
|
+
// params: [timestamp] — the next block's, once; later than the head's.
|
|
3386
|
+
// Returns null, as anvil does.
|
|
3387
|
+
nextTimestamp = laterThanHead(params[0], 'evm_setNextBlockTimestamp');
|
|
3388
|
+
return null;
|
|
3389
|
+
}
|
|
3390
|
+
case 'evm_increaseTime': {
|
|
3391
|
+
// params: [seconds] — added to the offset. Returns the TOTAL offset in
|
|
3392
|
+
// seconds as a JSON number, as anvil and ganache do.
|
|
3393
|
+
timeOffset += quantity(params[0], 'evm_increaseTime');
|
|
3394
|
+
return Number(timeOffset);
|
|
3395
|
+
}
|
|
3396
|
+
case 'anvil_setBlockTimestampInterval': {
|
|
3397
|
+
// params: [seconds] — each block is its parent's plus this (0 repeats
|
|
3398
|
+
// the parent's); a next timestamp still wins for its block. Returns null.
|
|
3399
|
+
timestampInterval = quantity(
|
|
3400
|
+
params[0],
|
|
3401
|
+
'anvil_setBlockTimestampInterval',
|
|
3402
|
+
);
|
|
3403
|
+
return null;
|
|
3404
|
+
}
|
|
3405
|
+
case 'anvil_removeBlockTimestampInterval': {
|
|
3406
|
+
// Returns whether an interval was set, as anvil does.
|
|
3407
|
+
const was = timestampInterval !== undefined;
|
|
3408
|
+
timestampInterval = undefined;
|
|
3409
|
+
return was;
|
|
3410
|
+
}
|
|
3411
|
+
case 'evm_mine': {
|
|
3412
|
+
// params: [], [timestamp], or [{timestamp?, blocks?}] (anvil's and
|
|
3413
|
+
// ganache's options) — mine `blocks` (default 1) blocks NOW, the first
|
|
3414
|
+
// with whatever is pending (nothing under auto mining, so an empty
|
|
3415
|
+
// block): the RPC form of `node.mine()`. A timestamp is
|
|
3416
|
+
// `evm_setNextBlockTimestamp` for the first. Returns "0x0", as anvil
|
|
3417
|
+
// and ganache do.
|
|
3418
|
+
const opt = params[0];
|
|
3419
|
+
let blocks = 1n;
|
|
3420
|
+
let timestamp: unknown;
|
|
3421
|
+
if (opt != null && typeof opt === 'object' && !Array.isArray(opt)) {
|
|
3422
|
+
const o = opt as {timestamp?: unknown; blocks?: unknown};
|
|
3423
|
+
if (o.blocks != null)
|
|
3424
|
+
blocks = quantity(o.blocks, 'evm_mine', 'blocks');
|
|
3425
|
+
timestamp = o.timestamp ?? undefined;
|
|
3426
|
+
} else if (opt != null) timestamp = opt;
|
|
3427
|
+
if (timestamp !== undefined)
|
|
3428
|
+
nextTimestamp = laterThanHead(timestamp, 'evm_mine');
|
|
3429
|
+
await mineBlocks(blocks);
|
|
3430
|
+
return '0x0';
|
|
3431
|
+
}
|
|
3432
|
+
case 'anvil_mine':
|
|
3433
|
+
case 'hardhat_mine': {
|
|
3434
|
+
// params: [blocks?, interval?] — `blocks` (default 1, 0 mines none)
|
|
3435
|
+
// blocks now; an interval moves the clock on by that many seconds a
|
|
3436
|
+
// block (see `mineBlocks`); viem's `mine()` sends both. Returns null,
|
|
3437
|
+
// as anvil does (which takes `hardhat_mine` as an alias).
|
|
3438
|
+
const blocks =
|
|
3439
|
+
params[0] == null ? 1n : quantity(params[0], args.method, 'blocks');
|
|
3440
|
+
const interval =
|
|
3441
|
+
params[1] == null ? undefined : quantity(params[1], args.method);
|
|
3442
|
+
await mineBlocks(blocks, interval);
|
|
3443
|
+
return null;
|
|
3444
|
+
}
|
|
3445
|
+
|
|
3446
|
+
// ---- Snapshots: roll the whole chain back (see `takeSnapshot`) ----
|
|
3447
|
+
// anvil serves `anvil_snapshot` / `anvil_revert` with `evm_*` as serde
|
|
3448
|
+
// aliases (foundry crates/anvil/core/src/eth/mod.rs, `EvmSnapshot`,
|
|
3449
|
+
// `EvmRevert`), so the two names share one counter here as there.
|
|
3450
|
+
case 'evm_snapshot':
|
|
3451
|
+
case 'anvil_snapshot': {
|
|
3452
|
+
// params: [], and returns the new id as a quantity ("0x0" first).
|
|
3453
|
+
return takeSnapshot();
|
|
3454
|
+
}
|
|
3455
|
+
case 'evm_revert':
|
|
3456
|
+
case 'anvil_revert': {
|
|
3457
|
+
// params: [id], a quantity (hex or decimal string, or a JSON number).
|
|
3458
|
+
// Returns true, or false for an id this node does not hold.
|
|
3459
|
+
return revertToSnapshot(
|
|
3460
|
+
quantity(params[0], args.method, 'a snapshot id', 256n),
|
|
3461
|
+
);
|
|
3462
|
+
}
|
|
3463
|
+
|
|
2789
3464
|
case 'eth_gasPrice':
|
|
2790
3465
|
return numHex(gasPrice);
|
|
2791
3466
|
case 'eth_maxPriorityFeePerGas':
|
|
@@ -3025,6 +3700,7 @@ export async function createNodeWithInternals(
|
|
|
3025
3700
|
return {
|
|
3026
3701
|
version: 1,
|
|
3027
3702
|
chainId,
|
|
3703
|
+
hardfork,
|
|
3028
3704
|
accounts,
|
|
3029
3705
|
code,
|
|
3030
3706
|
storage,
|
|
@@ -3106,6 +3782,29 @@ export async function createNodeWithInternals(
|
|
|
3106
3782
|
}
|
|
3107
3783
|
|
|
3108
3784
|
async function loadState(state: SerializedState): Promise<void> {
|
|
3785
|
+
// THE FORK IS PART OF THE CHAIN, so a dump from another one is REFUSED, before
|
|
3786
|
+
// anything is written. A block's hash covers the header fields its fork
|
|
3787
|
+
// defines (Prague adds `requestsHash`), and the headers below are rebuilt
|
|
3788
|
+
// with THIS node's `Common`, so a Cancun chain loaded into a Prague node
|
|
3789
|
+
// would come back with every block hash changed and a next block naming a
|
|
3790
|
+
// parent no lookup resolves. An unlabelled dump predates the field, when
|
|
3791
|
+
// every node ran Cancun. This also guards a persisted chain: a node restored
|
|
3792
|
+
// from IndexedDB after `hardfork` changed fails to come up, naming the option,
|
|
3793
|
+
// and leaves the stored chain untouched.
|
|
3794
|
+
const dumpedFork = state.hardfork ?? HARDFORK_OF_AN_UNLABELLED_DUMP;
|
|
3795
|
+
if (dumpedFork !== hardfork)
|
|
3796
|
+
throw new Error(
|
|
3797
|
+
`webevm: this state was dumped from a node running hardfork '${dumpedFork}'` +
|
|
3798
|
+
(state.hardfork === undefined
|
|
3799
|
+
? ` (it carries no hardfork, so it predates the option, when every node ran Cancun)`
|
|
3800
|
+
: ``) +
|
|
3801
|
+
` and this node runs '${hardfork}'. A chain's block hashes depend on its fork, so it ` +
|
|
3802
|
+
`cannot be loaded into a node on another one. Create the node with hardfork: '${dumpedFork}' to load it.`,
|
|
3803
|
+
);
|
|
3804
|
+
// A pending next timestamp was set against the OLD head; the loaded one may
|
|
3805
|
+
// already be past it (the clock's offset and interval are node settings and
|
|
3806
|
+
// stay).
|
|
3807
|
+
nextTimestamp = undefined;
|
|
3109
3808
|
// Rehydrate accounts/code/storage directly into SimpleStateManager.
|
|
3110
3809
|
for (const [addr, accHex] of Object.entries(state.accounts)) {
|
|
3111
3810
|
const acc = createAccountFromRLP(hexToBytes(accHex));
|
|
@@ -3213,6 +3912,118 @@ export async function createNodeWithInternals(
|
|
|
3213
3912
|
derivedTrie = await DerivedStateTrie.build(sm, common);
|
|
3214
3913
|
}
|
|
3215
3914
|
|
|
3915
|
+
/**
|
|
3916
|
+
* SNAPSHOTS: `evm_snapshot` returns an id for the chain as it stands, and
|
|
3917
|
+
* `evm_revert(id)` puts it back, under anvil's names too (`anvil_snapshot` /
|
|
3918
|
+
* `anvil_revert`). Why the core and why these names: ADR 0016's principle (a
|
|
3919
|
+
* cheat that is not account policy, under the names the other dev nodes use),
|
|
3920
|
+
* applied in ADR 0017.
|
|
3921
|
+
*
|
|
3922
|
+
* BUILT ON THE NODE'S OWN `dumpState` / `loadState`: a snapshot holds a dump,
|
|
3923
|
+
* a revert empties the state and loads it, so everything a dump carries
|
|
3924
|
+
* (state, blocks, receipts, transactions, logs, the `stateHistory` window) is
|
|
3925
|
+
* restored by construction, and the derived trie is rebuilt. Both run here,
|
|
3926
|
+
* inside the serialisation point every request runs in (ADR 0012). The cost is
|
|
3927
|
+
* O(state) per snapshot and per revert; it is measured and stated in the
|
|
3928
|
+
* README (docs/spikes/snapshots-in-the-core/measurement.md). A cheaper
|
|
3929
|
+
* mechanism over the undo log (ADR 0013) is a later change if that asks for one.
|
|
3930
|
+
*
|
|
3931
|
+
* WHAT A DUMP DOES NOT CARRY, AND A SNAPSHOT DOES, because a snapshot is of
|
|
3932
|
+
* this NODE rather than a portable chain:
|
|
3933
|
+
*
|
|
3934
|
+
* - the undo log EXACTLY, and the open record (writes since the head was
|
|
3935
|
+
* mined). A dump folds the open record into the head's record and a load
|
|
3936
|
+
* makes those writes part of the head (`dumpHistory`), which answers every
|
|
3937
|
+
* read the same until the next block is mined, but then the old head would
|
|
3938
|
+
* read the cheats where a node that never reverted reads the values before
|
|
3939
|
+
* them. So the records are kept unfolded and put back after the load.
|
|
3940
|
+
* - the PENDING transactions (manual and interval mining): Hardhat restores
|
|
3941
|
+
* its mem pool (EDR crates/edr_provider/src/data.rs, `make_snapshot` /
|
|
3942
|
+
* `revert_to_snapshot`, `mem_pool`) and anvil its pool (foundry
|
|
3943
|
+
* crates/anvil/src/eth/api.rs, `evm_snapshot` / `evm_revert`,
|
|
3944
|
+
* `pool_snapshots`).
|
|
3945
|
+
* - THE CLOCK (ADR 0016), decided as anvil does it: a pending NEXT TIMESTAMP
|
|
3946
|
+
* and the OFFSET are restored, the INTERVAL is kept. anvil's `TimeSnapshot`
|
|
3947
|
+
* holds the offset and the next timestamp but not the interval
|
|
3948
|
+
* (crates/anvil/src/eth/backend/time.rs, `snapshot` / `restore`). Hardhat
|
|
3949
|
+
* restores its next timestamp and its offset too (it has no interval), but
|
|
3950
|
+
* ADDS the wall-clock seconds elapsed since the snapshot to the offset, so
|
|
3951
|
+
* that its clock reads what it read at the snapshot (EDR `data.rs`: "now +
|
|
3952
|
+
* new_offset == snapshot_date + old_offset"). That is not done here: anvil
|
|
3953
|
+
* is this node's reference where the two differ (ADR 0016), and on a pinned
|
|
3954
|
+
* `blockEnv.timestamp`, the clock a reproducible test uses, there is no wall
|
|
3955
|
+
* time to compensate for.
|
|
3956
|
+
*
|
|
3957
|
+
* IDS AND CONSUMPTION ARE ANVIL'S: one counter for both names, the first id
|
|
3958
|
+
* "0x0" (anvil's `StateSnapshots` starts at zero, foundry
|
|
3959
|
+
* crates/evm/core/src/state_snapshot.rs; Hardhat's starts at 1, as ganache's
|
|
3960
|
+
* did, and is a `U64` quantity too), never reissued. Reverting to an id
|
|
3961
|
+
* CONSUMES it and every id after it, earlier ones staying usable (both nodes:
|
|
3962
|
+
* anvil `StateSnapshots::remove` and `revert_state_snapshot`'s `retain`, EDR's
|
|
3963
|
+
* `split_off`); an id not held is `false`, not an error, on both. viem sends
|
|
3964
|
+
* `evm_snapshot` / `evm_revert` in every test-client mode and discards the
|
|
3965
|
+
* revert's result.
|
|
3966
|
+
*
|
|
3967
|
+
* NOT DONE, on purpose: a revert emits no `newHeads` (the head moves back, and
|
|
3968
|
+
* the subscription is for new heads; anvil emits removed logs to log filters,
|
|
3969
|
+
* which this node has none of). A `loadState` leaves snapshots held, since
|
|
3970
|
+
* each is a whole chain of its own, so a revert after a load brings back the
|
|
3971
|
+
* chain from before it. Snapshots live in memory and are not persisted.
|
|
3972
|
+
*/
|
|
3973
|
+
interface NodeSnapshot {
|
|
3974
|
+
readonly state: SerializedState;
|
|
3975
|
+
readonly sealed: SerializedHistoryBlock[];
|
|
3976
|
+
readonly historyFloor: number;
|
|
3977
|
+
readonly open: SerializedHistoryBlock | undefined;
|
|
3978
|
+
readonly headBlock: SerializedHistoryBlock | undefined;
|
|
3979
|
+
readonly pending: SubmittedTx[];
|
|
3980
|
+
readonly nextTimestamp: bigint | undefined;
|
|
3981
|
+
readonly timeOffset: bigint;
|
|
3982
|
+
}
|
|
3983
|
+
const snapshots = new Map<bigint, NodeSnapshot>();
|
|
3984
|
+
let nextSnapshotId = 0n;
|
|
3985
|
+
|
|
3986
|
+
async function takeSnapshot(): Promise<string> {
|
|
3987
|
+
const open = changeSets?.peekChangeSet();
|
|
3988
|
+
const id = nextSnapshotId++;
|
|
3989
|
+
snapshots.set(id, {
|
|
3990
|
+
state: await dumpState(),
|
|
3991
|
+
sealed: sealed.map((r) => serializeChangeSet(r.number, r.changes)),
|
|
3992
|
+
historyFloor,
|
|
3993
|
+
open: open && serializeChangeSet(latestNumber, open),
|
|
3994
|
+
headBlock:
|
|
3995
|
+
headBlockChangeSet &&
|
|
3996
|
+
serializeChangeSet(latestNumber, headBlockChangeSet),
|
|
3997
|
+
pending: [...pending],
|
|
3998
|
+
nextTimestamp,
|
|
3999
|
+
timeOffset,
|
|
4000
|
+
});
|
|
4001
|
+
return numHex(id);
|
|
4002
|
+
}
|
|
4003
|
+
|
|
4004
|
+
async function revertToSnapshot(id: bigint): Promise<boolean> {
|
|
4005
|
+
const snapshot = snapshots.get(id);
|
|
4006
|
+
if (snapshot === undefined) return false;
|
|
4007
|
+
for (const held of [...snapshots.keys()])
|
|
4008
|
+
if (held >= id) snapshots.delete(held);
|
|
4009
|
+
// A load writes over what is there and removes nothing, so the state is
|
|
4010
|
+
// emptied first: an account created after the snapshot must not survive.
|
|
4011
|
+
sm.clearState();
|
|
4012
|
+
await loadState(snapshot.state);
|
|
4013
|
+
sealed.length = 0;
|
|
4014
|
+
for (const r of snapshot.sealed)
|
|
4015
|
+
sealed.push({number: r.number, changes: deserializeChangeSet(r)});
|
|
4016
|
+
historyFloor = snapshot.historyFloor;
|
|
4017
|
+
if (snapshot.open !== undefined)
|
|
4018
|
+
sm.replaceChangeSet(deserializeChangeSet(snapshot.open));
|
|
4019
|
+
headBlockChangeSet =
|
|
4020
|
+
snapshot.headBlock && deserializeChangeSet(snapshot.headBlock);
|
|
4021
|
+
pending.splice(0, pending.length, ...snapshot.pending);
|
|
4022
|
+
nextTimestamp = snapshot.nextTimestamp;
|
|
4023
|
+
timeOffset = snapshot.timeOffset;
|
|
4024
|
+
return true;
|
|
4025
|
+
}
|
|
4026
|
+
|
|
3216
4027
|
// ---------- persistence auto-load on creation ----------
|
|
3217
4028
|
if (options.persistence) {
|
|
3218
4029
|
const saved = await options.persistence.load();
|
|
@@ -3271,11 +4082,20 @@ export async function createNodeWithInternals(
|
|
|
3271
4082
|
async function persistingRequest(args: RequestArguments): Promise<unknown> {
|
|
3272
4083
|
const out = await baseRequest(args);
|
|
3273
4084
|
if (
|
|
3274
|
-
(args.method === 'eth_sendRawTransaction' ||
|
|
4085
|
+
((args.method === 'eth_sendRawTransaction' ||
|
|
3275
4086
|
args.method === 'eth_sendRawTransactionSync' ||
|
|
3276
4087
|
args.method === 'evm_sendRawTransactionAs' ||
|
|
3277
4088
|
args.method === 'evm_sendRawTransactionSyncAs') &&
|
|
3278
|
-
|
|
4089
|
+
miningConfig.type === 'auto') ||
|
|
4090
|
+
// The mining cheats mine under every mining config, as `node.mine()`
|
|
4091
|
+
// does, so they persist like `mine()` does.
|
|
4092
|
+
args.method === 'evm_mine' ||
|
|
4093
|
+
args.method === 'anvil_mine' ||
|
|
4094
|
+
args.method === 'hardhat_mine' ||
|
|
4095
|
+
// A revert replaces the chain, so the store must hold the reverted one
|
|
4096
|
+
// (an id the node did not hold changed nothing).
|
|
4097
|
+
((args.method === 'evm_revert' || args.method === 'anvil_revert') &&
|
|
4098
|
+
out === true)
|
|
3279
4099
|
) {
|
|
3280
4100
|
await persistIfNeeded();
|
|
3281
4101
|
}
|