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/dist/node.js CHANGED
@@ -43,7 +43,7 @@ import { packAddressKey, packSlotKey, unpackAddressKey, unpackSlotKey, } from '.
43
43
  import { Common, Mainnet, Hardfork } from '@ethereumjs/common';
44
44
  import { createBlock } from '@ethereumjs/block';
45
45
  import { createTxFromRLP, createTx } from '@ethereumjs/tx';
46
- import { createAddressFromString, createAccountFromRLP, Account, hexToBytes as hexToBytesStrict, bytesToHex, bytesToBigInt, bigIntToHex, setLengthLeft, bigIntToBytes, unpadBytes, } from '@ethereumjs/util';
46
+ import { createAddressFromString, createAccountFromRLP, Account, hexToBytes as hexToBytesStrict, bytesToHex, bytesToBigInt, bigIntToHex, setLengthLeft, bigIntToBytes, unpadBytes, concatBytes, equalsBytes, eoaCode7702RecoverAuthority, } from '@ethereumjs/util';
47
47
  // `@ethereumjs/util`'s hexToBytes is typed to require a `0x${string}` literal.
48
48
  // Our hex comes from runtime sources (RPC params, serialized state) typed as
49
49
  // plain `string`, so wrap it once with a runtime 0x-guard rather than casting at
@@ -65,10 +65,15 @@ import { serveProvider } from '@eip-1193/over-port';
65
65
  // The engine reports EXECUTION gas for a read and the node adds intrinsic gas on top;
66
66
  // an engine that charges intrinsic gas itself (revm) subtracts the SAME formula,
67
67
  // so it has exactly one home. See ./intrinsic-gas.ts.
68
- import { accessListGas, intrinsicGas as intrinsicGasOf, } from './intrinsic-gas.js';
68
+ import { accessListGas, authorizationListGas, calldataFloorGas, intrinsicGas as intrinsicGasOf, transactionGasLimitCap, } from './intrinsic-gas.js';
69
+ import { RLP } from '@ethereumjs/rlp';
69
70
  import { RpcError, } from './types.js';
70
71
  const ZERO_HASH = '0x' + '00'.repeat(32);
71
72
  const ZERO_ADDRESS = '0x' + '00'.repeat(20);
73
+ /** EIP-7702: the code an authority holds once delegated is this, then 20 bytes. */
74
+ const DELEGATION_PREFIX = Uint8Array.of(0xef, 0x01, 0x00);
75
+ /** secp256k1's group order over two: EIP-2's bound on a signature's `s`. */
76
+ const SECP256K1_N_DIV_2 = 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0n;
72
77
  /**
73
78
  * What a block's `logsBloom` reads as when it admits nothing: a block with no
74
79
  * logs, and the defensive fallback for a stored header carrying none at all
@@ -232,6 +237,32 @@ function deserializeChangeSet(record) {
232
237
  function txHashOf(tx) {
233
238
  return hex(tx.hash());
234
239
  }
240
+ /**
241
+ * The GAS LIMIT field of a raw transaction, read off its RLP without building
242
+ * the transaction, or `undefined` for bytes this cannot decode (the parser then
243
+ * produces the error it always has). Its position differs by envelope: a legacy
244
+ * transaction is `[nonce, gasPrice, gasLimit, ...]`, EIP-2930 (type 1) is
245
+ * `[chainId, nonce, gasPrice, gasLimit, ...]`, and every 1559-family envelope
246
+ * (types 2, 3 and 4) is `[chainId, nonce, maxPriorityFee, maxFee, gasLimit, ...]`.
247
+ */
248
+ function wireGasLimit(raw) {
249
+ try {
250
+ if (raw.length === 0)
251
+ return undefined;
252
+ const type = raw[0] >= 0xc0 ? 0 : raw[0];
253
+ if (type > 4)
254
+ return undefined;
255
+ const fields = RLP.decode(type === 0 ? raw : raw.subarray(1));
256
+ if (!Array.isArray(fields))
257
+ return undefined;
258
+ const index = type === 0 ? 2 : type === 1 ? 3 : 4;
259
+ const field = fields[index];
260
+ return field instanceof Uint8Array ? bytesToBigInt(field) : undefined;
261
+ }
262
+ catch {
263
+ return undefined;
264
+ }
265
+ }
235
266
  /**
236
267
  * Intrinsic gas: 21000 base (+32000 create) + calldata (16/non-zero, 4/zero) +
237
268
  * the EIP-3860 initcode word cost (2 gas per 32-byte word) for creates, from
@@ -349,6 +380,40 @@ function validateGenesisTimestamp(options) {
349
380
  `${typeof value === 'bigint' ? `${value}n` : `${describeOption(value)} (${typeof value})`}.`);
350
381
  return value;
351
382
  }
383
+ /**
384
+ * The `@ethereumjs/common` hardfork each {@link NodeHardfork} runs on. ALSO the
385
+ * list of what the option accepts: a fork is here because the node's own gas
386
+ * rules (`./intrinsic-gas.ts`, the read admission in `evmCall`, the estimate's
387
+ * bounds, the submit-time refusals) are implemented and tested for it on BOTH
388
+ * engines, not because `@ethereumjs/common` or revm has a name for it.
389
+ */
390
+ const HARDFORK_OF = Object.freeze({
391
+ cancun: Hardfork.Cancun,
392
+ prague: Hardfork.Prague,
393
+ osaka: Hardfork.Osaka,
394
+ });
395
+ /** What a node runs when `hardfork` is absent: the latest fork it can cost. */
396
+ const DEFAULT_HARDFORK = 'osaka';
397
+ /** What a dump that predates `SerializedState.hardfork` was taken on. */
398
+ const HARDFORK_OF_AN_UNLABELLED_DUMP = 'cancun';
399
+ /**
400
+ * The node's hardfork, or a throw naming the option. A typo (`'Osaka'`,
401
+ * `'pectra'`) must not silently become the default: the fork decides what every
402
+ * transaction costs, and a node on a fork its caller did not ask for computes
403
+ * plausible numbers for the wrong chain.
404
+ */
405
+ function validateHardfork(options) {
406
+ const value = options.hardfork;
407
+ if (value === undefined)
408
+ return DEFAULT_HARDFORK;
409
+ if (typeof value === 'string' && Object.hasOwn(HARDFORK_OF, value))
410
+ return value;
411
+ throw new Error(`webevm: hardfork must be one of ${Object.keys(HARDFORK_OF)
412
+ .map((h) => `'${h}'`)
413
+ .join(', ')} (default '${DEFAULT_HARDFORK}'), got ${describeOption(value)}. ` +
414
+ `Those are the forks whose gas rules this node implements on every engine; ` +
415
+ `an earlier one is not offered, and a later one is not costed yet.`);
416
+ }
352
417
  function describeOption(value) {
353
418
  try {
354
419
  const s = JSON.stringify(value);
@@ -378,9 +443,10 @@ export async function createNodeWithInternals(options, internals) {
378
443
  * root. Only `true` turns it on (see {@link NodeOptions.computeStateRoot}).
379
444
  */
380
445
  const computeStateRoot = options.computeStateRoot === true;
446
+ const hardfork = validateHardfork(options);
381
447
  const common = new Common({
382
448
  chain: { ...Mainnet, chainId, name: 'webevm' },
383
- hardfork: Hardfork.Cancun,
449
+ hardfork: HARDFORK_OF[hardfork],
384
450
  customCrypto: { keccak256: (m) => keccak_256(m) },
385
451
  });
386
452
  // State backing, ONE for every node: our `SimpleStateManager` SUBCLASS, plain
@@ -741,6 +807,111 @@ export async function createNodeWithInternals(options, internals) {
741
807
  // Those two together are the one interleaving the serialisation point does not
742
808
  // cover, so the timer starts after the node is fully built instead.
743
809
  let intervalTimer;
810
+ /**
811
+ * THE NODE'S CLOCK: the timestamp a mined block is stamped with, and the time
812
+ * cheats that move it. They are the methods (and the wire shapes) anvil,
813
+ * hardhat and ganache already share, so viem's test actions drive them
814
+ * unchanged: `evm_setNextBlockTimestamp`, `evm_increaseTime`, `evm_mine`,
815
+ * `anvil_mine` (alias `hardhat_mine`, as anvil has it), and anvil's
816
+ * `anvil_setBlockTimestampInterval` / `anvil_removeBlockTimestampInterval`,
817
+ * which no other dev node defines and so keep anvil's names.
818
+ *
819
+ * WITH NO CHEAT ISSUED IT IS EXACTLY WHAT IT WAS: `blockEnv.timestamp` when
820
+ * pinned, else the wall clock in whole seconds, with no reference to the parent.
821
+ * Whether that default should become strictly increasing is a separate question
822
+ * (work/notes/observations/2026-09-28-mined-block-timestamps-are-not-strictly-increasing.md)
823
+ * which this does not decide. A block reads the cheats in this order:
824
+ *
825
+ * 1. a NEXT TIMESTAMP, set once and used by the next block mined; it must be
826
+ * later than the head's (hardhat's rule, and post-Merge consensus; anvil
827
+ * also admits an equal one), and once a block carries it the OFFSET moves
828
+ * so that the clock carries on from there, as on anvil and hardhat;
829
+ * 2. an INTERVAL: the parent's timestamp plus this many seconds (0 repeats
830
+ * the parent's), the wall clock not consulted, so a chain's timestamps do
831
+ * not depend on when or how fast it ran;
832
+ * 3. the BASE (`blockEnv.timestamp`, else the wall clock) plus the OFFSET,
833
+ * which `evm_increaseTime` adds to.
834
+ *
835
+ * NODE SETTINGS, NOT CHAIN STATE: none of it is in `dumpState`. `loadState`
836
+ * clears a pending next timestamp (the loaded head may already be past it);
837
+ * the offset and the interval belong to this node and survive it.
838
+ */
839
+ let nextTimestamp;
840
+ let timeOffset = 0n;
841
+ let timestampInterval;
842
+ const clockBase = () => blockEnv?.timestamp ?? BigInt(Math.floor(Date.now() / 1000));
843
+ const headTimestamp = () => blockStore.get(latestNumber)?.block.header.timestamp ?? 0n;
844
+ function plannedTimestamp() {
845
+ if (nextTimestamp !== undefined)
846
+ return nextTimestamp;
847
+ if (timestampInterval !== undefined)
848
+ return headTimestamp() + timestampInterval;
849
+ return clockBase() + timeOffset;
850
+ }
851
+ /**
852
+ * A time cheat's integer: a JSON number or a quantity string (hex `0x…` or
853
+ * decimal), the shapes anvil accepts; at most a uint64, a header timestamp's
854
+ * width, unless the caller names another (`bits`: 256 for a balance or a slot).
855
+ * Anything else is `-32602`, naming the method, rather than a guess.
856
+ */
857
+ function quantity(value, method, what = 'seconds', bits = 64n) {
858
+ let s;
859
+ if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0)
860
+ s = BigInt(value);
861
+ else if (typeof value === 'string' &&
862
+ (/^0x[0-9a-fA-F]+$/.test(value) || /^[0-9]+$/.test(value)))
863
+ s = BigInt(value);
864
+ if (s === undefined || s >= 2n ** bits)
865
+ throw new RpcError(-32602, `${method}: expected a non-negative integer number of ${what} below 2^${bits}, got ${JSON.stringify(value)}`);
866
+ return s;
867
+ }
868
+ /**
869
+ * A `hardhat_*` / `anvil_*` state cheat's hex parameter: `0x` and whole bytes,
870
+ * exactly `bytes` of them when given (20 for an address, 32 for a storage
871
+ * value). Anything else is `-32602`, naming the method and what it expected.
872
+ */
873
+ function cheatHex(value, method, what, bytes) {
874
+ const ok = typeof value === 'string' &&
875
+ /^0x([0-9a-fA-F]{2})*$/.test(value) &&
876
+ (bytes === undefined || value.length === 2 + 2 * bytes);
877
+ if (!ok)
878
+ throw new RpcError(-32602, `${method}: expected ${what} as 0x-prefixed hex of ${bytes === undefined ? 'whole' : `exactly ${bytes}`} bytes, got ${JSON.stringify(value)}`);
879
+ return value;
880
+ }
881
+ /**
882
+ * A next timestamp must be later than the head's: post-Merge blocks are, and
883
+ * hardhat refuses an equal one in the same words.
884
+ */
885
+ function laterThanHead(value, method) {
886
+ const t = quantity(value, method);
887
+ const head = headTimestamp();
888
+ if (t <= head)
889
+ throw new RpcError(-32000, `${method}: timestamp ${t} is lower than or equal to previous block's timestamp ${head}`);
890
+ return t;
891
+ }
892
+ /**
893
+ * Mine `blocks` blocks now, with whatever is pending in the first (nothing
894
+ * under auto mining), as anvil's `anvil_mine` does. Without an `interval` the
895
+ * clock stamps each. With one, it first moves the clock on by `interval`
896
+ * seconds and stamps the later of the clock and the parent plus `interval`:
897
+ * 0 lets a block repeat its parent's timestamp (what viem's `mine()` sends by
898
+ * default). A pending next timestamp still stamps the first block, and an
899
+ * interval set by `anvil_setBlockTimestampInterval` still stamps every one,
900
+ * as on anvil. The clock carries on from the last block.
901
+ */
902
+ async function mineBlocks(blocks, interval) {
903
+ for (let i = 0n; i < blocks; i++) {
904
+ if (interval !== undefined &&
905
+ nextTimestamp === undefined &&
906
+ timestampInterval === undefined) {
907
+ timeOffset += interval;
908
+ const clock = clockBase() + timeOffset;
909
+ const floor = headTimestamp() + interval;
910
+ nextTimestamp = clock > floor ? clock : floor;
911
+ }
912
+ await mineBlock();
913
+ }
914
+ }
744
915
  /**
745
916
  * THE BLOCK'S LOGS BLOOM: the OR of its receipts' own blooms, which is what a
746
917
  * block bloom IS. Derived here rather than carried out of the mining loop so
@@ -795,13 +966,19 @@ export async function createNodeWithInternals(options, internals) {
795
966
  async function executeAndMine(txs) {
796
967
  const number = blockEnv?.number ?? BigInt(latestNumber + 1);
797
968
  const blockBaseFee = blockEnv?.baseFeePerGas ?? baseFeePerGas;
969
+ // THE NODE'S CLOCK (above): unchanged from the wall clock or
970
+ // `blockEnv.timestamp` until a time cheat is issued. A next timestamp is
971
+ // spent only once the block is stored, so a refused transaction leaves it
972
+ // for the block that does get mined.
973
+ const timestamp = plannedTimestamp();
974
+ const spendsNextTimestamp = nextTimestamp !== undefined;
798
975
  const block = createBlock({
799
976
  header: {
800
977
  number,
801
978
  gasLimit: minedBlockGasLimit,
802
979
  baseFeePerGas: blockBaseFee,
803
980
  parentHash,
804
- timestamp: blockEnv?.timestamp ?? BigInt(Math.floor(Date.now() / 1000)),
981
+ timestamp,
805
982
  ...(blockEnv?.coinbase
806
983
  ? { coinbase: createAddressFromString(blockEnv.coinbase) }
807
984
  : {}),
@@ -904,6 +1081,10 @@ export async function createNodeWithInternals(options, internals) {
904
1081
  // The root BEFORE the record is taken below: `currentStateRoot` applies the
905
1082
  // open record, which at this point is exactly what this block changed.
906
1083
  storeBlock(block, txHashes, blockLogs, await currentStateRoot());
1084
+ if (spendsNextTimestamp) {
1085
+ nextTimestamp = undefined;
1086
+ timeOffset = timestamp - clockBase();
1087
+ }
907
1088
  // THE BLOCK'S CHANGE SET is everything written since the previous head was
908
1089
  // mined: this block's transactions AND any `evm_set*` cheat issued between
909
1090
  // the two blocks, which belongs to this block (the first one that can see
@@ -1030,6 +1211,8 @@ export async function createNodeWithInternals(options, internals) {
1030
1211
  */
1031
1212
  function parseTx(rawHex, claimedFrom) {
1032
1213
  const raw = hexToBytes(String(rawHex));
1214
+ refuseIfTypeBeforeItsFork(raw);
1215
+ refuseIfOverTransactionGasCap(raw);
1033
1216
  if (claimedFrom === undefined) {
1034
1217
  const tx = createTxFromRLP(raw, { common });
1035
1218
  // THE CURVE STEP, ON THE ENGINE WHEN THE ENGINE HAS ONE. The DECISION
@@ -1061,6 +1244,54 @@ export async function createNodeWithInternals(options, internals) {
1061
1244
  const tx = createTxFromRLP(raw, { common });
1062
1245
  return { tx, raw, sender: from };
1063
1246
  }
1247
+ function refuseIfTypeBeforeItsFork(raw) {
1248
+ // A TYPE-4 (EIP-7702) TRANSACTION ON A FORK BEFORE PRAGUE is refused in
1249
+ // geth's words rather than reaching the caller as `@ethereumjs/tx`'s own
1250
+ // "EIP-7702 not enabled on Common", with no RPC code. Same reason, and same
1251
+ // place, as the cap refusal below: the parser throws before the node holds a
1252
+ // transaction it could refuse in its own voice.
1253
+ if (raw[0] === 4 && !common.isActivatedEIP(7702))
1254
+ throw new RpcError(-32000, `transaction type not supported: a type-4 (EIP-7702) transaction needs Prague or later, ` +
1255
+ `and this node runs '${hardfork}'. Create the node with hardfork: 'prague' or later to send one.`);
1256
+ }
1257
+ /**
1258
+ * REFUSE A TRANSACTION ABOVE EIP-7825's PER-TRANSACTION GAS CAP (Osaka on),
1259
+ * in geth's words, from its WIRE BYTES, before it is parsed.
1260
+ *
1261
+ * WHY BEFORE PARSING. `@ethereumjs/tx` enforces the cap in its constructor, so
1262
+ * a transaction above it never becomes a `TypedTransaction` the other refusals
1263
+ * could read: it would reach the caller as that library's own exception, with
1264
+ * no RPC error code and no mention of the node, which is the failure the
1265
+ * sibling refusals below exist to remove. So the gas limit is read off the RLP
1266
+ * here (the one field this needs, at its position for each envelope) and a
1267
+ * transaction over the cap is refused as a `-32000` naming both numbers. The
1268
+ * parser's own check stays as the backstop underneath, and revm's
1269
+ * `TxGasLimitGreaterThanCap` under that.
1270
+ *
1271
+ * A MALFORMED ENVELOPE IS LEFT TO THE PARSER: this reads only what it can read,
1272
+ * and anything it cannot decode falls through to `createTxFromRLP`, whose error
1273
+ * is the one such bytes have always produced.
1274
+ */
1275
+ function refuseIfOverTransactionGasCap(raw) {
1276
+ const gasLimit = wireGasLimit(raw);
1277
+ if (gasLimit !== undefined)
1278
+ refuseGasLimitOverTheCap(gasLimit);
1279
+ }
1280
+ /**
1281
+ * The EIP-7825 refusal itself, for a gas limit the node already holds as a
1282
+ * number: a raw transaction's (above) and the `gas` a caller hands
1283
+ * `eth_fillTransaction`, which would otherwise reach `createTx` and come back
1284
+ * as that library's own exception rather than an RPC error.
1285
+ */
1286
+ function refuseGasLimitOverTheCap(gasLimit) {
1287
+ const cap = transactionGasLimitCap(common);
1288
+ if (cap === undefined || gasLimit <= cap)
1289
+ return;
1290
+ throw new RpcError(-32000, `transaction gas limit too high (cap: ${cap}, tx: ${gasLimit}). ` +
1291
+ `From Osaka on, EIP-7825 caps the gas limit of a single transaction at ${cap}, whatever the block gas limit is, ` +
1292
+ `so this transaction is REFUSED rather than mined. Sign it again with a gas limit of at most ${cap}; ` +
1293
+ `eth_estimateGas never recommends more. To run without the cap, create the node with hardfork: 'prague'.`);
1294
+ }
1064
1295
  /**
1065
1296
  * REFUSE A TRANSACTION NO BLOCK THIS NODE BUILDS COULD CONTAIN, in the node's
1066
1297
  * own words, before any engine sees it.
@@ -1204,6 +1435,19 @@ export async function createNodeWithInternals(options, internals) {
1204
1435
  function refuseIfBelowIntrinsicGas(tx) {
1205
1436
  const gasLimit = tx.gasLimit;
1206
1437
  const minimum = tx.getIntrinsicGas();
1438
+ // EIP-7623 (Prague on): the calldata floor is a SECOND lower bound on the
1439
+ // limit, independent of the intrinsic one (`max(intrinsic, floor)` is what
1440
+ // `runTx` validates against, and revm refuses with `GasFloorMoreThanGasLimit`).
1441
+ // Checked AFTER the intrinsic bound so a limit below both is reported in the
1442
+ // vocabulary it has always been, and in geth's words for the floor itself.
1443
+ const floor = calldataFloorGas(tx.data, common);
1444
+ if (gasLimit >= minimum && gasLimit < floor) {
1445
+ throw new RpcError(-32000, `insufficient gas for floor data gas cost: have ${gasLimit}, want ${floor}. ` +
1446
+ `From Prague on, EIP-7623 makes a transaction pay at least 21000 plus 10 gas per calldata token ` +
1447
+ `(a zero byte is one token, a non-zero byte four), whatever it executes, so a gas limit below that ` +
1448
+ `could not be charged and no block this node builds could contain it. Raise the gas limit to at least ` +
1449
+ `${floor}; eth_estimateGas never recommends less.`);
1450
+ }
1207
1451
  if (gasLimit >= minimum)
1208
1452
  return;
1209
1453
  throw new RpcError(-32000, `intrinsic gas too low: have ${gasLimit}, want ${minimum}. ` +
@@ -1939,13 +2183,12 @@ export async function createNodeWithInternals(options, internals) {
1939
2183
  // `createNode({blockGasLimit: 10_000_000_000n})` silently buys every
1940
2184
  // unbudgeted `eth_call` a 300x longer runaway, and the browser tab that
1941
2185
  // locks up is nowhere near the option that caused it.
1942
- // - The constant is also QUOTED as a fixed number by the revm engine's
1943
- // hardfork refusals (`REVM_REFUSED_HARDFORKS.osaka` compares it against
1944
- // EIP-7825's 16,777,216 cap in src/revm.ts), which a per-node value would
1945
- // make wrong for some nodes and right for others.
1946
2186
  // A caller who wants a bigger budget passes `gas` on the call itself, which is
1947
2187
  // the standard `eth_call` field for exactly this and needs no configuration.
1948
2188
  //
2189
+ // THE SAME ON EVERY FORK, Osaka included: EIP-7825's cap is a rule about
2190
+ // transactions, and geth's `eth_call` skips it too (see the refusal below).
2191
+ //
1949
2192
  // `budget` OVERRIDES BOTH, and exactly one caller passes it: the
1950
2193
  // `estimateGas` search below, which is asking a different question from
1951
2194
  // "how long may this call run". It probes a candidate gas LIMIT, and the
@@ -1954,6 +2197,7 @@ export async function createNodeWithInternals(options, internals) {
1954
2197
  // budget itself and this function must not re-derive one from `params.gas`,
1955
2198
  // which for `eth_estimateGas` is a CAP on the limit rather than a budget.
1956
2199
  const gasLimit = budget ?? (params.gas ? BigInt(params.gas) : DEFAULT_READ_BUDGET);
2200
+ refuseReadBelowTheFloor(gasLimit + intrinsicGasOf(data, to === undefined, common), data);
1957
2201
  return engine.call({
1958
2202
  from,
1959
2203
  to,
@@ -1963,6 +2207,152 @@ export async function createNodeWithInternals(options, internals) {
1963
2207
  block,
1964
2208
  });
1965
2209
  }
2210
+ /**
2211
+ * RUN A READ WITH ITS EIP-7702 AUTHORIZATION LIST APPLIED, the way the mined
2212
+ * transaction would apply it before its first opcode, so that `eth_call` and
2213
+ * `eth_estimateGas` execute the DELEGATED code a type-4 transaction runs.
2214
+ *
2215
+ * WHY THE NODE DOES IT, ABOVE THE SEAM. A read request carries no authorization
2216
+ * list (`ReadCallRequest` has none, exactly as it has no access list), so an
2217
+ * engine cannot apply one. Leaving the list out is not a small error: the usual
2218
+ * type-4 transaction is sent to its own authority, which holds NO code until the
2219
+ * list delegates it, so the read would execute nothing and the estimate would
2220
+ * come back as a bare transfer, a gas limit at which the real transaction runs
2221
+ * out of gas. So the delegations are written into a checkpoint the read runs
2222
+ * in and reverts, through the same state the overrides use, which makes them
2223
+ * identical on every engine.
2224
+ *
2225
+ * THE RULES ARE EIP-7702's, as `@ethereumjs/vm`'s `runTx` applies them, in list
2226
+ * order: an entry is SKIPPED (never an error) when its chain id is neither 0 nor
2227
+ * this chain's, its nonce cannot be bumped, its `s` is high or its `yParity` is
2228
+ * not 0/1, it does not recover, the authority holds code that is not a
2229
+ * delegation, or the authority's nonce is not the entry's (one more than the
2230
+ * account's when the authority is the caller, whose own nonce the transaction
2231
+ * bumps first). A valid entry bumps the authority's nonce and sets its code to
2232
+ * `0xef0100 || address`, or clears it for the zero address.
2233
+ *
2234
+ * WHAT IT DOES NOT MODEL, both in the safe direction for an estimate: the
2235
+ * 12,500 refunded per authority that already existed (the charge in
2236
+ * {@link authorizationListGas} is the full 25,000), and the warming of each
2237
+ * authority (a read touching one pays the cold price the mined transaction does
2238
+ * not).
2239
+ */
2240
+ async function withAuthorizations(p, method, read) {
2241
+ const list = p.authorizationList;
2242
+ if (list == null)
2243
+ return read();
2244
+ if (!Array.isArray(list))
2245
+ throw new RpcError(-32602, `invalid authorizationList for ${method}: expected an array of {chainId, address, nonce, yParity, r, s}.`);
2246
+ if (!common.isActivatedEIP(7702))
2247
+ throw new RpcError(-32602, `authorizationList is an EIP-7702 field, and this node runs '${hardfork}', which predates it. ` +
2248
+ `Create the node with hardfork: 'prague' or later, or omit the field.`);
2249
+ if (!p.to)
2250
+ throw new RpcError(-32000, `EIP-7702 transaction cannot be used to create contract: a request carrying an authorizationList must name a \`to\`.`);
2251
+ if (list.length === 0)
2252
+ return read();
2253
+ const caller = p.from
2254
+ ? createAddressFromString(p.from)
2255
+ : createAddressFromString(ZERO_ADDRESS);
2256
+ const quantity = (v, what) => {
2257
+ if (typeof v !== 'string' || !/^0x[0-9a-fA-F]*$/.test(v))
2258
+ throw new RpcError(-32602, `invalid authorizationList entry for ${method}: ${what} must be a hex quantity, got ${JSON.stringify(v)}.`);
2259
+ return v === '0x' ? 0n : BigInt(v);
2260
+ };
2261
+ await sm.checkpoint();
2262
+ try {
2263
+ for (const entry of list) {
2264
+ if (entry === null || typeof entry !== 'object')
2265
+ throw new RpcError(-32602, `invalid authorizationList entry for ${method}: expected {chainId, address, nonce, yParity, r, s}.`);
2266
+ const e = entry;
2267
+ const entryChainId = quantity(e.chainId, 'chainId');
2268
+ const entryNonce = quantity(e.nonce, 'nonce');
2269
+ // viem sends `yParity`; an older shape carries `v` (27/28 or 0/1).
2270
+ const parityRaw = e.yParity !== undefined
2271
+ ? quantity(e.yParity, 'yParity')
2272
+ : quantity(e.v, 'yParity');
2273
+ const yParity = parityRaw >= 27n ? parityRaw - 27n : parityRaw;
2274
+ const r = quantity(e.r, 'r');
2275
+ const s = quantity(e.s, 's');
2276
+ if (typeof e.address !== 'string')
2277
+ throw new RpcError(-32602, `invalid authorizationList entry for ${method}: address must be a 20-byte hex string.`);
2278
+ const target = createAddressFromString(e.address);
2279
+ if (entryChainId !== 0n && entryChainId !== BigInt(chainId))
2280
+ continue;
2281
+ if (entryNonce >= 2n ** 64n - 1n)
2282
+ continue;
2283
+ if (s > SECP256K1_N_DIV_2 || yParity > 1n)
2284
+ continue;
2285
+ let authority;
2286
+ try {
2287
+ authority = eoaCode7702RecoverAuthority([
2288
+ bigIntToBytes(entryChainId),
2289
+ target.bytes,
2290
+ bigIntToBytes(entryNonce),
2291
+ bigIntToBytes(yParity),
2292
+ bigIntToBytes(r),
2293
+ bigIntToBytes(s),
2294
+ ]);
2295
+ }
2296
+ catch {
2297
+ continue;
2298
+ }
2299
+ const account = (await sm.getAccount(authority)) ?? new Account();
2300
+ if (account.isContract()) {
2301
+ const code = await sm.getCode(authority);
2302
+ if (!equalsBytes(code.subarray(0, 3), DELEGATION_PREFIX))
2303
+ continue;
2304
+ }
2305
+ const expected = authority.equals(caller)
2306
+ ? account.nonce + 1n
2307
+ : account.nonce;
2308
+ if (entryNonce !== expected)
2309
+ continue;
2310
+ account.nonce += 1n;
2311
+ await sm.putAccount(authority, account);
2312
+ await sm.putCode(authority, target.isZero()
2313
+ ? new Uint8Array()
2314
+ : concatBytes(DELEGATION_PREFIX, target.bytes));
2315
+ }
2316
+ return await read();
2317
+ }
2318
+ finally {
2319
+ await sm.revert();
2320
+ }
2321
+ }
2322
+ /**
2323
+ * A READ BELOW EIP-7623's CALLDATA FLOOR (Prague on) IS REFUSED here, in geth's
2324
+ * words, before any engine sees it.
2325
+ *
2326
+ * `total` is what the read would carry as a transaction's gas limit: the
2327
+ * execution budget plus the intrinsic gas an engine that charges it (revm)
2328
+ * adds back. revm ENFORCES the floor on a read (`GasFloorMoreThanGasLimit`)
2329
+ * and `runCall` on the default engine does not, so without this the same read
2330
+ * would run on one engine and be refused on the other. geth refuses it too
2331
+ * (`insufficient gas for floor data gas cost`, also for `eth_call`). The node
2332
+ * therefore answers it for both, the same move it makes for a transaction's
2333
+ * validity (`refuseIfBelowIntrinsicGas` and friends), and the reason the floor
2334
+ * never crosses the engine seam: see
2335
+ * `docs/adr/0015-the-forks-gas-rules-on-the-read-path-are-the-nodes-admission-and-intrinsic-gas-stays-off-the-seam.md`.
2336
+ *
2337
+ * EIP-7825's CAP IS DELIBERATELY NOT CHECKED HERE: geth skips it for
2338
+ * `eth_call`, `runCall` never enforced it, and the revm engine lifts it on its
2339
+ * reads (`disableTxGasLimitCap`, `revm-wasm@0.5.0`), so a read may run with the
2340
+ * node's default 30,000,000 budget or more on every fork. The cap binds what
2341
+ * the node ADMITS and RECOMMENDS: transactions at submit, and the upper bound
2342
+ * of the `eth_estimateGas` search.
2343
+ *
2344
+ * `eth_estimateGas` never trips the floor: its search only probes limits at or
2345
+ * above it (see {@link estimateGas}).
2346
+ */
2347
+ function refuseReadBelowTheFloor(total, data) {
2348
+ const floor = calldataFloorGas(data, common);
2349
+ if (total < floor)
2350
+ throw new RpcError(-32000, `insufficient gas for floor data gas cost: have ${total}, want ${floor}. ` +
2351
+ `From Prague on, EIP-7623 makes a transaction pay at least 21000 plus 10 gas per calldata token, ` +
2352
+ `so a call carrying this calldata needs a gas limit of at least ${floor} ` +
2353
+ `(the figure is the call's gas plus the intrinsic gas a transaction with its calldata pays). ` +
2354
+ `Pass a larger \`gas\`, or omit it.`);
2355
+ }
1966
2356
  /**
1967
2357
  * THE SMALLEST GAS LIMIT AT WHICH THIS REQUEST SUCCEEDS — a SEARCH, not a
1968
2358
  * measurement, and the difference is the whole point of this function.
@@ -2037,7 +2427,22 @@ export async function createNodeWithInternals(options, internals) {
2037
2427
  async function estimateGas(p, block) {
2038
2428
  const dataHex = p.data ?? p.input ?? '0x';
2039
2429
  const isCreate = !p.to;
2040
- const overhead = intrinsicGas(dataHex, isCreate, common) + accessListGas(p.accessList);
2430
+ const intrinsic = intrinsicGas(dataHex, isCreate, common);
2431
+ // Everything the transaction pays before its first opcode that the engine's
2432
+ // read does NOT: the request's EIP-2930 access list and its EIP-7702
2433
+ // authorization list, charged here because the read request carries neither.
2434
+ const lists = accessListGas(p.accessList) + authorizationListGas(p.authorizationList);
2435
+ const overhead = intrinsic + lists;
2436
+ // THE LOWEST LIMIT WORTH PROBING, and why it can sit above `overhead` (Prague
2437
+ // on). EIP-7623's floor is a bound on the limit, so no limit below it is a
2438
+ // transaction at all. And the read underneath carries no lists, so its own
2439
+ // total is `limit - lists`, which must ALSO reach the floor or revm refuses
2440
+ // the read (`GasFloorMoreThanGasLimit`) where the default engine would run it.
2441
+ // So the search starts at `floor + lists`: exact without lists, and with them
2442
+ // at most `lists` above the protocol's `max(overhead, floor)`, the same on both
2443
+ // engines and in the safe direction. ADR 0015 records the trade.
2444
+ const floor = calldataFloorGas(hexToBytes(dataHex.startsWith('0x') ? dataHex : '0x' + dataHex), common);
2445
+ const minimum = floor === 0n || floor + lists <= overhead ? overhead : floor + lists;
2041
2446
  // THE UPPER BOUND, and why it is capped at the block gas limit even when the
2042
2447
  // caller named a larger `gas`: a limit above it is REFUSED at submit by
2043
2448
  // `refuseIfOverBlockGasLimit`, so recommending one would be the node handing
@@ -2049,22 +2454,35 @@ export async function createNodeWithInternals(options, internals) {
2049
2454
  // deliberately (historical-eth-call): the number is for a transaction to be
2050
2455
  // SUBMITTED now, and what it meets is the limit of the blocks this node
2051
2456
  // mines, whatever K's was. `block` only decides what the probes execute in.
2457
+ //
2458
+ // FROM OSAKA ON IT IS CAPPED AGAIN, at EIP-7825's per-transaction limit, for
2459
+ // the same reason: a transaction above it is refused at submit
2460
+ // (`refuseIfOverTransactionGasCap`). geth's estimator applies the same cap.
2052
2461
  const supplied = p.gas != null ? BigInt(p.gas) : undefined;
2053
- const cap = supplied === undefined || supplied > minedBlockGasLimit
2054
- ? minedBlockGasLimit
2055
- : supplied;
2462
+ const txCap = transactionGasLimitCap(common);
2463
+ const ceiling = txCap !== undefined && txCap < minedBlockGasLimit
2464
+ ? txCap
2465
+ : minedBlockGasLimit;
2466
+ const cap = supplied === undefined || supplied > ceiling ? ceiling : supplied;
2056
2467
  // Nothing to search: the cap cannot pay for the transaction's own bytes, so
2057
2468
  // no limit within it reaches an opcode. Said in the vocabulary of the refusal
2058
2469
  // that would meet such a limit at submit, and NOT as `execution reverted`:
2059
2470
  // nothing executed, and a client reading a revert here would look for return
2060
2471
  // data that does not exist.
2061
- if (cap < overhead) {
2062
- throw new RpcError(-32000, `gas required exceeds allowance (${cap}): this transaction pays ${overhead} gas ` +
2472
+ // WHICH ALLOWANCE IT WAS, for the two refusals below: the caller's `gas`, the
2473
+ // block gas limit (a node option), or EIP-7825's cap (the fork's rule, which
2474
+ // no option raises short of choosing another fork).
2475
+ const allowanceWasSupplied = supplied !== undefined && supplied <= ceiling;
2476
+ const allowanceIsTheTxCap = !allowanceWasSupplied && txCap !== undefined && ceiling === txCap;
2477
+ if (cap < minimum) {
2478
+ throw new RpcError(-32000, `gas required exceeds allowance (${cap}): this transaction pays ${minimum} gas ` +
2063
2479
  `for its 21000 base, its calldata and its access list before its first opcode ` +
2064
2480
  `runs, so no gas limit within the allowance could start it. ` +
2065
- (supplied !== undefined && supplied <= minedBlockGasLimit
2481
+ (allowanceWasSupplied
2066
2482
  ? `The allowance is the \`gas\` you passed on the request; raise it or omit it.`
2067
- : `The allowance is this node's block gas limit; raise it with createNode({blockGasLimit: ...}).`));
2483
+ : allowanceIsTheTxCap
2484
+ ? `The allowance is EIP-7825's per-transaction gas cap, which this fork enforces on every transaction; no node option raises it.`
2485
+ : `The allowance is this node's block gas limit; raise it with createNode({blockGasLimit: ...}).`));
2068
2486
  }
2069
2487
  const probe = (limit) => evmCall(p, block, limit - overhead);
2070
2488
  // 1) THE UPPER BOUND, run first: a request that cannot succeed with all the
@@ -2101,10 +2519,12 @@ export async function createNodeWithInternals(options, internals) {
2101
2519
  `allowance and still did not succeed, so it needs more gas than the allowance ` +
2102
2520
  `permits (or it cannot succeed at all — an invalid opcode also spends everything). ` +
2103
2521
  `Nothing reverted, so there is no revert reason to decode. ` +
2104
- (supplied !== undefined && supplied <= minedBlockGasLimit
2522
+ (allowanceWasSupplied
2105
2523
  ? `The allowance is the \`gas\` you passed on the request; raise it or omit it.`
2106
- : `The allowance is this node's block gas limit, which is also the most a transaction ` +
2107
- `it mines may ask for; raise it with createNode({blockGasLimit: ...}). `) +
2524
+ : allowanceIsTheTxCap
2525
+ ? `The allowance is EIP-7825's per-transaction gas cap, which this fork enforces on every transaction; no node option raises it. `
2526
+ : `The allowance is this node's block gas limit, which is also the most a transaction ` +
2527
+ `it mines may ask for; raise it with createNode({blockGasLimit: ...}). `) +
2108
2528
  `The engine reported: ${String(top.error)}.`);
2109
2529
  }
2110
2530
  const reason = revertReason(top.returnValue);
@@ -2127,7 +2547,11 @@ export async function createNodeWithInternals(options, internals) {
2127
2547
  // 2) WHAT IT CONSUMED, and the probe that tests whether consumption is also a
2128
2548
  // workable limit. `consumed >= cap` means the request needs everything the
2129
2549
  // cap allows, and the cap has just been proven to work, so it IS the answer.
2130
- const consumed = top.executionGasUsed + overhead;
2550
+ // RAISED TO THE SEARCH'S `minimum` when the floor binds (Prague on): a request
2551
+ // whose execution is cheap next to its calldata is charged the floor, not its
2552
+ // consumption, and a limit below the floor is no transaction at all.
2553
+ const measured = top.executionGasUsed + overhead;
2554
+ const consumed = measured < minimum ? minimum : measured;
2131
2555
  if (consumed >= cap)
2132
2556
  return cap;
2133
2557
  if (!(await probe(consumed)).error)
@@ -2205,7 +2629,7 @@ export async function createNodeWithInternals(options, internals) {
2205
2629
  ...parseStateOverrides(params[2], 'eth_call'),
2206
2630
  ];
2207
2631
  const block = blockStore.get(k ?? latestNumber).block;
2208
- const r = await pureRead(() => withStateEntries(entries, () => evmCall(params[0] ?? {}, block)));
2632
+ const r = await pureRead(() => withStateEntries(entries, () => withAuthorizations(params[0] ?? {}, 'eth_call', () => evmCall(params[0] ?? {}, block))));
2209
2633
  if (r.error)
2210
2634
  throw new RpcError(3, 'execution reverted', hex(r.returnValue));
2211
2635
  return hex(r.returnValue);
@@ -2223,7 +2647,7 @@ export async function createNodeWithInternals(options, internals) {
2223
2647
  ...parseStateOverrides(params[2], 'eth_estimateGas'),
2224
2648
  ];
2225
2649
  const block = blockStore.get(k ?? latestNumber).block;
2226
- return numHex(await pureRead(() => withStateEntries(entries, () => estimateGas(params[0] ?? {}, block))));
2650
+ return numHex(await pureRead(() => withStateEntries(entries, () => withAuthorizations(params[0] ?? {}, 'eth_estimateGas', () => estimateGas(params[0] ?? {}, block)))));
2227
2651
  }
2228
2652
  case 'eth_fillTransaction': {
2229
2653
  // Fill the missing fields of a tx request and return {tx, raw} like geth
@@ -2252,9 +2676,18 @@ export async function createNodeWithInternals(options, internals) {
2252
2676
  // and drops the field), so charging for a list its own answer does not
2253
2677
  // contain would hand back a gas limit for a different transaction. See
2254
2678
  // `accessListGas` in ./intrinsic-gas.ts.
2679
+ // A caller-supplied `gas` above EIP-7825's cap (Osaka on) is refused here,
2680
+ // in the same words as at submit, rather than by `createTx` below.
2681
+ if (p.gas != null)
2682
+ refuseGasLimitOverTheCap(BigInt(p.gas));
2255
2683
  const gas = p.gas != null
2256
2684
  ? BigInt(p.gas)
2257
- : await pureRead(() => estimateGas({ ...p, gas: undefined, accessList: undefined }, blockStore.get(latestNumber).block));
2685
+ : await pureRead(() => estimateGas({
2686
+ ...p,
2687
+ gas: undefined,
2688
+ accessList: undefined,
2689
+ authorizationList: undefined,
2690
+ }, blockStore.get(latestNumber).block));
2258
2691
  // Fee fields: legacy iff caller passed gasPrice (and no 1559 fields),
2259
2692
  // otherwise EIP-1559 with the node's constant fee market.
2260
2693
  const isLegacy = p.gasPrice != null &&
@@ -2357,33 +2790,93 @@ export async function createNodeWithInternals(options, internals) {
2357
2790
  // are `evm_*`-namespaced. They write the flat state only; on a `computeStateRoot` node the
2358
2791
  // open record names what they wrote, so the next getStateRoot() (or mined
2359
2792
  // block) rehashes it into the derived trie.
2360
- case 'evm_setBalance': {
2793
+ //
2794
+ // UNDER HARDHAT'S AND ANVIL'S NAMES TOO (`hardhat_setBalance`,
2795
+ // `anvil_setBalance`, and so on for nonce, code and storage), per ADR 0016's
2796
+ // principle: a cheat answers under the names the other dev nodes give it,
2797
+ // so viem's test actions in `hardhat` and `anvil` mode, and tooling such as
2798
+ // rocketh's `fundImpersonatedAccounts`, reach it unchanged. An alias has
2799
+ // EXACTLY the `evm_*` cheat's effect (the same write, below); what differs
2800
+ // is what it answers and what it refuses, which follow the two nodes:
2801
+ //
2802
+ // - RESULTS ARE ANVIL'S, under both names, as ADR 0016 set for
2803
+ // `hardhat_mine`: `null` for balance, nonce and code, `true` for
2804
+ // storage. anvil serves the `hardhat_*` names as serde aliases of its own
2805
+ // requests (foundry crates/anvil/core/src/eth/mod.rs, `SetBalance`,
2806
+ // `SetNonce`, `SetCode`, `SetStorageAt`) whose handlers return `()`,
2807
+ // `()`, `()` and `true` (crates/anvil/src/eth/api.rs,
2808
+ // `anvil_set_balance` .. `anvil_set_storage_at`), read at foundry
2809
+ // 875cf548. Hardhat answers `true` for all four (EDR ee0dece6,
2810
+ // crates/edr_provider/src/requests/hardhat/state.rs), so a caller that
2811
+ // tests a `hardhat_*` result for `=== true` sees `null` here, as it does
2812
+ // on anvil. viem's test actions discard the result. The `evm_*` names
2813
+ // keep answering `true`.
2814
+ // - VALIDATION IS WHERE BOTH NODES AGREE: an address of 20 bytes; a
2815
+ // balance and a slot below 2^256, a nonce below 2^64 (anvil's U256
2816
+ // narrowed to u64, Hardhat's u64), each a JSON number or a hex or
2817
+ // decimal string as anvil's `deserialize_number` takes it; code as whole
2818
+ // hex bytes; and a storage VALUE of EXACTLY 32 bytes (anvil's `B256`,
2819
+ // Hardhat's reference: "the value to write must be exactly 32 bytes
2820
+ // long"), where `evm_setStorageAt` left-pads a shorter one. Anything
2821
+ // else is `-32602` naming the method, before anything is written.
2822
+ // - THE ONE DIFFERENCE FROM HARDHAT: a nonce LOWER than the account's is
2823
+ // accepted, as anvil (and `evm_setNonce`) accepts it. Hardhat refuses it
2824
+ // (`New nonce (..) must not be smaller than the existing nonce (..)`)
2825
+ // and also refuses any nonce while its pool holds a transaction (EDR
2826
+ // crates/edr_provider/src/data.rs, `set_nonce`); neither is done here.
2827
+ case 'evm_setBalance':
2828
+ case 'hardhat_setBalance':
2829
+ case 'anvil_setBalance': {
2361
2830
  // params: [address, valueHex]
2362
- const addr = createAddressFromString(params[0]);
2831
+ const m = args.method;
2832
+ const alias = m !== 'evm_setBalance';
2833
+ const addr = createAddressFromString(alias ? cheatHex(params[0], m, 'an address', 20) : params[0]);
2834
+ const balance = alias
2835
+ ? quantity(params[1], m, 'wei', 256n)
2836
+ : BigInt(params[1]);
2363
2837
  await mutateAccount(addr, (acc) => {
2364
- acc.balance = BigInt(params[1]);
2838
+ acc.balance = balance;
2365
2839
  });
2366
- return true;
2840
+ return alias ? null : true;
2367
2841
  }
2368
- case 'evm_setNonce': {
2842
+ case 'evm_setNonce':
2843
+ case 'hardhat_setNonce':
2844
+ case 'anvil_setNonce': {
2369
2845
  // params: [address, nonceHex]
2370
- const addr = createAddressFromString(params[0]);
2846
+ const m = args.method;
2847
+ const alias = m !== 'evm_setNonce';
2848
+ const addr = createAddressFromString(alias ? cheatHex(params[0], m, 'an address', 20) : params[0]);
2849
+ const nonce = alias
2850
+ ? quantity(params[1], m, 'transactions')
2851
+ : BigInt(params[1]);
2371
2852
  await mutateAccount(addr, (acc) => {
2372
- acc.nonce = BigInt(params[1]);
2853
+ acc.nonce = nonce;
2373
2854
  });
2374
- return true;
2855
+ return alias ? null : true;
2375
2856
  }
2376
- case 'evm_setCode': {
2857
+ case 'evm_setCode':
2858
+ case 'hardhat_setCode':
2859
+ case 'anvil_setCode': {
2377
2860
  // params: [address, codeHex]
2378
- const addr = createAddressFromString(params[0]);
2379
- await sm.putCode(addr, hexToBytes(params[1]));
2380
- return true;
2861
+ const m = args.method;
2862
+ const alias = m !== 'evm_setCode';
2863
+ const addr = createAddressFromString(alias ? cheatHex(params[0], m, 'an address', 20) : params[0]);
2864
+ const code = hexToBytes(alias ? cheatHex(params[1], m, 'code') : params[1]);
2865
+ await sm.putCode(addr, code);
2866
+ return alias ? null : true;
2381
2867
  }
2382
- case 'evm_setStorageAt': {
2868
+ case 'evm_setStorageAt':
2869
+ case 'hardhat_setStorageAt':
2870
+ case 'anvil_setStorageAt': {
2383
2871
  // params: [address, slotHex, valueHex(32-byte)]
2384
- const addr = createAddressFromString(params[0]);
2385
- const slot = setLengthLeft(bigIntToBytes(BigInt(params[1])), 32);
2386
- await sm.putStorage(addr, slot, setLengthLeft(hexToBytes(params[2]), 32));
2872
+ const m = args.method;
2873
+ const alias = m !== 'evm_setStorageAt';
2874
+ const addr = createAddressFromString(alias ? cheatHex(params[0], m, 'an address', 20) : params[0]);
2875
+ const slot = setLengthLeft(bigIntToBytes(alias ? quantity(params[1], m, 'slot', 256n) : BigInt(params[1])), 32);
2876
+ const value = alias
2877
+ ? hexToBytes(cheatHex(params[2], m, 'a storage value', 32))
2878
+ : setLengthLeft(hexToBytes(params[2]), 32);
2879
+ await sm.putStorage(addr, slot, value);
2387
2880
  return true;
2388
2881
  }
2389
2882
  case 'evm_setAccount': {
@@ -2403,6 +2896,85 @@ export async function createNodeWithInternals(options, internals) {
2403
2896
  }
2404
2897
  return true;
2405
2898
  }
2899
+ // ---- Time cheats: move THE NODE'S CLOCK ----
2900
+ // They change what the NEXT mined block is stamped with and nothing
2901
+ // already mined; see the clock's own comment for the order a block reads
2902
+ // them in. Names, parameters and results are anvil's (hardhat and
2903
+ // ganache share the `evm_*` ones), so viem's test actions reach them;
2904
+ // mining goes through `mineBlock`, already inside the serialisation point.
2905
+ case 'evm_setNextBlockTimestamp': {
2906
+ // params: [timestamp] — the next block's, once; later than the head's.
2907
+ // Returns null, as anvil does.
2908
+ nextTimestamp = laterThanHead(params[0], 'evm_setNextBlockTimestamp');
2909
+ return null;
2910
+ }
2911
+ case 'evm_increaseTime': {
2912
+ // params: [seconds] — added to the offset. Returns the TOTAL offset in
2913
+ // seconds as a JSON number, as anvil and ganache do.
2914
+ timeOffset += quantity(params[0], 'evm_increaseTime');
2915
+ return Number(timeOffset);
2916
+ }
2917
+ case 'anvil_setBlockTimestampInterval': {
2918
+ // params: [seconds] — each block is its parent's plus this (0 repeats
2919
+ // the parent's); a next timestamp still wins for its block. Returns null.
2920
+ timestampInterval = quantity(params[0], 'anvil_setBlockTimestampInterval');
2921
+ return null;
2922
+ }
2923
+ case 'anvil_removeBlockTimestampInterval': {
2924
+ // Returns whether an interval was set, as anvil does.
2925
+ const was = timestampInterval !== undefined;
2926
+ timestampInterval = undefined;
2927
+ return was;
2928
+ }
2929
+ case 'evm_mine': {
2930
+ // params: [], [timestamp], or [{timestamp?, blocks?}] (anvil's and
2931
+ // ganache's options) — mine `blocks` (default 1) blocks NOW, the first
2932
+ // with whatever is pending (nothing under auto mining, so an empty
2933
+ // block): the RPC form of `node.mine()`. A timestamp is
2934
+ // `evm_setNextBlockTimestamp` for the first. Returns "0x0", as anvil
2935
+ // and ganache do.
2936
+ const opt = params[0];
2937
+ let blocks = 1n;
2938
+ let timestamp;
2939
+ if (opt != null && typeof opt === 'object' && !Array.isArray(opt)) {
2940
+ const o = opt;
2941
+ if (o.blocks != null)
2942
+ blocks = quantity(o.blocks, 'evm_mine', 'blocks');
2943
+ timestamp = o.timestamp ?? undefined;
2944
+ }
2945
+ else if (opt != null)
2946
+ timestamp = opt;
2947
+ if (timestamp !== undefined)
2948
+ nextTimestamp = laterThanHead(timestamp, 'evm_mine');
2949
+ await mineBlocks(blocks);
2950
+ return '0x0';
2951
+ }
2952
+ case 'anvil_mine':
2953
+ case 'hardhat_mine': {
2954
+ // params: [blocks?, interval?] — `blocks` (default 1, 0 mines none)
2955
+ // blocks now; an interval moves the clock on by that many seconds a
2956
+ // block (see `mineBlocks`); viem's `mine()` sends both. Returns null,
2957
+ // as anvil does (which takes `hardhat_mine` as an alias).
2958
+ const blocks = params[0] == null ? 1n : quantity(params[0], args.method, 'blocks');
2959
+ const interval = params[1] == null ? undefined : quantity(params[1], args.method);
2960
+ await mineBlocks(blocks, interval);
2961
+ return null;
2962
+ }
2963
+ // ---- Snapshots: roll the whole chain back (see `takeSnapshot`) ----
2964
+ // anvil serves `anvil_snapshot` / `anvil_revert` with `evm_*` as serde
2965
+ // aliases (foundry crates/anvil/core/src/eth/mod.rs, `EvmSnapshot`,
2966
+ // `EvmRevert`), so the two names share one counter here as there.
2967
+ case 'evm_snapshot':
2968
+ case 'anvil_snapshot': {
2969
+ // params: [], and returns the new id as a quantity ("0x0" first).
2970
+ return takeSnapshot();
2971
+ }
2972
+ case 'evm_revert':
2973
+ case 'anvil_revert': {
2974
+ // params: [id], a quantity (hex or decimal string, or a JSON number).
2975
+ // Returns true, or false for an id this node does not hold.
2976
+ return revertToSnapshot(quantity(params[0], args.method, 'a snapshot id', 256n));
2977
+ }
2406
2978
  case 'eth_gasPrice':
2407
2979
  return numHex(gasPrice);
2408
2980
  case 'eth_maxPriorityFeePerGas':
@@ -2613,6 +3185,7 @@ export async function createNodeWithInternals(options, internals) {
2613
3185
  return {
2614
3186
  version: 1,
2615
3187
  chainId,
3188
+ hardfork,
2616
3189
  accounts,
2617
3190
  code,
2618
3191
  storage,
@@ -2689,6 +3262,27 @@ export async function createNodeWithInternals(options, internals) {
2689
3262
  historyFloor = kept.length > 0 ? kept[0].number - 1 : latestNumber;
2690
3263
  }
2691
3264
  async function loadState(state) {
3265
+ // THE FORK IS PART OF THE CHAIN, so a dump from another one is REFUSED, before
3266
+ // anything is written. A block's hash covers the header fields its fork
3267
+ // defines (Prague adds `requestsHash`), and the headers below are rebuilt
3268
+ // with THIS node's `Common`, so a Cancun chain loaded into a Prague node
3269
+ // would come back with every block hash changed and a next block naming a
3270
+ // parent no lookup resolves. An unlabelled dump predates the field, when
3271
+ // every node ran Cancun. This also guards a persisted chain: a node restored
3272
+ // from IndexedDB after `hardfork` changed fails to come up, naming the option,
3273
+ // and leaves the stored chain untouched.
3274
+ const dumpedFork = state.hardfork ?? HARDFORK_OF_AN_UNLABELLED_DUMP;
3275
+ if (dumpedFork !== hardfork)
3276
+ throw new Error(`webevm: this state was dumped from a node running hardfork '${dumpedFork}'` +
3277
+ (state.hardfork === undefined
3278
+ ? ` (it carries no hardfork, so it predates the option, when every node ran Cancun)`
3279
+ : ``) +
3280
+ ` and this node runs '${hardfork}'. A chain's block hashes depend on its fork, so it ` +
3281
+ `cannot be loaded into a node on another one. Create the node with hardfork: '${dumpedFork}' to load it.`);
3282
+ // A pending next timestamp was set against the OLD head; the loaded one may
3283
+ // already be past it (the clock's offset and interval are node settings and
3284
+ // stay).
3285
+ nextTimestamp = undefined;
2692
3286
  // Rehydrate accounts/code/storage directly into SimpleStateManager.
2693
3287
  for (const [addr, accHex] of Object.entries(state.accounts)) {
2694
3288
  const acc = createAccountFromRLP(hexToBytes(accHex));
@@ -2786,6 +3380,48 @@ export async function createNodeWithInternals(options, internals) {
2786
3380
  if (computeStateRoot)
2787
3381
  derivedTrie = await DerivedStateTrie.build(sm, common);
2788
3382
  }
3383
+ const snapshots = new Map();
3384
+ let nextSnapshotId = 0n;
3385
+ async function takeSnapshot() {
3386
+ const open = changeSets?.peekChangeSet();
3387
+ const id = nextSnapshotId++;
3388
+ snapshots.set(id, {
3389
+ state: await dumpState(),
3390
+ sealed: sealed.map((r) => serializeChangeSet(r.number, r.changes)),
3391
+ historyFloor,
3392
+ open: open && serializeChangeSet(latestNumber, open),
3393
+ headBlock: headBlockChangeSet &&
3394
+ serializeChangeSet(latestNumber, headBlockChangeSet),
3395
+ pending: [...pending],
3396
+ nextTimestamp,
3397
+ timeOffset,
3398
+ });
3399
+ return numHex(id);
3400
+ }
3401
+ async function revertToSnapshot(id) {
3402
+ const snapshot = snapshots.get(id);
3403
+ if (snapshot === undefined)
3404
+ return false;
3405
+ for (const held of [...snapshots.keys()])
3406
+ if (held >= id)
3407
+ snapshots.delete(held);
3408
+ // A load writes over what is there and removes nothing, so the state is
3409
+ // emptied first: an account created after the snapshot must not survive.
3410
+ sm.clearState();
3411
+ await loadState(snapshot.state);
3412
+ sealed.length = 0;
3413
+ for (const r of snapshot.sealed)
3414
+ sealed.push({ number: r.number, changes: deserializeChangeSet(r) });
3415
+ historyFloor = snapshot.historyFloor;
3416
+ if (snapshot.open !== undefined)
3417
+ sm.replaceChangeSet(deserializeChangeSet(snapshot.open));
3418
+ headBlockChangeSet =
3419
+ snapshot.headBlock && deserializeChangeSet(snapshot.headBlock);
3420
+ pending.splice(0, pending.length, ...snapshot.pending);
3421
+ nextTimestamp = snapshot.nextTimestamp;
3422
+ timeOffset = snapshot.timeOffset;
3423
+ return true;
3424
+ }
2789
3425
  // ---------- persistence auto-load on creation ----------
2790
3426
  if (options.persistence) {
2791
3427
  const saved = await options.persistence.load();
@@ -2842,11 +3478,20 @@ export async function createNodeWithInternals(options, internals) {
2842
3478
  const baseRequest = request;
2843
3479
  async function persistingRequest(args) {
2844
3480
  const out = await baseRequest(args);
2845
- if ((args.method === 'eth_sendRawTransaction' ||
3481
+ if (((args.method === 'eth_sendRawTransaction' ||
2846
3482
  args.method === 'eth_sendRawTransactionSync' ||
2847
3483
  args.method === 'evm_sendRawTransactionAs' ||
2848
3484
  args.method === 'evm_sendRawTransactionSyncAs') &&
2849
- miningConfig.type === 'auto') {
3485
+ miningConfig.type === 'auto') ||
3486
+ // The mining cheats mine under every mining config, as `node.mine()`
3487
+ // does, so they persist like `mine()` does.
3488
+ args.method === 'evm_mine' ||
3489
+ args.method === 'anvil_mine' ||
3490
+ args.method === 'hardhat_mine' ||
3491
+ // A revert replaces the chain, so the store must hold the reverted one
3492
+ // (an id the node did not hold changed nothing).
3493
+ ((args.method === 'evm_revert' || args.method === 'anvil_revert') &&
3494
+ out === true)) {
2850
3495
  await persistIfNeeded();
2851
3496
  }
2852
3497
  return out;