diff --git a/MEGAETH-FORK.md b/MEGAETH-FORK.md
index 4fbd4af500..341d1e90bb 100644
--- a/MEGAETH-FORK.md
+++ b/MEGAETH-FORK.md
@@ -8,7 +8,7 @@ Crate names stay `revm-*`; consumers switch to the fork through a `[patch.crates
revm does not expose the hooks MegaETH needs (multi-dimensional gas, gas preserved on halt, read-only journal access).
Without them, `mega-evm` had to wrap every opcode and copy upstream functions.
-The fork adds those hooks as a thin layer; all MegaETH logic stays in `mega-evm`.
+The fork adds those hooks, and the MegaETH accounting it carries today inside revm's forwarding and settlement, a set rule 2 names and bounds; every other MegaETH rule stays in `mega-evm`.
## Baseline
@@ -36,9 +36,29 @@ The baseline moves only when the MegaETH node moves to a newer revm major (see T
`reth`, `alloy-evm` and `revm-inspectors` are compiled against this fork unmodified; `op-revm` is forked separately at [megaeth-labs/op-revm](https://github.com/megaeth-labs/op-revm) and ported there.
The `Semver` workflow checks every pull request against its base; a deviation passes only with the `api:exception` label, and the pull request body lists every deviating item with the consumers it was checked against.
Each consumer's own CI builds against the tagged fork.
-2. **Thin layer.**
- The fork adds hooks and data; it does not implement MegaETH semantics.
- If a change needs a design decision, it belongs in `mega-evm`.
+ The fork carries accepted exceptions, and each entry under Hooks names its own.
+ One changes the signature of an upstream function the fork picked with the EIP-8037 / EIP-2780 gas core: `pre_execution::apply_auth_list_eip2780`.
+ The fork's takes the context, the authorization list as `&[Eip7702AuthFacts]` and whether EIP-8037 is on, where upstream's takes the journal, an iterator of authorizations and the two state-gas prices, so that every authorization's charge is priced through `Host::state_gas_price` (see State-gas price).
+ The base line has no such function, so the change breaks no code written for it.
+ A consumer that runs the authorization phase through `pre_execution::apply_eip7702_auth_list` or `Handler::apply_eip7702_auth_list`, whose signatures are upstream's, is unaffected.
+ It affects code that calls `apply_auth_list_eip2780` itself, written for upstream's signature: it does not compile against the fork until it passes the context and the list `Eip7702AuthFacts::collect` builds.
+2. **Hooks and data, and a bounded set of MegaETH accounting.**
+ The fork adds hooks and data.
+ It also carries a named, bounded set of MegaETH accounting inside revm's charges and settlement:
+ - withheld regular gas and its crossing record, which every regular charge reads;
+ - the history-gas dimension, charged reservoir-first, unwound with state gas, and charged for deployed code inside `return_create`;
+ - give-backs to the reservoir alone, which change where revm's refills, rollbacks and reservoir merges credit a give-back, and the legacy share of an opcode's state charge.
+
+ Each item has its entry under Hooks, whose Default keeps upstream's results for a consumer that sets nothing.
+ Nothing else that implements MegaETH semantics enters the fork.
+ What a consumer decides per frame start, such as a budget, a charge the frame's failure gives back, an allowance or a part of the caller's reservoir it keeps, it keeps beside revm's gas, driven by the start lifecycle's hooks; the lifecycle carries no MegaETH figure, so it is a generic hook and the set does not grow with it (see Start lifecycle).
+ An addition to the set needs all of these, argued in its pull request:
+ - no hook that sees only the state revm exposes at that point can make the same decision, because the figure is read or written inside a charge, or has to be ordered with revm's own settlement; the pull request says why the consumer cannot keep it beside revm's gas;
+ - it is mechanism, not policy: every amount, share, price and limit comes from the consumer, through the gas schedule or a hook, and a detail the fork has to fix itself, such as a rounding, is named in its entry;
+ - zero, unlimited or none as its default leaves every result upstream's, and its entry states what a consumer that sets nothing pays for it, in bytes on the frame results and in instructions;
+ - its entry names the condition under which the fork drops it.
+
+ A design decision still belongs in `mega-evm`: the fork carries the figures and moves them with the gas, and `mega-evm` decides what they are and what happens when one runs out.
3. **Cargo versions stay fixed between base-line moves.**
The `[patch.crates-io]` mechanism only applies when the patched version satisfies the consumer's requirement, and pre-release suffixes do not satisfy `^40.0.3`.
Releases are identified by git tags only.
@@ -61,26 +81,52 @@ The baseline moves only when the MegaETH node moves to a newer revm major (see T
A tag is the only identity a fork release has (rule 3), and the release workflow tags only commits whose `ci success` is green.
Consumer tag pinning is not enforced mechanically; each consumer's `Cargo.lock` records the commit it built against.
+## What the fork carries
+
+`git diff ..` is the fork's footprint on upstream (rule 4).
+It falls into five classes, and the next base-line move (see Tracking upstream) treats each one differently.
+The sizes are the lines of `crates/`, without tests, that `git blame ..` attributes to each class's commits.
+
+| Class | What | Size | At the next base-line move |
+|---|---|---|---|
+| Upstream gas core | The EIP-8037 / EIP-2780 gas core, picked from later upstream releases | about 2,600 lines | Goes away once the new base contains every pick; the sweep issues record which tag first contains each. The settlement code the fork's MegaETH accounting is written into is upstream's own (`handle_reservoir_remaining_gas`, `rollback_state_gas`, `return_create`), so that accounting is re-applied to the new base's versions of it. |
+| Other upstream picks | Fixes and performance picks | about 140 lines | Goes away once the new base contains them; a pick the base lacks is picked again or dropped, as its sweep decides. A behaviour a switch takes back stays switchable (see Consumer switches). |
+| Generic hooks | State-gas price, precompile price, code-deposit admission, the failed-charge record, the completed-write and frame-start hooks, the pending action, the frame-run-result hook and the start lifecycle | not counted | Each is proposed upstream, in a form upstream can take: without MegaETH vocabulary in its types, as an instruction-level helper rather than a `Host` method where one serves, and with no cost on the default path that upstream would not accept. It is carried until upstream has an equivalent (its Removal). |
+| Consumer switches | Amsterdam opcodes and EIP-7708 below Amsterdam, the base line's journal semantics | about 300 lines | Carried until their Removal conditions. The Amsterdam switch is proposed in the shape of upstream's per-EIP activation switches, which already cover three of its four opcodes; the base line's journal semantics are not proposed. |
+| MegaETH accounting (rule 2) | Withheld regular gas, the history-gas dimension, give-backs to the reservoir alone and the legacy share | about 800 lines | Carried and re-applied to the new base, or replaced: an item a later design keeps in `mega-evm` instead, with the same results for the consumer that uses it, leaves the fork, and its entry's Removal says when. |
+
## Hooks
-This section lists every hook and switch the fork carries.
+This section lists every hook, switch and accessor the fork carries, and each item of rule 2's MegaETH accounting.
Each entry names the API a consumer uses and what the fork guarantees about it.
A hook's default keeps upstream's behaviour: a consumer that does not use it sees the same results.
-Each entry's **Consumer** says who needs it and why it cannot be done outside the fork, its **Removal** the condition under which the fork drops it, and its **Default** what it costs a consumer that does not use it.
+Each entry's **Consumer** says who uses it and why the fork carries it, its **Removal** the condition under which the fork drops it, and its **Default** what it costs a consumer that does not use it.
+
+A field a hook adds to a serialized type carries `serde(default)`, so in a format that carries field names, such as JSON, an encoding made before the field existed decodes with the default.
+A format that encodes a struct by position, such as bincode, cannot read such an encoding, as with upstream's own field additions: it reads the old fields in their places and then looks for the new ones, so a value persisted in such a format must not cross an upgrade of the fork that adds a field.
+
+A gas schedule (`GasParams`) is a table of 256 entries, not named fields, so `serde(default)` cannot reach an entry: a table built raw (`GasParams::new`) or decoded from an encoding made before an entry existed holds zero there.
+Every entry the fork adds is therefore zero by default, and zero is upstream's behaviour: such a table behaves as the default schedule does.
+An id the fork once used for an entry is left unused rather than given a new meaning, so a table encoded then does not read as a setting: ids 246 to 254 are such ids.
### State-gas price
- **API.** `Host::state_gas_price(&mut self, id: GasId, site: StateGasSite) -> Option` and `Host::state_gas_charge(&mut self, charge: StateGasCharge) -> Option`.
The value types `StateGasSite` (`account`, `slot`) and `StateGasCharge` (`one`, `units`, `total`) in `revm_context_interface::cfg`.
For the refund: `charged_state_gas_address` on `CreateInputs`, `CallOutcome` and `CreateOutcome`, and `FrameResult::refundable_state_gas_charge`.
- `pre_execution::Eip7702AuthFacts`, the authorization list lifted out of the transaction so the authorization phase can hand the whole context to the hook.
+ `pre_execution::Eip7702AuthFacts`, the authorization list lifted out of the transaction so the authorization phase can hand the whole context to the hook, and the signature of `pre_execution::apply_auth_list_eip2780`, which takes the context and that list in place of upstream's journal, authorization iterator and two state-gas prices (an exception to rule 1).
- **Contract.** Every EIP-8037 state-gas charge and every refund of one is priced through `state_gas_price`, so a charge and the refund that undoes it agree by construction.
`site` names the account the charge lands on, and the storage slot for a slot-scoped charge; a creation is priced at the address it deploys at, the first frame's included.
`None` reports a failed lookup: the implementation records the cause in the context error, and the charge site turns it into a fatal external error.
- **Consumer.** mega-evm prices state gas by the storage bucket of the account or slot a charge lands on. Only the charge site knows the site, and the price must be the same at the charge and at its refund.
- **Removal.** When upstream prices state gas through an equivalent hook, or when mega-evm prices every state-gas charge from the flat schedule.
-- **Default.** Reads the flat schedule (`gas_params().get(id)`) and never fails, so every charge and refund is upstream's.
+- **Default.** Reads the flat schedule (`gas_params().get(id)`) and never fails, so every price is upstream's, and so is every charge and refund but one.
+ With EIP-2780 on, the first frame's creation is checked and charged at the address it deploys at, which the caller's account nonce gives, where upstream's derives the address from the transaction's nonce.
+ The two agree while the nonce check is on.
+ With the nonce check off and a transaction nonce that differs from the caller's account nonce, as for an OP deposit, upstream's checks, charges and warms an address the transaction does not deploy at, and the fork's the address it deploys at.
+ There, whether the creation pays `create_state_gas` can differ from upstream's, and so can the gas of a later access to the other address, which upstream's leaves warm and the fork's leaves cold.
The refund carries one address more in the frame inputs and outcomes, and under EIP-2780 an EIP-7702 transaction's authorization list is buffered before the authorization phase, one 88-byte entry per authorization that can apply.
+ `CallOutcome` and `CreateOutcome` are constructible by literal and carry `charged_state_gas_address`, which upstream's do not, so an outcome literal written for upstream's fields does not compile against the fork until it names it (`Address::ZERO` with nothing charged).
### History gas
@@ -88,13 +134,34 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th
`GasId::code_deposit_history_gas` and `GasParams::code_deposit_history_gas(len)`.
- **Contract.** A history charge draws the same reservoir-first budget as a state-gas charge: the reservoir, then regular gas, withheld part first.
It is booked on its own counter, so history gas can be reported and limited apart from state gas.
- It unwinds with state gas: a frame that reverts or halts refills both in last-in-first-out order, and `refill_history` returns a spill before it tops up the reservoir.
+ It unwinds with state gas: a frame that reverts or halts refills both in last-in-first-out order, and `refill_history` returns a spill before it tops up the reservoir, unless give-backs go to the reservoir alone (see Give-backs to the reservoir alone and the legacy share).
`return_create` charges `code_deposit_history_gas` for the deployed bytes after their state-gas charge.
`ResultGas` has no field for it: `total_gas_spent` and `block_regular_gas_used` include it, and the `ResultGas` documentation says how a block-level consumer separates it.
- **Consumer.** mega-evm charges history gas for the bytes a transaction appends to the chain's history. The code deposit is charged inside `return_create`, and only the tracker can unwind a frame's history charges with its state charges.
- **Removal.** When upstream carries an equivalent gas dimension, or when mega-evm stops charging history gas.
- **Default.** No schedule prices `code_deposit_history_gas`, and nothing else in the workspace charges history gas, so the counter stays zero and every result is upstream's.
- The counter decodes as zero from encodings that predate it.
+ In a format that carries field names, the counter decodes as zero from encodings that predate it.
+
+### Give-backs to the reservoir alone and the legacy share
+
+- **API.** `CfgEnv::reservoir_only_give_backs` with `with_reservoir_only_give_backs`, and `Cfg::reservoir_only_give_backs` (default `false`).
+ On `GasTracker`, forwarded on `Gas`: `reservoir_only_give_backs`, `set_reservoir_only_give_backs`, `record_state_cost_with_legacy_share`, `consume_regular_paid_charges` and `halted_regular_paid`; on `GasTracker` alone, `add_regular_paid_of`.
+ `GasId::sstore_set_state_gas_legacy_share`, `new_account_state_gas_legacy_share`, `selfdestruct_new_account_state_gas_legacy_share` and `create_state_gas_legacy_share` (ids 245 to 242), with their `GasParams` accessors, and the `state_gas_with_legacy_share!` instruction macro.
+- **Contract.** revm sets the switch on the transaction's gas (`Handler::tx_gas`) and on every frame's gas, and on the results it builds for a call or creation it answers without running a frame (`EthFrame::make_call_frame`, `make_create_frame`), from the configuration.
+ With it on, no give-back of state or history gas credits regular gas: `refill_reservoir` and `refill_history` top up the reservoir alone, `rollback_state_gas` sets the reservoir to `reservoir + state_gas_spent + history_gas_spent` and leaves regular gas as it was, and `absorb_returned_reservoir` takes the returned reservoir as the caller's without unwinding anything.
+ A frame's regular gas then rises within the frame only by the regular gas a child returns.
+ `state_gas_spilled` counts every part of a state or history charge regular gas paid in a frame and in the frames below it that returned to it, and no give-back lowers it: a child adds its count to its caller's however it ended (`handle_reservoir_remaining_gas`, `add_regular_paid_of`).
+ A halt takes the part of the count no halt below consumed yet out of the reservoir the rollback set, which leaves the reservoir the frame received, and records the whole count as consumed (`consume_regular_paid_charges`, `halted_regular_paid`), before it spends the regular gas; the record travels up with the count, so a caller's own halt does not take a halted child's part out a second time.
+ After a halt of the transaction's frame, `settle_first_frame` gives back only the part of the EIP-2780 first-frame charge the reservoir paid: that charge is the last made before the frame, and every charge there draws the reservoir first, so the part regular gas paid is the last `min(charge, paid)` of what the transaction's count held before the frame's joined it.
+ The legacy share is the part of an opcode's state charge regular gas pays before the reservoir pays any of it: `SSTORE`'s fresh slot, a value `CALL`'s new account, a `SELFDESTRUCT`'s new beneficiary and a `CREATE`'s or `CREATE2`'s created account each take `min(charge, entry)` of their schedule entry from regular gas, withheld part first, before the reservoir; a value call's and a creation's before the forward is computed.
+ A frame whose regular gas cannot pay the share and what the reservoir cannot pay runs out of gas, whatever the reservoir holds.
+ The share is state gas, counted with its charge and given back with it, and the switch and the shares are independent: with the switch off a share is part of the spill a give-back unwinds.
+- **Consumer.** mega-evm keeps a frame's regular gas from rising within the frame by gas spent on state and history, and keeps creating state at its pre-Amsterdam price in regular gas when a transaction carries a reservoir.
+ Every refill, rollback and reservoir merge that credits regular gas is inside revm: an `SSTORE` that writes a slot back refills inside its instruction, and a frame's rollback and the merge of its reservoir into its caller's are revm's settlement, so no hook that sees the gas afterwards can tell what revm credited; and a value call's and a creation's share must come off regular gas before the opcode computes its forward.
+- **Removal.** When upstream's EIP-8037 credits every give-back to the reservoir and takes a legacy share from regular gas, as ethereum/EIPs#12581 proposes, or when mega-evm stops doing either.
+- **Default.** The switch is off and every share entry is zero, so every result is upstream's: `record_state_cost_with_legacy_share` with a share of zero is `record_state_cost`, `consume_regular_paid_charges` changes nothing, a failed child's count, which its rollback zeroed, is not added, and `halted_regular_paid` stays zero.
+ The switch is a `bool` in a word the tracker already had; the record of what halts consumed is a word of its own, so `GasTracker` is 96 bytes and `Gas` 112, `InterpreterResult` 152, `CallOutcome` and `FrameResult` 216 and `CreateOutcome` 200 (64-bit targets), still copied inline; in a format that carries field names the two decode as `false` and zero from encodings that predate them.
+ In instructions, a give-back, a rollback and a merge read one `bool`, a value call that creates an account and the three other share sites read one schedule entry, and every frame's construction reads the switch from the configuration once.
### Amsterdam opcodes and transfer logs below Amsterdam
@@ -138,7 +205,7 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th
- a regular charge (`record_regular_cost`, `record_cost_unsafe`), whether or not the withheld part would have paid it;
- a state or history charge whose spill past the reservoir regular gas cannot pay (`record_state_cost`, `record_history_cost`), whether the reservoir paid nothing or part of it; the record is regular gas alone, and the reservoir is left as it was;
- a forward to a child that regular gas cannot pay (`record_withheld_first_cost`), which only a call before EIP-150 can fail;
- - an out-of-gas halt of the interpreter with no record there, before the halt zeroes the frame's gas: a cold access the instruction refused before its charge because the frame could not pay it (an account read, `SLOAD`, `SSTORE`, `SELFDESTRUCT`, a call's target and the account it delegates to), or an out-of-gas a consumer's instruction returned itself; a record already there is the failure that caused the halt, and is kept;
+ - an out-of-gas halt of the interpreter with no record there, before the halt zeroes the frame's gas: a cold access the instruction refused before its charge because the frame could not pay it (an account read, `SLOAD`, `SSTORE`, `SELFDESTRUCT`, a call's target and the account it delegates to), an out-of-gas a consumer's instruction returned itself, or one an instruction hook asked for (see Completed-write hook and Frame-start hook); a record already there is the failure that caused the halt, and is kept;
- a precompile run that needs more gas than the frame has: the frame's whole gas limit, as nothing ran.
The failed deduction took nothing, so the record is all the regular gas the frame had; the unchecked charge records it before the spendable part wraps, and a failure with nothing left records `Some(0)`.
@@ -151,7 +218,8 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th
- **Consumer.** mega-evm's gas detention reads what a halting frame burned. An `OutOfGas` halt zeroes the frame's regular gas inside the interpreter, before the frame's result reaches any boundary mega-evm owns.
- **Removal.** When upstream keeps a halting frame's regular gas readable, or when mega-evm no longer reads what a halting frame burned.
- **Default.** Each record is written on the failure side only: the tracker's in cold, out-of-line functions, the interpreter's in its cold out-of-gas halt, the handler's on a precompile's out-of-gas. A deduction or load that succeeds runs the same code.
- It is two words: the tracker is 88 bytes, and a copy of the tracker, and of every `Gas` and frame result that holds one, is 16 bytes larger.
+ It takes two words of the tracker, a number and a flag, and the flag's word also holds the start mark (see Start lifecycle); every copy of the tracker, and of every `Gas` and frame result that holds one, carries both words.
+ Encoded, the record is an optional number in the field's place.
Where measured (callgrind, the fork's release profile), the field left a transfer and a precompile call unchanged and cost about 0.1% of the instructions of a creation; the records written on the failure side add nothing measurable.
### Precompile price
@@ -170,7 +238,7 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th
- **Coverage.** Every precompile the crate defines carries its price function, so every precompile of every set `Precompiles::new` returns answers.
A precompile built with `Precompile::new` carries none and answers `None`.
A precompile that wraps a built-in must price itself from the price function of the run it wraps, and price its own refusals at `0`; `with_required_gas`'s documentation shows the pattern, and such a wrapper needs a differential test against its own run.
- Outstanding: the port to the op-revm fork. At `v20.0.0-mega.2` its nine size-limited wrappers (the BN254 pairing and the BLS12-381 G1 MSM, G2 MSM and pairing, across its hardforks) are built with `Precompile::new` and answer `None`.
+ A precompile defined outside this repository that wraps a revm run must price itself from the run it wraps, as the op-revm fork's size-limited wrappers do; that fork's `MEGAETH-FORK.md` ("Precompile prices") carries their guard.
- **Guard.** `ecrecover`, `sha256`, `ripemd160` and `blake2f` repeat literals their runs keep private; the differential test `required_gas_matches_every_builtin_run`, run under every backend, fails when a run's gas changes and its price does not.
- **Consumer.** mega-evm holds a precompile call to an allowance below its forward and must tell a crossing from a plain out-of-gas without running it. A precompile's gas rule is private to its run.
- **Removal.** When upstream exposes a precompile's price before the run, or when mega-evm stops holding precompile calls to an allowance.
@@ -190,7 +258,7 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th
The deposit's charges, and with them its state-gas price lookup through `Host::state_gas_price`, are made before it is offered, so that lookup is made whether or not the deposit is admitted; a refusal does not undo what the lookup recorded.
- **Reach.** The hook is on the context `return_create` is called with, so a consumer that wraps `EthFrame`, runs `process_next_action` from its own `frame_run`, or customises `Handler` reaches it by implementing `ContextTr` for its context.
A context that wraps another and implements `ContextTr` by hand must forward the method, or it gets the admitting default.
-- **Consumer.** mega-evm refuses a deposit its own rules reject, after revm's checks and charges and before the creation commits. That point is inside `return_create`, between its last charge and the checkpoint commit.
+- **Consumer.** mega-evm refuses a deposit its own rules reject, after revm's checks and charges and before the creation commits, and counts the deployed code against the creating frame's budget there. That point is inside `return_create`, between its last charge and the checkpoint commit.
- **Removal.** When upstream has an equivalent admission point, or when mega-evm stops refusing deposits.
- **Default.** `return_create` compiles to the same code, on its own and inlined into the handler on the plain and the inspected path.
Inlined into a consumer's own function, the admitting default may shift its block layout; where measured, that cost one unconditional branch on one out-of-gas path and changed no success path.
@@ -204,22 +272,234 @@ Each entry's **Consumer** says who needs it and why it cannot be done outside th
- **Removal.** When no consumer needs to reproduce revm 40.0.3's journal.
- **Default.** Off, which is the picked behaviour; the journal reads one `bool` when it warms a cold slot and when it records a code change.
+### Completed-write hook
+
+- **API.** `Host::write_completed(&mut self, write: CompletedWrite<'_>, gas: &mut GasTracker) -> WriteVerdict`, whose default continues.
+ `CompletedWrite` (`Sstore`, `Log`, `SelfDestruct`, with the write's account and what the instruction knows of it; `SelfDestruct` also carries `balance`, the destructed account's balance before the write) and `WriteVerdict` (`Continue`, `OutOfGas`, `Revert(Bytes)`), in `revm_context_interface::host`.
+ `CompletedWrite` is exhaustive on purpose: mega-evm matches it to meter each write, so a new kind is a compile error in every consumer that matches it rather than a write that passes a wildcard arm un-metered, and adding one is an `api:exception` change.
+ Its variants' fields are exhaustive too: a consumer that builds a variant, or matches one naming every field without `..`, names every field, `SelfDestruct`'s `balance` included, and a field added to a variant is an `api:exception` change as a new kind is.
+- **Contract.** `SSTORE`, `LOG0`–`LOG4` and `SELFDESTRUCT` call it once the write is in the journal and every charge the instruction makes has been made, its refund included, so only on the instruction's success path, on the plain and the inspected path.
+ `gas` is the running frame's tracker. The hook may debit and credit it, and the instruction uses it as the hook left it: nothing is charged after the hook. A charge the hook makes that fails records as any failed charge does (see The failed-charge record), whatever the verdict.
+ `Continue` ends the instruction as it would have ended. `OutOfGas` fails it as a failed charge does: the frame halts out of gas, and the halt records the regular gas the hook left unless a failed charge already did. `Revert(output)` ends the frame as a `Revert` with `output`, on its gas as the hook left it; a `SELFDESTRUCT` so reverted does not self-destruct.
+ Only these instructions call it: a write the journal records any other way (a value transfer and its log, deployed code, an inspector's or a precompile's write) is not offered.
+ A destruction changes only balances, no nonce and no code. So with the journal at the hook, `SelfDestruct`'s `balance` rebuilds both accounts as they were before the write: the destructed account held `balance`, and a beneficiary that is another account held its balance less `balance`, since it got all of it.
+ When the beneficiary is the destructed account itself, the account's balance after the write says whether the spec burned the balance or left it.
+- **Consumer.** mega-evm meters each completed write against its per-transaction limits and charges its history. Without the hook it wraps the three instructions and stages what its `Host` saw.
+ It counts an account's write record while the account's info differs from what the transaction loaded. A destruction's two accounts can look the same after the write whether or not they had changed before it (loaded with 5, now 0, from 5 or from 7), so it needs the balance before the write, which only the instruction reads before the write.
+- **Removal.** When upstream exposes an equivalent point, or when mega-evm stops metering writes.
+- **Default.** Continues and touches nothing. The facts are references to values the instruction holds anyway, except `SelfDestruct`'s `balance`, which the instruction reads for the hook from the running frame's own account just before the write. The journal holds that account warm, so the read loads nothing cold.
+ Where measured (callgrind, the fork's release profile), `SSTORE` and `LOG0`–`LOG4` compile to the same code as without the hook. The read costs a `SELFDESTRUCT` 119 instructions, one warm journal lookup (+1.5% of a transaction that self-destructs a contract). It is a `Host::load_account_info_skip_cold_load` call that upstream's instruction does not make, so a `Host` that counts or refuses loads sees one more per `SELFDESTRUCT`.
+
+### Frame-start hook
+
+- **API.** `Host::frame_starting(&mut self, start: &mut FrameStart, gas: &mut GasTracker) -> bool`, whose default returns `true`.
+ `FrameStart` (`#[non_exhaustive]`, built with `FrameStart::new`: `kind`, `caller`, `target`, `value`, `forward`, and `reservoir`, which `new` leaves `None`) and `FrameStartKind` (`Call`, `CallCode`, `DelegateCall`, `StaticCall`, `Create`, `Create2`), in `revm_context_interface::host`.
+ `FrameStartKind` is exhaustive on purpose, as `CompletedWrite` is: mega-evm matches it to charge each start, so a new kind is a compile error in every consumer that matches it rather than a start that passes a wildcard arm uncharged, and adding one is an `api:exception` change.
+- **Contract.** `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2` call it after every charge they make and after the forward is taken from the caller's gas, before they build the frame's input, on the plain and the inspected path.
+ `forward` is the regular gas taken: the frame's gas limit without a value call's stipend. `value` is the value transferred, zero for `DELEGATECALL` and `STATICCALL`.
+ `target` is the account the frame runs as: the account called for `CALL` and `STATICCALL`, the calling frame's own for `CALLCODE` and `DELEGATECALL`, and for `CREATE` and `CREATE2` the address the creation would take.
+ Whether a creation takes it is the outcome's to say (`CreateOutcome::address`): a creation that lands on an account that already has code or a nonce, one the handler refuses after the hook (an inspector changed the caller's balance), and one an inspector's `create` or a consumer's `frame_init` answers without a frame take none, though their start named the address. A consumer that counts the created account from `target` settles that count on the outcome.
+ A creation's address is computed once, into the creation's input, and the handler builds the frame at it without computing it again. With EIP-8037 on, the instruction's EIP-8037 branch computes it. With EIP-8037 off, the instruction computes it after the same checks, reading the caller's balance and nonce from the journal.
+ It is `None` only for a creation the handler fails before it takes an address: an endowment above the caller's balance, a caller's nonce at its maximum, or a creating frame at the depth limit. Such a creation reaches the hook only with EIP-8037 off; with it on, the instruction ends the creation before the hook.
+ The address is fixed when the hook sees it. Something that changes the caller's nonce between the instruction and the frame does not move it, as on upstream's EIP-8037 path. An inspector that changes the creation's caller, scheme or init code (`CreateInputs::set_call`, `set_scheme`, `set_init_code`) clears it, and the handler computes the new one.
+ `gas` is the caller's tracker. The hook may debit and credit it, and the instruction uses it as the hook left it: nothing is charged after the hook, and the frame's input copies the reservoir the hook left in it, so a frame the handler runs and one it answers without running (a precompile) both start from that reservoir. A charge the hook makes that fails records as any failed charge does, whatever the answer.
+ `start` is the hook's to name the child's reservoir on (`reservoir`), if it takes that out of `gas` itself; the instruction reads nothing else back from it.
+ `FrameStart::reservoir` is `None` when the hook is called. `None` leaves the frame's input a copy of the reservoir in `gas`, which the caller keeps while the child runs, as upstream's instructions do. `Some(r)` means the hook took the child's reservoir out of `gas` itself: the frame's input carries `r` instead, and the caller keeps what the hook left it. The instruction does not check `r` against what the hook took.
+ Either way the child's settlement replaces the caller's reservoir with the one the child returns, as upstream's does; a consumer that kept part of the caller's reservoir adds it back when revm settles the child (`FrameSettle::held_reservoir`, see Start lifecycle).
+ `true` hands the start to the handler, which may still refuse it (call depth, balance) or answer it without a frame; what the hook did to `gas` stands either way. `false` fails the instruction out of gas and starts no frame: the forward stays taken unless the hook gave it back, and the halt records the regular gas the hook left unless a failed charge already did.
+ A creation the instruction ends before its forward (EIP-8037's checks of the endowment, the nonce and the depth) is not offered.
+- **Consumer.** mega-evm charges a start's write records after the forward and before the frame inherits the caller's reservoir. Without the hook it wraps the call and creation instructions, rewrites the reservoir revm already copied into the input, and takes the input back when the charge fails.
+ It counts the created account's record only when the transaction has not changed that account already (funded it, say), so it needs the address at the start. A `CREATE2`'s address depends on the init-code hash, which only the instruction has.
+- **Removal.** When upstream exposes an equivalent point, or when mega-evm stops charging frame starts.
+- **Default.** Returns `true` and touches nothing.
+ Where measured (callgrind, the fork's release profile), a call runs one instruction more than without the hook: the store of the forward its helper returns, about 0.05% of a call to a contract that stops.
+ For `CREATE` and `CREATE2` the hook's only cost is the start's address.
+ With EIP-8037 off, the default spec's path, the address costs a warm journal read of the caller and the three checks: 149 instructions per `CREATE` and 147 per `CREATE2` from a contract (+0.95% and +0.73%). The read is a `Host::load_account_info_skip_cold_load` call that upstream's instruction does not make, so a `Host` that counts or refuses loads sees one more per creation.
+ The instruction computes the address and a `CREATE2`'s init-code hash, and the handler reuses them, so a creation the handler builds or fails computes the same hashes as upstream's.
+ A start that never reaches the handler's frame building computes them for the hook alone: one hash for a `CREATE`, two for a `CREATE2`. That is a start the hook refuses, and a creation answered without a frame, by an inspector's `create` or by a consumer's own `frame_init`. Upstream's EIP-8037 path computes them before the hook in the same way.
+ With EIP-8037 on, the start reads the address the EIP-8037 branch already computed from the input; that path was not measured.
+ `CreateInputs`' derived `PartialEq` compares the cached address and hash, which the input of a creation the instruction starts holds with EIP-8037 on and off, so it compares unequal to an otherwise equal input that has computed nothing, and to its own serde round trip, which skips the cache.
+ A consumer tells a creation from a call by `kind`, not by `target`: `target` is `None` only for the creations the Contract names, and for every other start an address, which for a creation is the one it would take.
+
+### The pending action
+
+- **API.** No new item: upstream's `LoopControl::set_action` on a frame's interpreter, which `Interpreter::run_plain` (and `run_plain_as_output`) and `revm_inspector::inspect_instructions` honour before their first instruction, and which `InspectorEvmTr::inspect_frame_init` reads before it hands a new frame to `Inspector::initialize_interp`.
+- **Contract.** An action set on a frame's interpreter before the frame runs is what the run returns, before any instruction runs. That is an action set once `frame_init` built the frame, or once `frame_return_result` put a child's result into its caller.
+ The plain and the inspected run return it alike: no instruction executes, so the frame's gas, stack, memory and program counter are as they were when it was set, and the inspected run calls neither `Inspector::step` nor `step_end` for that run.
+ The handler then processes it as any instruction's action (`process_next_action`): a `NewFrame` starts a child, a `Return` ends the frame on its result, as an instruction's return would.
+ A run that starts with no action set runs as upstream's: the inspector's `step` comes before each instruction, and an action the inspector sets in `step` ends the run after that `step`, as upstream's does.
+ A frame whose action is set when it is built is not handed to `initialize_interp`, and runs no `step` before that action: the action `frame_init` set is the frame's, which no inspector can replace, and the inspector sees the frame's start and end, as it sees a precompile's answer.
+ If that action starts a child and the frame resumes with no action set, the frame runs its code with a `step` before each instruction, never having been handed to `initialize_interp`.
+ An action an inspector sets in `initialize_interp` on any other frame is pending when the run starts, so it is returned the same way, without a `step`; upstream's inspected run calls `step` once before returning it, and returns the action as that `step` left it (see Baseline behaviour the fork changes).
+ One action at a time: `set_action` asserts in a debug build that none is pending, so a consumer sets an action only on a frame that has none.
+- **Consumer.** mega-evm makes some of a frame's actions outside an instruction: the creation and the answer of a system contract's call, and the stop of a frame that a child left over a limit when it returns. They come back through the frame's run, so the loop starts the next frame or ends the frame, and an inspector sees the frame end.
+ Without the check, the plain run executes the frame's code before it returns the action, so mega-evm overrides `frame_run`, and the inspected run shows an inspector a `step` of an instruction that never runs.
+ Without the `initialize_interp` rule, an inspector that halts the frame of a system contract's call there trips `set_action`'s assertion in a debug build, and in a release build replaces the creation mega-evm set with its halt.
+- **Removal.** When upstream's runs check for a pending action before their first instruction and its inspected frame start does not hand a frame with one to `initialize_interp`, or when mega-evm makes no action outside an instruction.
+- **Default.** revm sets no action before a run, so the check finds none, every frame revm builds is handed to `initialize_interp`, and every run is upstream's, callbacks included, for a consumer and an inspector that set none.
+ Where measured (callgrind, the fork's release profile), the check costs about three instructions per frame run on the plain path: 6.03 per `CALL` (+0.23% on a transaction of 64 calls) and 6.12 per nested `CREATE`, which each run two frames (the child, and the caller's resume); 2 or 3 for a transaction whose one frame runs code; nothing for a transfer to an account without code or a precompile's answer, which run no frame. The inspected path, which also reads the action once per new frame before `initialize_interp`, was not measured.
+
+### Frame-run result hook
+
+- **API.** `EvmTr::frame_run_result(&mut self, result: &mut ::FrameResult) -> Result<(), ContextDbError>`, whose default does nothing.
+- **Contract.** The handler loops hand it the result of each frame that ran and returns, once, as the frame's run left it: after `process_next_action` processed the frame's last action (`return_create`'s checks and charges included, for a creation), with the frame still on top of the stack.
+ Whether the frame is marked finished differs by path and frame type, so the hook does not rely on it: revm's `frame_run` marks it before the plain loop calls the hook, the inspected run marks a frame with an `EthFrame` after the inspector's end callbacks, as upstream's does, and a frame without one is marked by its own `frame_run`, before the hook.
+ On the plain path `Handler::run_exec_loop` calls it when `frame_run` returns a result. On the inspected path `InspectorEvmTr::inspect_frame_run` calls it before the inspector's `call_end` or `create_end` and its `frame_end`, and also for a frame without an `EthFrame`, whose run calls no inspector. On both, it runs before `frame_return_result`.
+ What it leaves in `result` is what everything after it sees: the inspector's end callbacks, `frame_return_result` and so the caller, and `last_frame_result` for the transaction's frame. An error it returns ends the transaction as an error of `frame_run` would. It leaves the frame stack as it found it.
+ A frame that returns a pending action (see The pending action) ran, and its result reaches it.
+ A result given without a run does not reach it: `frame_init` returns those (a start the handler refuses, a precompile's answer, an inspector's answer from `frame_start`, `call` or `create`, and an answer of a consumer's own `frame_init`). The consumer's `frame_init` has them first, and an inspector's answer is the inspector's.
+ It is on `EvmTr` because both calls reach it there: the inspected run is a provided method of `InspectorEvmTr`, which extends `EvmTr`, and has the EVM but not the handler.
+ The plain call is in the handler's loop, not in `Evm::frame_run`, and the inspected call is in the provided `inspect_frame_run`. So an EVM type that wraps revm's `Evm`, delegates `frame_run` to it and keeps the provided `inspect_frame_run` has its own `frame_run_result` called on both paths.
+ An override of `run_exec_loop` or of `inspect_frame_run` calls it at the same point itself. An `inspect_frame_run` that delegates to an inner EVM's reaches the inner EVM's `frame_run_result`, not its own, and runs the inner EVM's `frame_end` before the outer type sees the result.
+- **Consumer.** mega-evm decides how a frame that crossed its compute limit ends: its out-of-gas becomes a revert carrying the limit's output, with its gas put back. That has to happen once, before an inspector sees the frame end, on both paths. The plain path could do it in `frame_return_result`, but the inspected run calls `frame_end` before that, so a tracer would see the out-of-gas the caller never gets.
+- **Removal.** When upstream has an equivalent point between a frame's last action and the inspector's end of it, or when mega-evm rewrites no frame's end.
+- **Default.** Does nothing, so every result and every callback is upstream's.
+ Where measured (callgrind, the fork's release profile), the default compiles to nothing on the plain path: the costs measured under The pending action are that check's. The inspected path was not measured.
+
+### Start lifecycle
+
+- **API.**
+ On `Host`, each with a no-op default: `frame_split(&mut self, split: &FrameSplit)`, `frame_settle(&mut self, settle: &FrameSettle, gas: &mut GasTracker)` and `frame_lifecycle_end(&mut self, end: LifecycleEnd)`.
+ `FrameSplit` (`id`, `parent`, `depth`), `FrameSettle` (`id`, `depth`, `status`, `created`, `inspector_answer`, `gas_replaced`, `outcome_rebuilt`, `held_reservoir`), `SettleStatus` (`Ok`, `Revert`, `Halt`) and `LifecycleEnd` (`Settled`, `Discarded`), in `revm_context_interface::host`.
+ `FrameSplit` and `FrameSettle` are `#[non_exhaustive]` and have no public constructor: only the record builds them (`FrameStack::open_start`, `FrameStack::close_start`), so a hook is called by hand only with a value the record made, and a field added later breaks no consumer.
+ `SettleStatus` and `LifecycleEnd` are exhaustive.
+ `revm_handler::lifecycle`: `open_frame_start`, `open_transaction_start`, `Returning` and `close_frame_start`, `close_transaction_start`, `finish_transaction`, `discard_transaction`, `mark_for_end_callbacks` and `check_end_callbacks`.
+ On `FrameStack`, the record: `open_start`, `close_start`, `pending_start`, `running_start`, `lifecycle_active`, `lifecycle_settled`, and its two boundaries `settle_lifecycle` and `discard_lifecycle`.
+ `StartLifecycleError` (`Exhausted`, `Stale`, `NotOpen`, `NoParent`, `Unsettled`; `#[non_exhaustive]`), `PendingStart` (its fields are private: the identity can be read and not written, and only the three flags can be set), `StartMark` and `OutcomeMark`.
+ `GasTracker::start_mark` and `set_start_mark`, and `start_mark` on `CallOutcome` and `CreateOutcome` (a field).
+ `LocalContextTr::lifecycle_mirror`, `LifecycleMirror` and `LifecycleEvent` (`Split`, `Settle`, `End`), the debug mirror (below). The types and the method exist in every profile.
+- **Contract.** A *start* is one frame's beginning with the identity revm gave it; revm pairs every start it opens with exactly one settlement, last in first out, and the consumer does not pair them.
+ *Where revm opens one.*
+ - Where it consumes a `NewFrame` action, so the child's start opens against the frame on top of the stack, its caller, at that frame's depth plus one, which is the init's depth:
+ the plain `Evm::frame_run` opens it as the frame consumes the action, before `process_next_action` builds the init, and `InspectorEvmTr::inspect_frame_run` right after `process_next_action` returns the init.
+ Nothing a consumer can observe happens between the two positions.
+ - Where it makes the transaction's first frame: `Handler::execution` and `InspectorHandler::inspect_execution`.
+ - In the default `Handler::runtime_oog_result`, for the stand-in result of a transaction whose EIP-2780 runtime phase ran out of gas.
+
+ It opens before `EvmTr::frame_init` on the plain path and before `InspectorEvmTr::inspect_frame_init` on the inspected one, and so before an inspector's `frame_start`, `call` and `create`: an answer made in any of them, an inspector's or a consumer's own, settles on a start that is already open.
+ An action an inspector drops or replaces in `step_end` is replaced before revm consumes it, so a start it dropped was never opened, and a clone of the input opens its own.
+ A frame init revm answers without running a frame (a precompile, a start it refuses) opens a start and settles it like any other.
+
+ *Where revm settles one.*
+ - `Evm::frame_return_result`, after `return_result` applied revm's own settlement, closes the returning child's start, held in the slot of the caller on top of the stack (the caller's own start stays open), and calls `frame_settle` with the caller's tracker.
+ - `Handler::last_frame_result`, after `settle_first_frame`, closes the transaction's start and calls `frame_settle` with the transaction's tracker, and after a halt revm consumes the hook's net credit of regular gas and keeps the gas its own settlement left.
+
+ `frame_split` is handed the start's `id`, a per-transaction number revm allocates from 1 with a checked add and never reuses within the transaction; the `parent` identity, the start of the frame that makes this one, `None` for the transaction's frame; the `depth`, read from revm's frame record and never from `interpreter.input`, which an inspector can write; and nothing else: a start's kind, caller, target, value and forward are the frame's own input.
+ Whether the consumer's `frame_init` is handed that input after the split is conditional: when initialisation reaches it, it receives the input as an inspector's `frame_start`, `call` or `create` left it; an inspector that answers the start does so before `frame_init` is called, and the stand-in for a runtime out-of-gas transaction has no init at all, so a start can split and settle with no `frame_init` between.
+ What a consumer charges or keeps for an instruction's start it does at `frame_starting`, before the split; the transaction's start does not pass through `frame_starting`.
+ `frame_settle` is handed the same `id` and `depth` back, and the `status` (`Ok`, `Revert` or `Halt`), `created` (for a creation, whether it took an address), the three flags (below) and `held_reservoir`, the reservoir the caller held before revm settled the child into it.
+
+ *The reservoir.* revm forwards and settles the reservoir as upstream does: the child's input copies the caller's reservoir, or carries the reservoir the frame-start hook named (`FrameStart::reservoir`), and the settlement replaces the caller's reservoir with the one the child returns, once that has unwound the caller's outstanding spill, or as it is when give-backs go to the reservoir alone.
+ A consumer that keeps part of the caller's reservoir for it takes that part in `frame_starting` and names the rest as the child's, and adds `held_reservoir` back to the caller's reservoir in `frame_settle`.
+ The caller then holds what the child returned on top of the part it kept, whatever refills the settlement made, since the unwinding and every refill read the spill and their own amount, never the reservoir.
+ The transaction's frame, and the stand-in for a runtime out-of-gas transaction, are handed a copy of the transaction's reservoir, which the transaction's gas keeps until the settlement replaces it, so there `held_reservoir` is that copy: a consumer adds back only what it kept.
+ `frame_lifecycle_end` is called once at the end of a transaction's lifecycle: `Settled` at the successful boundary, with every start settled, and `Discarded` when a fatal error ends the transaction and the open starts are dropped unsettled.
+ A transaction that ends before any start opened emits neither.
+
+ *The record* is revm's `FrameStack`, which no inspector callback is handed: a per-transaction counter of identities, a slot for the transaction's start and one slot per frame on the stack for the start of the child that frame is making, at most one.
+ A child's parent is the start in the slot of the frame under it, and its depth is one more than its caller's.
+ Both boundaries reset it.
+
+ *The lifecycle helpers.* A handler or an EVM type that replaces a method revm opens or settles in calls the helper that method calls:
+
+ | It overrides or reimplements | It calls |
+ |---|---|
+ | `Handler::execution` or `InspectorHandler::inspect_execution` | `open_frame_start` where it makes the first frame's init |
+ | `Handler::runtime_oog_result`, building its own stand-in | `open_transaction_start` before it returns |
+ | `EvmTr::frame_run` or `InspectorEvmTr::inspect_frame_run` | `open_frame_start` after `process_next_action` returns an init |
+ | `EvmTr::frame_return_result` | `lifecycle::Returning::new(&result, caller)` before `return_result` consumes the result, then `lifecycle::close_frame_start` after it |
+ | `Handler::last_frame_result` | `close_transaction_start` right after `settle_first_frame`, given the reservoir the caller's gas held before the settlement |
+ | `Handler::execution_result` | `finish_transaction`, after the context's recorded error is taken and before the output is built |
+ | `Handler::catch_error` | `discard_transaction`, first |
+
+ `finish_transaction` is the successful boundary (`FrameStack::settle_lifecycle`): with every start settled it emits `LifecycleEnd::Settled` and resets the record.
+ `discard_transaction` is the fatal boundary (`FrameStack::discard_lifecycle`): it emits `Discarded` only if a lifecycle is under way, resets the record, and is idempotent, so a cleanup that runs twice emits once. It resets the lifecycle only; the frame stack is cleared separately (see Reuse after an uncaught error).
+ `close_frame_start` and `close_transaction_start` hand the settlement to `frame_settle` with the caller's tracker and the transaction's, and `close_transaction_start` applies the halt rule after the hook: it consumes only the hook's net regular-gas credit, and a hook that credits nothing or debits leaves the gas as it is.
+ A call sits where the mainnet method makes it and passes what that method passes.
+
+ *Fatal errors.* The record refuses these in every build, debug and release alike, as a `ContextError::Custom` carrying the error's `Display`, which fails the transaction and which `catch_error` reports:
+ - `Stale`: a start opened where one is still open, so a boundary or a settlement was missed;
+ - `NoParent`: a child start under a frame with no start of its own, so a runner drove the transaction's frame without opening its start;
+ - `NotOpen`: a settlement found no start open;
+ - `Exhausted`: the transaction opened 4,294,967,295 starts; the start does not open;
+ - `Unsettled`: `finish_transaction` found a start open. It discards the lifecycle, emits `Discarded` and fails the transaction, so the `catch_error` that reports the error owes no second end.
+
+ The only `debug_assert!`s are on the helpers' own preconditions: the transaction's start opens and closes on an empty frame stack.
+
+ *The marks and the flags.* Before it calls an inspector's end callbacks (`call_end`, `create_end`, `frame_end`) revm writes the start's identity on the result's tracker (`StartMark`, a `u32`, with `GasTracker::set_start_mark`) and a mark of the start on the outcome (`OutcomeMark`, a `u16`, `(id − 1) mod 65535 + 1`, never zero) (`mark_for_end_callbacks`); after them it reads both (`check_end_callbacks`). A consumer has no reason to set a mark.
+ `gas_replaced` is set on the start when the tracker's mark is no longer the start's, `outcome_rebuilt` when the outcome's is not, and `inspector_answer` when `frame_start`, `call` or `create` answered the start.
+ A constructor (`Gas::new`, `CallOutcome::new`, `CreateOutcome::new`) and a literal that names the mark as `Default::default()` leave it zero, so a value built afresh is always seen; a copy of another start's value is seen unless the two identities are a multiple of 65,535 apart, and a copy made in the previous transaction at the same sequence position is not.
+ A tracker an inspector saved before the marking carries none, so restoring it at an end callback sets `gas_replaced` even when it came from the same start.
+ The flags say what an inspector did, never what the consumer did: the consumer's own answers are made in `frame_init`, before any end callback, and are never flagged.
+ Only the inspected path marks and flags; the plain path leaves all three clear.
+ Both marks take no part in equality, hashing, `Debug` or serde: they compare equal always, hash to nothing, are skipped by serde and decode as none, and `GasTracker`, `CallOutcome` and `CreateOutcome` have a hand-written `Debug` that lists the other fields in declaration order, so its output is the derived output without the mark, and `GasTracker`'s encoding has no mark.
+ A change to a field of those three types changes that `Debug` too.
+ An inspector can forge a mark or call a hook by hand through the `&mut` context: a forged mark changes only the flags, and a hand call desynchronises the consumer's own stack from the record without touching the record or its checks; both are outside the contract.
+
+ *Reuse after an uncaught error.* `Handler::run_without_catch_error` skips the cleanup `catch_error` does.
+ A caller that drops its error must do all of it before it reuses the EVM: `discard_transaction`, clearing the local context, discarding the journal (`discard_tx`) and clearing the frame stack.
+ A frame stack left as the error left it makes the next transaction's opening a child under a frame whose start was discarded, and it fails with `NoParent`; a record left open fails the next opening with `Stale`.
+ Calling `catch_error` does all of it.
+
+ *A hand-driven first frame.* A runner that makes and runs the transaction's first frame itself, or settles one it made, opens the transaction's start first (`open_frame_start` with the frame's init, or `open_transaction_start` for a frame it never initialises), then closes it with `last_frame_result` or `close_transaction_start`, and ends the lifecycle with `execution_result` or `finish_transaction`.
+ Without the open, its first child fails with `NoParent` and a direct settlement with `NotOpen`.
+ A test that settles a first frame by hand does the same.
+
+ *The debug mirror.* A debug build keeps, in `LocalContext`, a `LifecycleMirror` of the hooks' order that `Context`'s own hooks feed and that panics when an event does not fit: a root split is at depth 0, a child's parent is the identity on top and its depth one more, a settle pops its own identity and depth, and `Settled` finds the mirror empty. It holds the events as `LifecycleEvent`s (`events()`) and the open starts (`open()`).
+ The type and `LocalContextTr::lifecycle_mirror` exist in every profile, and a consumer's own ledger can be a `LifecycleMirror`; only `LocalContext`'s field and `Context`'s three hook overrides are debug-only, and a release build holds no mirror and calls none.
+ It runs only where a local context returns it from `lifecycle_mirror` (the default returns `None`), and it resets at every root split, so a simulation on a cloned context or an independent EVM nested in an inspector callback checks itself from its own root.
+ A consumer's own ledger follows the same rule: it is initialised at the root split, not at construction or at clone time, and dropped at either end.
+ A context type that wraps `Context` and implements `Host` itself forwards the three hooks to the inner context, or the mirror never runs; the record and its checks run either way.
+- **Consumer.** A consumer that keeps per-start accounting keeps an entry for each start on a stack of its own, drives it only by `frame_split` and `frame_settle`, and ends it at `frame_lifecycle_end`; it does not pair a start with its settlement itself.
+ A consumer that pairs them from the frames it sees breaks when an inspector replaces an interpreter, rewrites an input's depth or drops an action.
+ The flags are what such a consumer needs of an inspector's answers, rewrites and rebuilds to settle them as it would without the inspector.
+ The lifecycle carries no MegaETH figure; what a start's entry holds is the consumer's.
+- **Removal.** When upstream exposes an equivalent pairing of a frame's start with its settlement, or when mega-evm keeps no accounting per start.
+- **Default.** The hooks do nothing and are inlined away, the flags are set on the inspected path and read by no one, and every result and every callback is upstream's.
+ What a consumer that sets nothing pays is revm's own record and the marks, in bytes: the record adds 40 bytes to `FrameStack`, which grows from 40 to 80 bytes per EVM, and a slot of 8 bytes (`PendingStart`) on the heap and reused: the slots are sized with the frame stack's capacity (for zero-sized frames, one per frame that made a child), grown when a child first opens past them and never shrunk: a boundary neither resizes nor frees the slots, a successful end does not scan them, and discarding open children clears the retained slots, at a cost proportional to their retained length.
+ The marks sit in the padding of the values they ride on, so they add nothing to `GasTracker`, `Gas`, `InterpreterResult`, `CallOutcome`, `FrameResult` and `CreateOutcome` (96, 112, 152, 216, 216 and 200 bytes on 64-bit targets with the give-back record), and a release build's `LocalContext` stays 32 bytes; a debug build's is larger for the mirror.
+ In instructions, a start costs a checked increment, a slot write and a parent read, a settlement a slot take, a transaction one reset at each boundary (and, after a discard with open children, one clear of the retained slots), and an inspected frame's end two stores and two compares; the cost per frame, in instructions, is measured separately and not given here.
+ Where measured, the three hooks leave no symbol in an unstripped optimised build; what the loop gains is a call to `FrameStack::open_start`.
+ `Host`, `LocalContextTr` and `FrameStack` gain only default methods and private fields, and `revm_handler` a module, so they break no code written for upstream's.
+ Three exceptions to that compatibility are carried, each an `api:exception` item.
+ A pull request that introduces such an exception lists it and checks the consumers against it.
+ What a consumer does for each:
+ - The outcomes' public `start_mark` field (`CallOutcome` and `CreateOutcome`): a consumer that builds an outcome by literal names it as `start_mark: Default::default()`, or builds it with the constructors. It extends the exception the outcome literals already carry for the state-gas refund's address (see State-gas price).
+ - `LocalContext` gains a private field in a debug build, so a debug build cannot build it with a struct literal; a consumer builds it with `LocalContext::default()` or `new`. A release build's is unchanged.
+ - A behaviour change no compiler finds: a runner that drives the transaction's frame, or settles it, without `Handler::execution` and `Handler::last_frame_result` must open and close the transaction's start (see A hand-driven first frame); otherwise the record refuses it with `NoParent` or `NotOpen`.
+
+### The original account info by reference
+
+- **API.** `revm_state::Account::original_info_ref(&self) -> &AccountInfo`.
+- **Contract.** It returns what `Account::original_info` returns, by reference, cloning nothing: the info the account holds as its original, or the default info for an account whose original was never set.
+- **Consumer.** mega-evm tells whether a transaction changed an account by comparing the account's info with its original, for every frame start, value transfer and destruction it counts. `original_info` returns a copy, and copying the info's code moves the code's reference count up and down; the original is a private field, so only the crate can lend it.
+- **Removal.** When upstream has an equivalent accessor, or when mega-evm stops comparing an account with its original.
+- **Default.** Nothing in this workspace calls it, so every result is upstream's. The default info it lends an account without an original is built on the first such read and kept for the process.
+
## Baseline behaviour the fork changes
Picked upstream fixes change revm 40.0.3's results where 40.0.3 was wrong; that is why they are taken (see Tracking upstream), and each pick's pull request says what it changes.
+Once a consumer spec that runs on the fork is sealed, a pick that changes a result it can reach lands behind a switch that keeps the sealed result, or is not taken (see Tracking upstream).
A pick that changes what the journal records lands with a switch back to the base line (see revm 40.0.3's journal semantics).
-One pick changes what the top-level entry points do with the journal, and has no switch:
+One pick changes what the top-level entry points do with the journal, and has no switch.
+The pending-action check changes what an inspector that sets an action before a frame runs sees and gets, and has no switch either:
- **The journal is finalized on an error.** `ExecuteCommitEvm::transact_commit`, `ExecuteEvm::replay`, `InspectEvm::inspect_tx` and `inspect`, `InspectCommitEvm::inspect_tx_commit` and `inspect_commit`, and the four `inspect_system_call` variants clear the journal when execution returns an error.
revm 40.0.3 left it holding the failed transaction's warm set and touched accounts, which leaked into the next transaction run on the same EVM.
Upstream #3780, carried verbatim with the EIP-8037 / EIP-2780 gas core.
There is no switch: a consumer that must keep the journal after an error uses the entry points that do not finalize (`transact_one`, `inspect_one_tx`, `system_call_one`) and finalizes itself.
+- **An action an inspector sets in `initialize_interp` is returned without a `step`.** The inspected run returns an action pending when it starts before its first `Inspector::step` (see The pending action).
+ Only an inspector that sets an action before a frame runs, by halting the frame or setting its next action in `initialize_interp`, is affected: it loses that run's first `step`, and with it whatever that `step` would have done.
+ revm 40.0.3 called `step` once first, at the frame's first instruction, and then returned the action as that `step` left it, without running the instruction.
+ An inspector whose `step` only observes sees one `step` fewer and gets the same result, since no instruction runs on either.
+ An inspector whose `step` edits the pending action (`LoopControl::action`), or changes the context or the state, gets a different result: the frame returns the action `initialize_interp` set, and the `step`'s changes are not made.
## Tracking upstream
The fork keeps its crate versions at the revm version the MegaETH node pins, today `40.0.3`; a newer upstream tag would bump every crate's major, so the fork takes single upstream commits until the node moves.
Taken: changes to the EIP-8037 / EIP-2780 gas core whatever their prefix; fixes that change execution results (gas, state, logs, halt reasons, precompile output, bytecode analysis, serialized formats); correctness and safety fixes relevant to the consumers, including undefined behaviour, missing out-of-gas checks, panics, and dependency or build failures; performance improvements to execution, precompiles and the database; each with the test-fixture bump that comes with it.
+A change that moves an execution result is taken this way only until the consumer spec that runs on the fork is sealed; after that it follows the sealed-spec rule below, whatever its kind.
Not taken: tooling-only changes, feature-gated additions the consumers do not use, and change/revert pairs, after checking that no taken commit depends on them.
Picks are batched by crate or subsystem, one pull request per batch, so one reviewer can read a whole batch.
The fork has no benchmark gate: a performance pick must leave execution results unchanged under the crate tests and the EEST run, and cite upstream's benchmark numbers in the pull request body.
@@ -227,7 +507,17 @@ A pick that touches a precompile is tested under mutually exclusive feature sets
A pick that breaks the public API needs `api:exception`, the deviating items listed in the pull request body, and a check of every consumer that uses them.
An upstream change that upstream later reverted but the fork still needs lands as a fork-owned opt-in switch (`mega:hook`) whose default keeps upstream's behaviour.
A picked upstream fix that changes journal semantics lands with an opt-in switch back to the base line's behaviour when a consumer reproduces the base line exactly; the switch defaults to the picked behaviour, the consumer that needs the base line sets it, and nothing else reads it. `CfgEnv::legacy_journal_semantics` (the cold-slot re-baseline and the `CodeChange` revert of revm 40.0.3) is the first.
+
+**Sealed specs.** Once a consumer spec that runs on the fork is sealed, the fork must not move that spec's results.
+A pick that changes an execution result the sealed spec can reach then lands behind a switch, or is not taken.
+The switch follows the `legacy_journal_semantics` pattern: it keeps the result the spec was sealed with, its default is the picked behaviour, which is upstream's, and the consumer turns it on for each sealed spec, so a later spec can take the fix by leaving it off.
+A pick that cannot be put behind such a switch is not taken while a sealed spec runs on the fork, and its sweep records why.
+A pick that changes only results no sealed spec reaches, such as a fix to a feature the sealed specs leave off, lands without a switch, and its pull request says why no sealed spec reaches it.
+A pick lands without a switch only with both of these in its pull request: a code-based argument that names the behaviour the pick changes and shows that no sealed spec reaches it, and targeted regression tests for that behaviour.
+The consumer's outcome check on each sealed spec, run against the pick, is supporting evidence and is recorded too; a fixture corpus shows only the cases it reaches, so passing it does not define the pick as safe.
+
Every pick is applied verbatim: `git show -U0 | git patch-id --verbatim` gives the same id for the pick and its upstream commit unless the pick's message records a conflict resolution; the pull request body, which becomes the squash message, lists each pick's `(cherry picked from commit )` line and its conflicts.
+A pick that lands behind a switch keeps the verbatim pick as its own branch commit, followed by the switch in a commit of its own, and the squash message records the switch as the pick's conflict resolution.
For every upstream tag, a maintainer sweeps `..` across the whole repository, fixtures, manifests and lockfile included, and records each commit as taken, candidate (with an owner and a disposition) or excluded (with the reason), with both tag SHAs, in the issue titled `Sweep ` that the nightly workflow opens when the tag appears.
The pull request that carries the picks links that issue; a sweep that takes nothing is closed with its classification in the issue.
@@ -245,7 +535,7 @@ Every pull request carries exactly one `mega:` label and one `api:` label; the `
| Label | Meaning |
|---|---|
| `mega:cherry-pick` | Upstream commits brought into the fork unchanged apart from recorded conflicts |
-| `mega:hook` | A hook or data field added in the thin layer |
+| `mega:hook` | A hook, data field or switch, or an item of rule 2's MegaETH accounting |
| `mega:vendor` | A vendored crate (`crates/op-revm`) added or updated |
| `mega:ci` | Workflows, `scripts/mega`, the fork documents |
| `mega:rebase` | The base line moves to a new upstream tag |
diff --git a/REVIEW.md b/REVIEW.md
index 37bd3d8fa4..9ba1400776 100644
--- a/REVIEW.md
+++ b/REVIEW.md
@@ -9,8 +9,9 @@ It is read by the automated reviewer as well as by people.
1. **Superset.** The public API of every published crate stays a superset of the crates.io baseline recorded in `scripts/mega/crates.txt`.
The `Semver` workflow checks API changes against the pull request base; reviewers check baseline compatibility and the documented exceptions.
A PR that must break the superset carries the `api:exception` label and lists in its body every deviating item with the consumers it was checked against (`reth`, `alloy-evm`, `revm-inspectors`, the `op-revm` fork).
-2. **Thin layer.** The fork adds hooks and data, never MegaETH semantics.
+2. **Hooks and data, and rule 2's set.** The fork adds hooks and data, and no MegaETH semantics beyond the bounded set of accounting `MEGAETH-FORK.md` rule 2 names.
If a change makes a design decision (a price, a limit, a policy), ask for it to move to `mega-evm` and for the fork to expose only the hook it needs.
+ A change that adds to rule 2's set must argue every condition rule 2 lists, the first above all: why a hook on the state revm exposes cannot make the same decision.
3. **`no_std`.** No unguarded `std::`, no new dependency that enables `std` by default, no allocation in a path that did not allocate before.
The CI checks both riscv targets; the reviewer checks the intent.
4. **One topic per PR, conventional prefix on every fork-authored commit.** Fork-authored commits and PR titles start with `feat`, `fix`, `chore`, `docs`, `ci` or `test` and say what changed; cherry-picked commits keep upstream's subject (`MEGAETH-FORK.md` rule 4); `git log --oneline ..main` (`` from `scripts/mega/base.txt`) is the fork's changelog and must stay readable.
@@ -20,8 +21,8 @@ It is read by the automated reviewer as well as by people.
| Label | Look for |
|---|---|
-| `mega:cherry-pick` | The title names the upstream commit (`chore: cherry-pick upstream — `) or, for a batch, the upstream pull requests (`chore: cherry-pick upstream fixes #a #b …`); branch commits keep upstream's subject; a batch stays within one crate or subsystem; a precompile pick reports its tests under mutually exclusive feature sets (the `std`-only fallback run, the default set, all features, and the backend feature it changes); the body links the `Sweep ` issue, lists the `-x` trailers and, for a performance pick, cites the upstream benchmark reference; the diff equals the upstream diff apart from conflicts the message records; nothing MegaETH-specific rides along |
-| `mega:hook` | New logic in new files where practical; upstream files get a `mod` line or a call site; a default implementation keeps existing behaviour byte for byte; a new serialized field carries `serde(default)` so payloads that predate it still decode |
+| `mega:cherry-pick` | The title names the upstream commit (`chore: cherry-pick upstream — `) or, for a batch, the upstream pull requests (`chore: cherry-pick upstream fixes #a #b …`); branch commits keep upstream's subject; a batch stays within one crate or subsystem; a precompile pick reports its tests under mutually exclusive feature sets (the `std`-only fallback run, the default set, all features, and the backend feature it changes); the body links the `Sweep ` issue, lists the `-x` trailers and, for a performance pick, cites the upstream benchmark reference; the diff equals the upstream diff apart from conflicts the message records; nothing MegaETH-specific rides along; once a consumer spec is sealed, a pick that moves a result that spec reaches carries the switch that keeps it, or is not taken, and a pick without a switch carries a code-based argument that no sealed spec reaches the changed behaviour, with targeted regression tests (the consumer's outcome check is supporting evidence) (`MEGAETH-FORK.md`, Tracking upstream) |
+| `mega:hook` | New logic in new files where practical; upstream files get a `mod` line or a call site; a default implementation keeps existing behaviour byte for byte; a new serialized field carries `serde(default)`, so that in a format that carries field names (JSON) payloads that predate it decode with the default; a positional format (bincode) cannot read them whatever the attribute, as `MEGAETH-FORK.md` (Hooks) says |
| `mega:vendor` | The vendored crate keeps its upstream version number and a note of the upstream commit it was taken from; its own tests run in CI |
| `mega:ci` | Workflows pin action SHAs; nothing requires a secret the repository does not have; the local equivalent of every job is documented |
| `mega:rebase` | `scripts/mega/base.txt`, `scripts/mega/crates.txt`, `rust-toolchain.toml` and the baseline table move together; the upstream tag comes in as a merge commit, not a rebase; the merged tree is compared with the new tag and carried picks reconciled; the PR carries `api:exception` for upstream's own API changes |
diff --git a/crates/context/interface/src/cfg.rs b/crates/context/interface/src/cfg.rs
index 9c9effe5e6..dd2ac171d2 100644
--- a/crates/context/interface/src/cfg.rs
+++ b/crates/context/interface/src/cfg.rs
@@ -124,6 +124,14 @@ pub trait Cfg {
fn legacy_journal_semantics(&self) -> bool {
false
}
+
+ /// Returns whether every give-back of state or history gas credits the reservoir alone
+ /// (`GasTracker::reservoir_only_give_backs`), which revm sets on the transaction's gas and on
+ /// every frame's. Default is `false`, EIP-8037's tracker.
+ #[inline]
+ fn reservoir_only_give_backs(&self) -> bool {
+ false
+ }
}
/// What bytecode analysis to perform
@@ -264,5 +272,6 @@ mod tests {
let cfg = RequiredOnly(GasParams::default());
assert!(!cfg.legacy_journal_semantics());
assert!(!cfg.enable_amsterdam_eip7708());
+ assert!(!cfg.reservoir_only_give_backs());
}
}
diff --git a/crates/context/interface/src/cfg/gas.rs b/crates/context/interface/src/cfg/gas.rs
index 8582e8ae8a..c99ee931ea 100644
--- a/crates/context/interface/src/cfg/gas.rs
+++ b/crates/context/interface/src/cfg/gas.rs
@@ -3,9 +3,14 @@
use crate::{cfg::gas_params, cfg::GasParams, Transaction};
use primitives::hardfork::SpecId;
+#[cfg(feature = "serde")]
+mod encoding;
mod failed_charge;
+mod give_backs;
+mod mark;
mod withheld;
+pub use mark::{OutcomeMark, StartMark};
pub use withheld::WithheldCrossing;
/// Tracker for gas during execution.
@@ -38,7 +43,8 @@ pub use withheld::WithheldCrossing;
/// of them lands inside a frame rather than at a frame boundary: `SSTORE`'s refill when it
/// restores a slot to its original zero (0→x→0). A consumer that holds the spendable part at an
/// allowance limits it at a frame's start and again after each credit: when a child returns, and
-/// after `SSTORE`.
+/// after `SSTORE`. With [`reservoir_only_give_backs`](Self::reservoir_only_give_backs) set only the
+/// first of them credits regular gas.
///
/// Releasing the withheld part ([`release_withheld`](Self::release_withheld)) is not needed to
/// conserve gas: the gas a child returns is its [`remaining`](Self::remaining), withheld part
@@ -55,8 +61,37 @@ pub use withheld::WithheldCrossing;
/// checks it. Above it, a rollback no longer restores the reservoir exactly and can burn or mint
/// gas at the boundary. Reaching it takes a transaction gas limit above `i64::MAX`
/// (about 9.2 × 10^18).
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
-#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
+///
+/// With [`reservoir_only_give_backs`](Self::reservoir_only_give_backs) set, which is off by
+/// default, no give-back of state or history gas credits regular gas: a refill, the rollback of a
+/// failed frame and a reservoir a child returns all land in the reservoir, so `remaining` rises
+/// only by the regular gas a child returns. `state_gas_spilled` then counts every part of a state
+/// or history charge that regular gas paid, and no give-back lowers it; a halt reads it to give the
+/// frame back the reservoir it received.
+///
+/// A state charge can take a legacy share from regular gas before it draws the reservoir
+/// ([`record_state_cost_with_legacy_share`](Self::record_state_cost_with_legacy_share)); a share of
+/// zero, the default schedule's for every charge, is [`record_state_cost`](Self::record_state_cost).
+///
+/// Encoded, the tracker has a field per figure, in the order below; the failed-charge record,
+/// a number and a flag in memory, is encoded as an optional number in its place.
+///
+/// A field the fork added decodes with its default from an encoding made before it existed only
+/// in a format that carries field names, such as JSON, as each field says. A format that encodes
+/// a struct by position, such as bincode, cannot read an encoding made before a field was added,
+/// as with upstream's own field additions: it reads the old fields in their places and then
+/// looks for the new ones, so a tracker persisted in such a format must not cross an upgrade of
+/// this crate that adds a field.
+///
+/// The tracker also carries the [`StartMark`] revm writes on a frame result's tracker before an
+/// inspector's end callbacks. The mark is no part of the tracker's value: equality, hashing, the
+/// debug output and the encoding leave it out, and a decoded tracker carries none.
+#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
+#[cfg_attr(
+ feature = "serde",
+ derive(serde::Serialize, serde::Deserialize),
+ serde(from = "encoding::Encoded", into = "encoding::Encoded")
+)]
pub struct GasTracker {
/// Gas Limit,
gas_limit: u64,
@@ -86,6 +121,13 @@ pub struct GasTracker {
/// halt) the spilled portion is credited back to `remaining` in last-in-
/// first-out order by [`Self::rollback_state_gas`]; on success it is
/// propagated to the parent frame so a later parent rollback can return it.
+ ///
+ /// With [`reservoir_only_give_backs`](Self::reservoir_only_give_backs) set it is the state and
+ /// history gas regular gas paid in this frame and in every frame below it that returned to
+ /// it, a legacy share included: no give-back lowers it, and a child adds its own to its
+ /// caller's however it ends. A halt takes the part of it no halt below consumed yet out of the
+ /// reservoir ([`consume_regular_paid_charges`](Self::consume_regular_paid_charges),
+ /// [`halted_regular_paid`](Self::halted_regular_paid)).
state_gas_spilled: u64,
/// Net history gas spent so far.
///
@@ -105,8 +147,8 @@ pub struct GasTracker {
/// `code_deposit_history_gas` a price, so a chain that does not price history bytes behaves
/// exactly as it did before this field existed.
///
- /// Encodings made before this field existed decode it as zero.
- #[cfg_attr(feature = "serde", serde(default))]
+ /// In a format that carries field names, such as JSON, encodings made before this field existed
+ /// decode it as zero.
history_gas_spent: i64,
/// Refunded gas. Used to refund the gas to the caller at the end of execution.
refunded: i64,
@@ -117,8 +159,8 @@ pub struct GasTracker {
/// but never by a regular charge. Zero unless a consumer withholds gas; while it is zero, every
/// method behaves as it did before this field existed.
///
- /// Encodings made before this field existed decode it as zero.
- #[cfg_attr(feature = "serde", serde(default))]
+ /// In a format that carries field names, such as JSON, encodings made before this field existed
+ /// decode it as zero.
withheld: u64,
/// The record of the last failed regular charge the withheld part would have paid
/// ([`withheld_crossing`](Self::withheld_crossing)): the regular gas left before that
@@ -131,14 +173,58 @@ pub struct GasTracker {
/// position, such as bincode, cannot tell the two records apart and reads the old one as the
/// regular gas left, so a record persisted in such a format must not cross an upgrade of this
/// crate.
- #[cfg_attr(feature = "serde", serde(default))]
withheld_crossing: Option,
/// The regular gas left, spendable and withheld parts together, before the last charge that
- /// failed ([`failed_charge_remaining`](Self::failed_charge_remaining)).
+ /// failed ([`failed_charge_remaining`](Self::failed_charge_remaining)), if
+ /// `failed_charge_recorded` is set, and zero otherwise.
+ ///
+ /// In a format that carries field names, such as JSON, encodings made before this field existed
+ /// decode it as `None`.
+ failed_charge_remaining: u64,
+ /// Whether `failed_charge_remaining` holds a record. A flag apart from the record rather than
+ /// an `Option`, whose tag would take a word of its own, so it shares a word with
+ /// `start_mark`.
+ failed_charge_recorded: bool,
+ /// Whether every give-back of state or history gas credits the reservoir alone
+ /// ([`reservoir_only_give_backs`](Self::reservoir_only_give_backs)). A flag that shares the word
+ /// of `failed_charge_recorded` and `start_mark`, so the tracker's size is unchanged.
///
- /// Encodings made before this field existed decode it as `None`.
- #[cfg_attr(feature = "serde", serde(default))]
- failed_charge_remaining: Option,
+ /// In a format that carries field names, such as JSON, encodings made before this field existed
+ /// decode it as `false`.
+ reservoir_only_give_backs: bool,
+ /// With [`reservoir_only_give_backs`](Self::reservoir_only_give_backs) set, the part of
+ /// `state_gas_spilled` that halts already consumed: what frames below this one that halted, or
+ /// that returned to it from frames that halted below them, paid of state and history gas from
+ /// regular gas ([`halted_regular_paid`](Self::halted_regular_paid)). Zero with it off.
+ ///
+ /// In a format that carries field names, such as JSON, encodings made before this field existed
+ /// decode it as zero.
+ halted_regular_paid: u64,
+ /// The start revm marked this tracker for ([`start_mark`](Self::start_mark)). It fits padding
+ /// the tracker already had, in the word `failed_charge_recorded` takes, so the tracker's size
+ /// is unchanged. No part of the tracker's value, and not encoded.
+ start_mark: StartMark,
+}
+
+impl core::fmt::Debug for GasTracker {
+ /// The output the derive gives the tracker's figures, in their order; the mark is left out.
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ f.debug_struct("GasTracker")
+ .field("gas_limit", &self.gas_limit)
+ .field("remaining", &self.remaining)
+ .field("reservoir", &self.reservoir)
+ .field("state_gas_spent", &self.state_gas_spent)
+ .field("state_gas_spilled", &self.state_gas_spilled)
+ .field("history_gas_spent", &self.history_gas_spent)
+ .field("refunded", &self.refunded)
+ .field("withheld", &self.withheld)
+ .field("withheld_crossing", &self.withheld_crossing)
+ .field("failed_charge_remaining", &self.failed_charge_remaining)
+ .field("failed_charge_recorded", &self.failed_charge_recorded)
+ .field("reservoir_only_give_backs", &self.reservoir_only_give_backs)
+ .field("halted_regular_paid", &self.halted_regular_paid)
+ .finish()
+ }
}
impl GasTracker {
@@ -155,10 +241,28 @@ impl GasTracker {
refunded: 0,
withheld: 0,
withheld_crossing: None,
- failed_charge_remaining: None,
+ failed_charge_remaining: 0,
+ failed_charge_recorded: false,
+ reservoir_only_give_backs: false,
+ halted_regular_paid: 0,
+ start_mark: StartMark::NONE,
}
}
+ /// The start revm marked this tracker for before an inspector's end callbacks, or
+ /// [`StartMark::NONE`].
+ #[inline]
+ pub const fn start_mark(&self) -> StartMark {
+ self.start_mark
+ }
+
+ /// Marks this tracker for a start. revm marks a start's result before an inspector's end
+ /// callbacks and reads the mark after them; a consumer has no reason to set it.
+ #[inline]
+ pub const fn set_start_mark(&mut self, mark: StartMark) {
+ self.start_mark = mark;
+ }
+
/// Creates a new `GasTracker` with the given used gas and reservoir.
/// Remaining gas saturates at zero when used gas exceeds the gas limit.
#[inline]
@@ -232,8 +336,16 @@ impl GasTracker {
/// This only reconciles the funding pools. The child's signed
/// `state_gas_spent` has already accounted for the refill and is merged
/// separately by the frame handler.
+ ///
+ /// With [`reservoir_only_give_backs`](Self::reservoir_only_give_backs) set nothing is
+ /// unwound: the returned reservoir becomes this frame's reservoir as it is, and regular gas is
+ /// left as it was.
#[inline]
pub const fn absorb_returned_reservoir(&mut self, reservoir: u64) {
+ if self.reservoir_only_give_backs {
+ self.reservoir = reservoir;
+ return;
+ }
let to_remaining = if reservoir < self.state_gas_spilled {
reservoir
} else {
@@ -415,8 +527,18 @@ impl GasTracker {
/// last-in-first-out order: `remaining` is credited up to `state_gas_spilled`, the rest tops up
/// the reservoir, and the net history gas falls by the full `amount` — below zero when the
/// matching charge was made by a parent frame, which the merge on return reconciles.
+ ///
+ /// With [`reservoir_only_give_backs`](Self::reservoir_only_give_backs) set the whole `amount`
+ /// tops up the reservoir, and `remaining` and `state_gas_spilled` are left as they were.
#[inline]
pub const fn refill_history(&mut self, amount: u64) {
+ if self.reservoir_only_give_backs {
+ self.reservoir = self.reservoir.saturating_add(amount);
+ self.history_gas_spent = self
+ .history_gas_spent
+ .saturating_sub(saturating_signed(amount));
+ return;
+ }
let to_remaining = if amount < self.state_gas_spilled {
amount
} else {
@@ -447,12 +569,26 @@ impl GasTracker {
/// On revert the resulting `remaining` (including the refilled spill) is
/// returned to the parent; on halt the caller additionally zeroes `remaining`
/// so the spilled gas is consumed while the reservoir is left untouched.
+ ///
+ /// With [`reservoir_only_give_backs`](Self::reservoir_only_give_backs) set every charge the
+ /// frame made, net of the give-backs it received, goes into the reservoir, whichever pool
+ /// paid it: the reservoir becomes `reservoir + state_gas_spent + history_gas_spent`, and
+ /// `remaining` and `state_gas_spilled` are left as they were. That is a reverted frame's
+ /// reservoir; a halting frame's caller then consumes the part regular gas paid
+ /// ([`consume_regular_paid_charges`](Self::consume_regular_paid_charges)), which leaves the
+ /// reservoir the frame received.
#[inline]
pub const fn rollback_state_gas(&mut self) {
// The two nets are summed before they meet the reservoir: a frame that took back a parent's
// state charge after its own history charge spilled holds less reservoir than its state
// net is negative, and adding the terms one at a time would clamp at zero part-way.
let charged = self.state_gas_spent.saturating_add(self.history_gas_spent);
+ if self.reservoir_only_give_backs {
+ self.reservoir = self.reservoir.saturating_add_signed(charged);
+ self.state_gas_spent = 0;
+ self.history_gas_spent = 0;
+ return;
+ }
self.reservoir = self
.reservoir
.saturating_add_signed(charged)
@@ -480,8 +616,18 @@ impl GasTracker {
/// (`remaining`) last, the refill credits the pool charged last first:
/// `remaining` is credited up to `state_gas_spilled` and any remainder tops
/// up the reservoir.
+ ///
+ /// With [`reservoir_only_give_backs`](Self::reservoir_only_give_backs) set the whole `amount`
+ /// tops up the reservoir, and `remaining` and `state_gas_spilled` are left as they were.
#[inline]
pub const fn refill_reservoir(&mut self, amount: u64) {
+ if self.reservoir_only_give_backs {
+ self.reservoir = self.reservoir.saturating_add(amount);
+ self.state_gas_spent = self
+ .state_gas_spent
+ .saturating_sub(saturating_signed(amount));
+ return;
+ }
let to_remaining = if amount < self.state_gas_spilled {
amount
} else {
@@ -681,6 +827,25 @@ mod tests {
assert_eq!(parent.reservoir(), 500);
}
+ /// A returned reservoir replaces the caller's, once it has unwound the caller's outstanding
+ /// spill, last in first out: what the caller held beside it does not stay.
+ #[test]
+ fn test_a_returned_reservoir_replaces_the_callers() {
+ // The caller holds the 1,000 it gave the child, which returns 700 of it.
+ let mut caller = GasTracker::new(1_000, 1_000, 1_000);
+ caller.absorb_returned_reservoir(700);
+ assert_eq!((caller.reservoir(), caller.remaining()), (700, 1_000));
+
+ // A spill of 150 outstanding (a successful child's, merged before the absorb): the
+ // returned 100 unwinds 100 of it, and the 20 the caller held goes with the replace.
+ let mut spilled = GasTracker::new(1_000, 850, 20);
+ spilled.add_state_gas_spilled(150);
+ spilled.absorb_returned_reservoir(100);
+ assert_eq!(spilled.reservoir(), 0);
+ assert_eq!(spilled.remaining(), 950);
+ assert_eq!(spilled.state_gas_spilled(), 50);
+ }
+
/// Copying the counter through its getter and setter, as `PrecompileOutput` does for state gas,
/// keeps a negative net.
#[test]
diff --git a/crates/context/interface/src/cfg/gas/encoding.rs b/crates/context/interface/src/cfg/gas/encoding.rs
new file mode 100644
index 0000000000..8108b7f617
--- /dev/null
+++ b/crates/context/interface/src/cfg/gas/encoding.rs
@@ -0,0 +1,143 @@
+//! The encoding of a [`GasTracker`].
+//!
+//! In memory the failed-charge record is a number and a flag, and the flag shares a word with the
+//! tracker's start mark, which is not encoded. Encoded, the tracker keeps the fields, names and
+//! order the derived encoding had: the failed-charge record is an optional number in its place.
+//!
+//! A format that carries field names, such as JSON, decodes an encoding made before a field
+//! existed with the field's default. A format that encodes by position, such as bincode, does not
+//! (see [`GasTracker`]).
+
+use super::{GasTracker, WithheldCrossing};
+
+/// A [`GasTracker`] as it is encoded: its fields in their order, with the defaults an encoding
+/// made before a field existed decodes to in a format that carries field names. Each field of the
+/// tracker documents its own.
+#[derive(serde::Serialize, serde::Deserialize)]
+#[serde(rename = "GasTracker")]
+pub(super) struct Encoded {
+ gas_limit: u64,
+ remaining: u64,
+ reservoir: u64,
+ state_gas_spent: i64,
+ state_gas_spilled: u64,
+ #[serde(default)]
+ history_gas_spent: i64,
+ refunded: i64,
+ #[serde(default)]
+ withheld: u64,
+ #[serde(default)]
+ withheld_crossing: Option,
+ #[serde(default)]
+ failed_charge_remaining: Option,
+ #[serde(default)]
+ reservoir_only_give_backs: bool,
+ #[serde(default)]
+ halted_regular_paid: u64,
+}
+
+impl From for Encoded {
+ fn from(tracker: GasTracker) -> Self {
+ Self {
+ gas_limit: tracker.gas_limit,
+ remaining: tracker.remaining,
+ reservoir: tracker.reservoir,
+ state_gas_spent: tracker.state_gas_spent,
+ state_gas_spilled: tracker.state_gas_spilled,
+ history_gas_spent: tracker.history_gas_spent,
+ refunded: tracker.refunded,
+ withheld: tracker.withheld,
+ withheld_crossing: tracker.withheld_crossing,
+ failed_charge_remaining: tracker.failed_charge_remaining(),
+ reservoir_only_give_backs: tracker.reservoir_only_give_backs,
+ halted_regular_paid: tracker.halted_regular_paid,
+ }
+ }
+}
+
+impl From for GasTracker {
+ fn from(encoded: Encoded) -> Self {
+ let mut tracker = Self {
+ gas_limit: encoded.gas_limit,
+ remaining: encoded.remaining,
+ reservoir: encoded.reservoir,
+ state_gas_spent: encoded.state_gas_spent,
+ state_gas_spilled: encoded.state_gas_spilled,
+ history_gas_spent: encoded.history_gas_spent,
+ refunded: encoded.refunded,
+ withheld: encoded.withheld,
+ withheld_crossing: encoded.withheld_crossing,
+ failed_charge_remaining: 0,
+ failed_charge_recorded: false,
+ reservoir_only_give_backs: encoded.reservoir_only_give_backs,
+ halted_regular_paid: encoded.halted_regular_paid,
+ start_mark: super::StartMark::NONE,
+ };
+ tracker.set_failed_charge_remaining(encoded.failed_charge_remaining);
+ tracker
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::super::GasTracker;
+
+ /// A tracker with every field away from its default: part of its regular gas withheld, a
+ /// crossing and a failed charge recorded, a state charge spilled past the reservoir, a
+ /// refund, give-backs that credit the reservoir alone, and a halted child's count.
+ fn every_field_set() -> GasTracker {
+ let mut tracker = GasTracker::new(1_000, 400, 300);
+ tracker.set_reservoir_only_give_backs(true);
+ let mut halted = GasTracker::new(10, 10, 0);
+ halted.set_reservoir_only_give_backs(true);
+ assert!(halted.record_state_cost(4));
+ halted.rollback_state_gas();
+ halted.consume_regular_paid_charges();
+ tracker.add_regular_paid_of(&halted);
+ tracker.withhold(100);
+ assert!(!tracker.record_regular_cost(350));
+ assert!(tracker.record_state_cost(500));
+ tracker.record_refund(-3);
+ tracker
+ }
+
+ /// The encoding has the fields, the names and the order the derived encoding gave the
+ /// tracker's figures, so a format that encodes by position finds every field in its place; the
+ /// failed-charge record is an optional number.
+ #[test]
+ fn test_the_encoding_keeps_its_fields_and_their_order() {
+ assert_eq!(
+ serde_json::to_string(&every_field_set()).unwrap(),
+ concat!(
+ r#"{"gas_limit":1000,"remaining":200,"reservoir":0,"state_gas_spent":500,"#,
+ r#""state_gas_spilled":204,"history_gas_spent":0,"refunded":-3,"withheld":0,"#,
+ r#""withheld_crossing":{"remaining":400},"failed_charge_remaining":400,"#,
+ r#""reservoir_only_give_backs":true,"halted_regular_paid":4}"#,
+ )
+ );
+ assert_eq!(
+ serde_json::to_string(&GasTracker::new(1_000, 1_000, 0)).unwrap(),
+ concat!(
+ r#"{"gas_limit":1000,"remaining":1000,"reservoir":0,"state_gas_spent":0,"#,
+ r#""state_gas_spilled":0,"history_gas_spent":0,"refunded":0,"withheld":0,"#,
+ r#""withheld_crossing":null,"failed_charge_remaining":null,"#,
+ r#""reservoir_only_give_backs":false,"halted_regular_paid":0}"#,
+ )
+ );
+ }
+
+ /// Every field round-trips, a failed charge of zero apart from none.
+ #[test]
+ fn test_the_encoding_round_trips() {
+ let mut zero_left = GasTracker::new(1_000, 0, 0);
+ assert!(!zero_left.record_regular_cost(1));
+ for tracker in [every_field_set(), zero_left, GasTracker::default()] {
+ let encoded = serde_json::to_string(&tracker).unwrap();
+ assert_eq!(
+ serde_json::from_str::(&encoded).unwrap(),
+ tracker,
+ "{encoded}"
+ );
+ }
+ }
+}
diff --git a/crates/context/interface/src/cfg/gas/failed_charge.rs b/crates/context/interface/src/cfg/gas/failed_charge.rs
index 25a2ae6c3f..5c64f846e6 100644
--- a/crates/context/interface/src/cfg/gas/failed_charge.rs
+++ b/crates/context/interface/src/cfg/gas/failed_charge.rs
@@ -28,7 +28,9 @@ impl GasTracker {
///
/// The interpreter records it too when it halts a frame out of gas with no record there: a
/// cold access the instruction refused before its charge, because the frame could not pay it,
- /// or an out-of-gas a consumer's instruction returned itself. The handler records it where a
+ /// an out-of-gas a consumer's instruction returned itself, or one an instruction hook asked
+ /// for ([`Host::write_completed`](crate::Host::write_completed),
+ /// [`Host::frame_starting`](crate::Host::frame_starting)). The handler records it where a
/// precompile runs out of gas: the frame's whole gas limit, as nothing ran. A consumer that
/// builds an out-of-gas result itself can record the same with
/// [`set_failed_charge_remaining`](Self::set_failed_charge_remaining).
@@ -45,7 +47,11 @@ impl GasTracker {
/// record is left on a creation that returns successfully.
#[inline]
pub const fn failed_charge_remaining(&self) -> Option {
- self.failed_charge_remaining
+ if self.failed_charge_recorded {
+ Some(self.failed_charge_remaining)
+ } else {
+ None
+ }
}
/// Sets the record returned by [`failed_charge_remaining`](Self::failed_charge_remaining),
@@ -57,7 +63,20 @@ impl GasTracker {
/// failure, the record survives [`spend_all`](Self::spend_all).
#[inline]
pub const fn set_failed_charge_remaining(&mut self, remaining: Option) {
+ match remaining {
+ Some(remaining) => self.record_failed_charge(remaining),
+ None => {
+ self.failed_charge_remaining = 0;
+ self.failed_charge_recorded = false;
+ }
+ }
+ }
+
+ /// Records `remaining` as the regular gas left before a failed charge.
+ #[inline]
+ const fn record_failed_charge(&mut self, remaining: u64) {
self.failed_charge_remaining = remaining;
+ self.failed_charge_recorded = true;
}
/// Records a failed regular charge of `cost` against `spendable`: the regular gas left,
@@ -72,7 +91,7 @@ impl GasTracker {
#[inline(never)]
pub(super) const fn regular_charge_failed(&mut self, cost: u64, spendable: u64) {
let remaining = spendable.saturating_add(self.withheld);
- self.failed_charge_remaining = Some(remaining);
+ self.record_failed_charge(remaining);
// `cost > spendable`, so a withheld part that covers the difference is never zero, and
// neither is the regular gas left.
if cost - spendable <= self.withheld {
@@ -92,7 +111,7 @@ impl GasTracker {
#[cold]
#[inline(never)]
pub(super) const fn withheld_first_cost_failed(&mut self) {
- self.failed_charge_remaining = Some(self.remaining.saturating_add(self.withheld));
+ self.record_failed_charge(self.remaining.saturating_add(self.withheld));
}
}
@@ -344,11 +363,11 @@ mod tests {
assert_eq!(tracker.failed_charge_remaining(), None);
}
- /// The record round-trips, a zero included, and encodings made before it existed decode with
- /// none.
+ /// The record round-trips, a zero included, and JSON encodings made before it existed decode
+ /// with none.
#[cfg(feature = "serde")]
#[test]
- fn test_serde_round_trip_and_older_payloads() {
+ fn test_serde_round_trip_and_older_json_payloads() {
for regular in [0, 400] {
let mut tracker = GasTracker::new(1_000, regular, 0);
fail(&mut tracker, regular + 1, false);
diff --git a/crates/context/interface/src/cfg/gas/give_backs.rs b/crates/context/interface/src/cfg/gas/give_backs.rs
new file mode 100644
index 0000000000..325900d523
--- /dev/null
+++ b/crates/context/interface/src/cfg/gas/give_backs.rs
@@ -0,0 +1,376 @@
+//! Give-backs to the reservoir alone, and the legacy share of a state charge.
+//!
+//! The switch that makes every give-back of state or history gas credit a [`GasTracker`]'s
+//! reservoir and never its regular gas, the count of what regular gas paid for state and history
+//! and the part of it halts consumed, and the charge that takes a legacy share from regular gas before the
+//! reservoir. The tracker's own documentation describes how each give-back is credited with the
+//! switch on and off.
+
+use super::GasTracker;
+
+impl GasTracker {
+ /// Whether every give-back of state or history gas credits the reservoir alone. Off by
+ /// default, which is EIP-8037's tracker.
+ ///
+ /// With it on, no give-back credits regular gas, whichever pool paid the charge it gives back:
+ /// a refill ([`refill_reservoir`](Self::refill_reservoir),
+ /// [`refill_history`](Self::refill_history)), a failed frame's rollback
+ /// ([`rollback_state_gas`](Self::rollback_state_gas)) and a reservoir a child returns
+ /// ([`absorb_returned_reservoir`](Self::absorb_returned_reservoir)) land in the reservoir, so a
+ /// frame's `remaining` rises within the frame only by the regular gas a child returns.
+ /// [`state_gas_spilled`](Self::state_gas_spilled) counts what regular gas paid of state and
+ /// history charges in the frame and in the frames below it that returned to it, however they
+ /// ended, and no give-back lowers it. A halt consumes the frame's regular gas and the part of
+ /// its charges regular gas paid, and gives it back the reservoir it received
+ /// ([`consume_regular_paid_charges`](Self::consume_regular_paid_charges)).
+ #[inline]
+ pub const fn reservoir_only_give_backs(&self) -> bool {
+ self.reservoir_only_give_backs
+ }
+
+ /// Sets whether every give-back of state or history gas credits the reservoir alone; see
+ /// [`reservoir_only_give_backs`](Self::reservoir_only_give_backs). revm sets it on the
+ /// transaction's gas and on every frame's from `Cfg::reservoir_only_give_backs`.
+ #[inline]
+ pub const fn set_reservoir_only_give_backs(&mut self, on: bool) {
+ self.reservoir_only_give_backs = on;
+ }
+
+ /// Records a state gas cost that takes a legacy share from regular gas before it draws the
+ /// reservoir.
+ ///
+ /// The share is `min(cost, legacy_share)`: it is drawn from `remaining` first, withheld part
+ /// first ([`record_withheld_first_cost`](Self::record_withheld_first_cost)); the rest of the
+ /// charge is then paid as [`record_state_cost`](Self::record_state_cost) pays it, from the
+ /// reservoir and, past it, from `remaining` again. The share and that spill are one deduction
+ /// from `remaining`, booked on [`state_gas_spilled`](Self::state_gas_spilled), and the whole
+ /// charge is state gas.
+ ///
+ /// Returns `false` if `remaining` cannot pay the share and the spill together, whatever the
+ /// reservoir holds, leaving the tracker's gas untouched and recording the regular gas left
+ /// ([`failed_charge_remaining`](Self::failed_charge_remaining)). A share of zero is
+ /// [`record_state_cost`](Self::record_state_cost).
+ #[inline]
+ #[must_use = "In case of not enough gas, the interpreter should halt with an out-of-gas error"]
+ pub const fn record_state_cost_with_legacy_share(
+ &mut self,
+ cost: u64,
+ legacy_share: u64,
+ ) -> bool {
+ let share = if legacy_share < cost {
+ legacy_share
+ } else {
+ cost
+ };
+ let rest = cost - share;
+ let from_reservoir = if self.reservoir < rest {
+ self.reservoir
+ } else {
+ rest
+ };
+ let from_regular = cost - from_reservoir;
+ if from_regular != 0 && !self.record_withheld_first_cost(from_regular) {
+ return false;
+ }
+ self.reservoir -= from_reservoir;
+ self.state_gas_spent = self
+ .state_gas_spent
+ .saturating_add(super::saturating_signed(cost));
+ self.state_gas_spilled = self.state_gas_spilled.saturating_add(from_regular);
+ true
+ }
+
+ /// The part of [`state_gas_spilled`](Self::state_gas_spilled) that halts below this frame
+ /// already consumed, with [`reservoir_only_give_backs`](Self::reservoir_only_give_backs) set:
+ /// what frames that halted paid of state and history gas from regular gas, which their halts
+ /// took out of the reservoirs they returned. Zero with it off.
+ #[inline]
+ pub const fn halted_regular_paid(&self) -> u64 {
+ self.halted_regular_paid
+ }
+
+ /// Consumes, after [`rollback_state_gas`](Self::rollback_state_gas) of a frame that halts, the
+ /// part of its state and history charges regular gas paid that no halt below it consumed yet:
+ /// the reservoir gives up `state_gas_spilled` less
+ /// [`halted_regular_paid`](Self::halted_regular_paid), so it holds the reservoir the frame
+ /// received, and what regular gas paid is consumed with the regular gas the halt spends. The
+ /// count stays, all of it now consumed, for the caller to add to its own.
+ ///
+ /// The rollback put every charge into the reservoir only with
+ /// [`reservoir_only_give_backs`](Self::reservoir_only_give_backs) set. With it off the rollback
+ /// credited the spill to `remaining` and zeroed it, so there is nothing left to take and this
+ /// changes nothing.
+ #[inline]
+ pub const fn consume_regular_paid_charges(&mut self) {
+ if !self.reservoir_only_give_backs {
+ return;
+ }
+ let unconsumed = self
+ .state_gas_spilled
+ .saturating_sub(self.halted_regular_paid);
+ self.reservoir = self.reservoir.saturating_sub(unconsumed);
+ self.halted_regular_paid = self.state_gas_spilled;
+ }
+
+ /// Adds what a returning `child`'s regular gas paid of state and history gas to this frame's
+ /// count, with the part of it halts consumed, however the child ended
+ /// ([`reservoir_only_give_backs`](Self::reservoir_only_give_backs) set): no give-back lowers
+ /// the count, and a halted child's part is spent like the rest.
+ #[inline]
+ pub const fn add_regular_paid_of(&mut self, child: &GasTracker) {
+ self.state_gas_spilled = self
+ .state_gas_spilled
+ .saturating_add(child.state_gas_spilled);
+ self.halted_regular_paid = self
+ .halted_regular_paid
+ .saturating_add(child.halted_regular_paid);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::GasTracker;
+
+ /// A tracker with `remaining` regular gas and `reservoir`, its give-backs to the reservoir
+ /// alone when `on`.
+ fn tracker(remaining: u64, reservoir: u64, on: bool) -> GasTracker {
+ let mut tracker = GasTracker::new(remaining, remaining, reservoir);
+ tracker.set_reservoir_only_give_backs(on);
+ tracker
+ }
+
+ /// `(remaining, reservoir, state_spent, history_spent, spilled)`.
+ const fn figures(tracker: &GasTracker) -> (u64, u64, i64, i64, u64) {
+ (
+ tracker.remaining(),
+ tracker.reservoir(),
+ tracker.state_gas_spent(),
+ tracker.history_gas_spent(),
+ tracker.state_gas_spilled(),
+ )
+ }
+
+ /// The switch is off on every tracker built, and is no part of a tracker that has it off.
+ #[test]
+ fn test_the_switch_is_off_by_default() {
+ assert!(!GasTracker::new(1_000, 1_000, 0).reservoir_only_give_backs());
+ assert!(!GasTracker::default().reservoir_only_give_backs());
+ let mut on = GasTracker::default();
+ on.set_reservoir_only_give_backs(true);
+ assert!(on.reservoir_only_give_backs());
+ assert_ne!(
+ on,
+ GasTracker::default(),
+ "the switch is part of the tracker's value"
+ );
+ }
+
+ /// A refill of state gas regular gas paid credits regular gas first with the switch off, and
+ /// the reservoir alone with it on, the spill count standing.
+ #[test]
+ fn test_a_state_refill_credits_the_reservoir_alone_with_the_switch_on() {
+ for on in [false, true] {
+ let mut gas = tracker(1_000, 100, on);
+ assert!(gas.record_state_cost(300));
+ assert_eq!(figures(&gas), (800, 0, 300, 0, 200));
+ gas.refill_reservoir(300);
+ let expected = if on {
+ (800, 300, 0, 0, 200)
+ } else {
+ (1_000, 100, 0, 0, 0)
+ };
+ assert_eq!(figures(&gas), expected, "switch on: {on}");
+ }
+ }
+
+ /// A refill of history gas follows the same rule as a refill of state gas.
+ #[test]
+ fn test_a_history_refill_credits_the_reservoir_alone_with_the_switch_on() {
+ for on in [false, true] {
+ let mut gas = tracker(1_000, 100, on);
+ assert!(gas.record_history_cost(300));
+ gas.refill_history(300);
+ let expected = if on {
+ (800, 300, 0, 0, 200)
+ } else {
+ (1_000, 100, 0, 0, 0)
+ };
+ assert_eq!(figures(&gas), expected, "switch on: {on}");
+ }
+ }
+
+ /// A reservoir a child returns unwinds the caller's spill with the switch off, and becomes the
+ /// caller's reservoir as it is with it on.
+ #[test]
+ fn test_a_returned_reservoir_unwinds_nothing_with_the_switch_on() {
+ for on in [false, true] {
+ let mut gas = tracker(1_000, 0, on);
+ assert!(gas.record_state_cost(300));
+ gas.absorb_returned_reservoir(500);
+ let expected = if on {
+ (700, 500, 300, 0, 300)
+ } else {
+ (1_000, 200, 300, 0, 0)
+ };
+ assert_eq!(figures(&gas), expected, "switch on: {on}");
+ }
+ }
+
+ /// With the switch on a revert puts every charge the frame made, net of what it was given
+ /// back, into the reservoir, whichever pool paid it, and keeps the count of what regular gas
+ /// paid; regular gas is left as it was. With it off the spill goes back to regular gas.
+ #[test]
+ fn test_a_rollback_puts_every_charge_into_the_reservoir_with_the_switch_on() {
+ for on in [false, true] {
+ let mut gas = tracker(1_000, 100, on);
+ assert!(gas.record_state_cost(300));
+ assert!(gas.record_history_cost(50));
+ gas.refill_reservoir(20);
+ gas.rollback_state_gas();
+ let expected = if on {
+ // 100 − 100 − 0 + 20 (refill) + 330 (net) = 350 of reservoir; 750 regular left.
+ (750, 350, 0, 0, 250)
+ } else {
+ (1_000, 100, 0, 0, 0)
+ };
+ assert_eq!(figures(&gas), expected, "switch on: {on}");
+ }
+ }
+
+ /// After a halting frame's rollback, consuming what regular gas paid leaves the reservoir the
+ /// frame received with the switch on, and keeps the count, all of it now consumed, for the
+ /// caller; with it off it changes nothing, where the rollback already credited the spill to
+ /// regular gas and zeroed it.
+ #[test]
+ fn test_a_halt_gives_back_the_reservoir_the_frame_received() {
+ for on in [false, true] {
+ let mut gas = tracker(1_000, 100, on);
+ assert!(gas.record_state_cost(300));
+ assert!(gas.record_history_cost(50));
+ gas.refill_reservoir(300);
+ assert!(gas.record_state_cost_with_legacy_share(200, 80));
+ gas.rollback_state_gas();
+ gas.consume_regular_paid_charges();
+ gas.spend_all();
+ assert_eq!(gas.reservoir(), 100, "switch on: {on}");
+ // Regular gas paid 200 and 50 past the reservoir, then the share of 80.
+ let paid = if on { 330 } else { 0 };
+ assert_eq!(gas.state_gas_spilled(), paid, "switch on: {on}");
+ assert_eq!(gas.halted_regular_paid(), paid, "switch on: {on}");
+ assert_eq!(gas.remaining(), 0, "switch on: {on}");
+ }
+ }
+
+ /// A halt consumes only what no halt below it consumed: a frame whose child halted adds the
+ /// child's count with the record that the child's halt consumed it, so its own halt leaves the
+ /// reservoir it received rather than taking the child's part out a second time.
+ #[test]
+ fn test_a_halt_after_a_halted_child_consumes_the_childs_part_once() {
+ let mut parent = tracker(10_000, 500, true);
+ // 500 from the reservoir, 200 from regular gas.
+ assert!(parent.record_state_cost(700));
+ let mut child = tracker(1_000, 0, true);
+ assert!(child.record_state_cost(40));
+ child.rollback_state_gas();
+ child.consume_regular_paid_charges();
+ child.spend_all();
+ assert_eq!(
+ (
+ child.reservoir(),
+ child.state_gas_spilled(),
+ child.halted_regular_paid()
+ ),
+ (0, 40, 40)
+ );
+
+ parent.add_regular_paid_of(&child);
+ assert_eq!(
+ (parent.state_gas_spilled(), parent.halted_regular_paid()),
+ (240, 40)
+ );
+ parent.rollback_state_gas();
+ parent.consume_regular_paid_charges();
+ assert_eq!(parent.reservoir(), 500, "the reservoir the parent received");
+ assert_eq!(
+ (parent.state_gas_spilled(), parent.halted_regular_paid()),
+ (240, 240)
+ );
+ }
+
+ /// A legacy share is paid from regular gas before the reservoir, which pays the rest; the
+ /// regular part is counted as paid by regular gas, and the whole charge is state gas.
+ #[test]
+ fn test_a_legacy_share_comes_from_regular_gas_before_the_reservoir() {
+ let mut gas = tracker(1_000, 500, true);
+ assert!(gas.record_state_cost_with_legacy_share(300, 100));
+ assert_eq!(figures(&gas), (900, 300, 300, 0, 100));
+
+ // The share is capped at the charge.
+ let mut gas = tracker(1_000, 500, true);
+ assert!(gas.record_state_cost_with_legacy_share(60, 100));
+ assert_eq!(figures(&gas), (940, 500, 60, 0, 60));
+
+ // What the reservoir cannot pay after the share spills onto regular gas too.
+ let mut gas = tracker(1_000, 150, true);
+ assert!(gas.record_state_cost_with_legacy_share(300, 100));
+ assert_eq!(figures(&gas), (850, 0, 300, 0, 150));
+ }
+
+ /// A share regular gas cannot pay is an out-of-gas whatever the reservoir holds, and leaves the
+ /// tracker's gas untouched with the failure recorded; so is a share and a spill it cannot pay
+ /// together.
+ #[test]
+ fn test_a_legacy_share_regular_gas_cannot_pay_runs_out_of_gas() {
+ let mut gas = tracker(99, 1_000, true);
+ let before = figures(&gas);
+ assert!(!gas.record_state_cost_with_legacy_share(300, 100));
+ assert_eq!(figures(&gas), before);
+ assert_eq!(gas.failed_charge_remaining(), Some(99));
+
+ let mut gas = tracker(149, 150, true);
+ assert!(!gas.record_state_cost_with_legacy_share(300, 100));
+ assert_eq!(gas.failed_charge_remaining(), Some(149));
+ }
+
+ /// The share draws the withheld part first, as a spill does.
+ #[test]
+ fn test_a_legacy_share_draws_the_withheld_part_first() {
+ let mut gas = tracker(1_000, 500, true);
+ gas.withhold(300);
+ assert!(gas.record_state_cost_with_legacy_share(300, 100));
+ assert_eq!(gas.withheld(), 200);
+ assert_eq!(gas.spendable(), 700);
+ }
+
+ /// A share of zero is the charge EIP-8037 makes, with the switch on or off.
+ #[test]
+ fn test_a_legacy_share_of_zero_is_the_plain_state_charge() {
+ for on in [false, true] {
+ for (remaining, reservoir, cost) in
+ [(1_000, 500, 300), (1_000, 100, 300), (200, 50, 300)]
+ {
+ let mut plain = tracker(remaining, reservoir, on);
+ let mut shared = plain;
+ assert_eq!(
+ plain.record_state_cost(cost),
+ shared.record_state_cost_with_legacy_share(cost, 0)
+ );
+ assert_eq!(plain, shared, "{remaining} {reservoir} {cost} {on}");
+ }
+ }
+ }
+
+ /// A give-back never lowers the count of what regular gas paid with the switch on, so a frame
+ /// that paid a slot from regular gas and wrote it back still counts what it paid.
+ #[test]
+ fn test_no_give_back_lowers_the_count_of_what_regular_gas_paid() {
+ let mut gas = tracker(1_000, 0, true);
+ assert!(gas.record_state_cost_with_legacy_share(300, 100));
+ assert!(gas.record_history_cost(40));
+ gas.refill_reservoir(300);
+ gas.refill_history(40);
+ gas.absorb_returned_reservoir(500);
+ assert_eq!(gas.state_gas_spilled(), 340);
+ assert_eq!(gas.remaining(), 660);
+ }
+}
diff --git a/crates/context/interface/src/cfg/gas/mark.rs b/crates/context/interface/src/cfg/gas/mark.rs
new file mode 100644
index 0000000000..e5025fba69
--- /dev/null
+++ b/crates/context/interface/src/cfg/gas/mark.rs
@@ -0,0 +1,129 @@
+//! The marks revm writes on a frame's result just before an inspector's end callbacks, and reads
+//! just after, to tell whether the callbacks put another value in the result's place: the
+//! [`StartMark`] on the result's gas tracker and the [`OutcomeMark`] on its outcome.
+//!
+//! A mark takes no part in the value it rides on: marks always compare equal and hash to nothing,
+//! and the tracker and the outcomes leave them out of their debug output and their encoding (a
+//! decoded value carries none). So a marked tracker or outcome compares, hashes, prints and encodes
+//! as the same value unmarked. Each fits padding of the type that carries it, so neither grows.
+
+/// The mark of a start on a gas tracker: the start's identity, or none.
+///
+/// revm marks the tracker of a start's result for the start before an inspector's end callbacks;
+/// a tracker that does not carry the mark after them is one the callbacks put in its place
+/// ([`FrameSettle::gas_replaced`](crate::host::FrameSettle::gas_replaced)). A copy of the
+/// tracker carries the mark with it.
+#[derive(Clone, Copy, Default)]
+pub struct StartMark(u32);
+
+impl StartMark {
+ /// No mark, as every tracker is built.
+ pub const NONE: Self = Self(0);
+
+ /// The mark of the start `id`.
+ #[inline]
+ pub const fn for_start(id: u32) -> Self {
+ Self(id)
+ }
+
+ /// Whether this is the mark of the start `id`.
+ #[inline]
+ pub const fn is_for(self, id: u32) -> bool {
+ self.0 != 0 && self.0 == id
+ }
+}
+
+/// The mark of a start on a call's or creation's outcome: 16 bits of the start's identity, or
+/// none.
+///
+/// revm marks the outcome of a start's result for the start before an inspector's end callbacks;
+/// an outcome that does not carry the mark after them is one the callbacks put in its place
+/// ([`FrameSettle::outcome_rebuilt`](crate::host::FrameSettle::outcome_rebuilt)), such as one a
+/// constructor built around the same result. A start's mark is never none, so a built outcome
+/// never carries it; two starts share a mark only when their identities are a multiple of 65,535
+/// apart.
+#[derive(Clone, Copy, Default)]
+pub struct OutcomeMark(u16);
+
+impl OutcomeMark {
+ /// No mark, as every constructor builds an outcome.
+ pub const NONE: Self = Self(0);
+
+ /// The mark of the start `id`: `(id - 1) % 65535 + 1`, never none.
+ #[inline]
+ pub const fn for_start(id: u32) -> Self {
+ Self((id.wrapping_sub(1) % 65535 + 1) as u16)
+ }
+
+ /// Whether this is the mark of the start `id`.
+ #[inline]
+ pub const fn is_for(self, id: u32) -> bool {
+ self.0 == Self::for_start(id).0
+ }
+}
+
+macro_rules! transparent_mark {
+ ($mark:ident) => {
+ impl PartialEq for $mark {
+ #[inline]
+ fn eq(&self, _: &Self) -> bool {
+ true
+ }
+ }
+
+ impl Eq for $mark {}
+
+ impl core::hash::Hash for $mark {
+ #[inline]
+ fn hash(&self, _: &mut H) {}
+ }
+
+ impl core::fmt::Debug for $mark {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ f.write_str(stringify!($mark))
+ }
+ }
+ };
+}
+
+transparent_mark!(StartMark);
+transparent_mark!(OutcomeMark);
+
+#[cfg(test)]
+mod tests {
+ use super::{OutcomeMark, StartMark};
+
+ #[test]
+ fn test_a_start_mark_names_its_start_only() {
+ let mark = StartMark::for_start(7);
+ assert!(mark.is_for(7));
+ assert!(!mark.is_for(8));
+ assert!(!StartMark::NONE.is_for(0), "no mark names no start");
+ }
+
+ /// The outcome's mark is never none for a start, and two starts share one only 65,535
+ /// identities apart.
+ #[test]
+ fn test_an_outcome_mark_is_never_none_and_repeats_every_65535_starts() {
+ for id in [
+ 1u32,
+ 2,
+ 65_534,
+ 65_535,
+ 65_536,
+ 65_537,
+ 131_070,
+ 131_071,
+ u32::MAX - 1,
+ u32::MAX,
+ ] {
+ assert!(!OutcomeMark::NONE.is_for(id), "id {id} has no mark");
+ assert!(OutcomeMark::for_start(id).is_for(id), "id {id}");
+ if id > 1 {
+ assert!(!OutcomeMark::for_start(id).is_for(id - 1), "id {id}");
+ }
+ }
+ assert!(OutcomeMark::for_start(1).is_for(65_536));
+ assert!(!OutcomeMark::for_start(1).is_for(65_535));
+ }
+}
diff --git a/crates/context/interface/src/cfg/gas/withheld.rs b/crates/context/interface/src/cfg/gas/withheld.rs
index 875eef9769..b7373e0359 100644
--- a/crates/context/interface/src/cfg/gas/withheld.rs
+++ b/crates/context/interface/src/cfg/gas/withheld.rs
@@ -236,12 +236,14 @@ mod tests {
assert_eq!(size_of::