revm_context_interface/cfg/gas.rs
1//! Gas constants and functions for gas calculation.
2
3use crate::{cfg::gas_params, cfg::GasParams, Transaction};
4use primitives::hardfork::SpecId;
5
6/// Tracker for gas during execution.
7///
8/// This is used to track the gas during execution.
9#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
10#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
11pub struct GasTracker {
12 /// Gas Limit,
13 gas_limit: u64,
14 /// Regular gas remaining (`gas_left`). Reservoir is tracked separately.
15 remaining: u64,
16 /// State gas reservoir (gas exceeding TX_MAX_GAS_LIMIT). Starts as `execution_gas - min(execution_gas, regular_gas_budget)`.
17 /// When 0, all remaining gas is regular gas with hard cap at `TX_MAX_GAS_LIMIT`.
18 reservoir: u64,
19 /// Net state gas spent so far.
20 ///
21 /// Can be negative within a call frame when 0→x→0 storage restoration refills
22 /// more state gas than the frame itself has charged (the parent previously
23 /// charged the 0→x portion). The net is reconciled on frame return.
24 state_gas_spent: i64,
25 /// State gas drawn from regular gas (`remaining`) because the reservoir was
26 /// empty (EIP-8037's `state_gas_from_gas_left`).
27 ///
28 /// Incremented by [`Self::record_state_cost`] whenever a state-gas charge
29 /// spills out of the reservoir into regular gas. On frame rollback (revert or
30 /// halt) the spilled portion is credited back to `remaining` in last-in-
31 /// first-out order by [`Self::rollback_state_gas`]; on success it is
32 /// propagated to the parent frame so a later parent rollback can return it.
33 state_gas_spilled: u64,
34 /// Refunded gas. Used to refund the gas to the caller at the end of execution.
35 refunded: i64,
36}
37
38impl GasTracker {
39 /// Creates a new `GasTracker` with the given remaining gas and reservoir.
40 #[inline]
41 pub const fn new(gas_limit: u64, remaining: u64, reservoir: u64) -> Self {
42 Self {
43 gas_limit,
44 remaining,
45 reservoir,
46 state_gas_spent: 0,
47 state_gas_spilled: 0,
48 refunded: 0,
49 }
50 }
51
52 /// Creates a new `GasTracker` with the given used gas and reservoir.
53 #[inline]
54 pub const fn new_used_gas(gas_limit: u64, used_gas: u64, reservoir: u64) -> Self {
55 Self::new(gas_limit, gas_limit - used_gas, reservoir)
56 }
57
58 /// Returns the gas limit.
59 #[inline]
60 pub const fn limit(&self) -> u64 {
61 self.gas_limit
62 }
63
64 /// Sets the gas limit.
65 #[inline]
66 pub const fn set_limit(&mut self, val: u64) {
67 self.gas_limit = val;
68 }
69
70 /// Returns the remaining gas.
71 #[inline]
72 pub const fn remaining(&self) -> u64 {
73 self.remaining
74 }
75
76 /// Sets the remaining gas.
77 #[inline]
78 pub const fn set_remaining(&mut self, val: u64) {
79 self.remaining = val;
80 }
81
82 /// Returns the reservoir gas.
83 #[inline]
84 pub const fn reservoir(&self) -> u64 {
85 self.reservoir
86 }
87
88 /// Sets the reservoir gas.
89 #[inline]
90 pub const fn set_reservoir(&mut self, val: u64) {
91 self.reservoir = val;
92 }
93
94 /// Returns the state gas spent.
95 #[inline]
96 pub const fn state_gas_spent(&self) -> i64 {
97 self.state_gas_spent
98 }
99
100 /// Sets the state gas spent.
101 #[inline]
102 pub const fn set_state_gas_spent(&mut self, val: i64) {
103 self.state_gas_spent = val;
104 }
105
106 /// Returns the state gas drawn from regular gas (`remaining`) because the
107 /// reservoir was empty (EIP-8037's `state_gas_from_gas_left`).
108 #[inline]
109 pub const fn state_gas_spilled(&self) -> u64 {
110 self.state_gas_spilled
111 }
112
113 /// Sets the spilled state gas.
114 #[inline]
115 pub const fn set_state_gas_spilled(&mut self, val: u64) {
116 self.state_gas_spilled = val;
117 }
118
119 /// Adds `delta` to the spilled state gas, saturating.
120 ///
121 /// Used to merge a successful child frame's spilled state gas into this
122 /// (parent) frame so a later parent rollback can return it.
123 #[inline]
124 pub const fn add_state_gas_spilled(&mut self, delta: u64) {
125 self.state_gas_spilled = self.state_gas_spilled.saturating_add(delta);
126 }
127
128 /// Returns the refunded gas.
129 #[inline]
130 pub const fn refunded(&self) -> i64 {
131 self.refunded
132 }
133
134 /// Sets the refunded gas.
135 #[inline]
136 pub const fn set_refunded(&mut self, val: i64) {
137 self.refunded = val;
138 }
139
140 /// Records a regular gas cost.
141 ///
142 /// Deducts from `remaining`. Returns `false` if insufficient gas.
143 #[inline]
144 #[must_use = "In case of not enough gas, the interpreter should halt with an out-of-gas error"]
145 pub const fn record_regular_cost(&mut self, cost: u64) -> bool {
146 if let Some(new_remaining) = self.remaining.checked_sub(cost) {
147 self.remaining = new_remaining;
148 return true;
149 }
150 false
151 }
152
153 /// Records a state gas cost (EIP-8037 reservoir model).
154 ///
155 /// State gas charges deduct from the reservoir first. If the reservoir is exhausted,
156 /// remaining charges spill into `remaining` (requiring `remaining >= cost`).
157 /// Tracks state gas spent.
158 ///
159 /// Returns `false` if total remaining gas is insufficient.
160 #[inline]
161 #[must_use = "In case of not enough gas, the interpreter should halt with an out-of-gas error"]
162 pub const fn record_state_cost(&mut self, cost: u64) -> bool {
163 if self.reservoir >= cost {
164 self.state_gas_spent = self.state_gas_spent.saturating_add(cost as i64);
165 self.reservoir -= cost;
166 return true;
167 }
168
169 let spill = cost - self.reservoir;
170
171 let success = self.record_regular_cost(spill);
172 if success {
173 self.state_gas_spent = self.state_gas_spent.saturating_add(cost as i64);
174 self.state_gas_spilled = self.state_gas_spilled.saturating_add(spill);
175 self.reservoir = 0;
176 }
177 success
178 }
179
180 /// Rolls back this frame's state-gas charges on revert or exceptional halt
181 /// (EIP-8037).
182 ///
183 /// The state gas charged within the frame is refilled in last-in-first-out
184 /// order: the spilled portion is credited back to `remaining` (the pool
185 /// charged last) and the rest restores the reservoir to its frame-start
186 /// value. Concretely, `remaining` gains `state_gas_spilled` and the reservoir
187 /// becomes `reservoir + state_gas_spent - state_gas_spilled`, which is exactly
188 /// the reservoir the frame inherited. Both state-gas counters are then reset.
189 ///
190 /// On revert the resulting `remaining` (including the refilled spill) is
191 /// returned to the parent; on halt the caller additionally zeroes `remaining`
192 /// so the spilled gas is consumed while the reservoir is left untouched.
193 #[inline]
194 pub const fn rollback_state_gas(&mut self) {
195 self.reservoir = self
196 .reservoir
197 .saturating_add_signed(self.state_gas_spent)
198 .saturating_sub(self.state_gas_spilled);
199 self.remaining = self.remaining.saturating_add(self.state_gas_spilled);
200 self.state_gas_spent = 0;
201 self.state_gas_spilled = 0;
202 }
203
204 /// Refills the reservoir with state gas that is returned by 0→x→0 storage
205 /// restoration (EIP-8037 issue #2).
206 ///
207 /// Per the spec, when a storage slot is restored to its original zero value
208 /// within the same transaction, the state gas charged for the initial 0→x
209 /// transition is directly restored to the reservoir rather than routed
210 /// through the capped refund counter.
211 ///
212 /// `state_gas_spent` is decremented by the full `amount` and may become
213 /// negative if the matching 0→x charge was made by a parent frame (so this
214 /// frame's `state_gas_spilled` is zero and the whole refill lands in the
215 /// reservoir); the parent's total is reconciled on frame return.
216 ///
217 /// Because charges deduct from the reservoir first and from regular gas
218 /// (`remaining`) last, the refill credits the pool charged last first:
219 /// `remaining` is credited up to `state_gas_spilled` and any remainder tops
220 /// up the reservoir.
221 #[inline]
222 pub const fn refill_reservoir(&mut self, amount: u64) {
223 let to_remaining = if amount < self.state_gas_spilled {
224 amount
225 } else {
226 self.state_gas_spilled
227 };
228 self.remaining = self.remaining.saturating_add(to_remaining);
229 self.state_gas_spilled -= to_remaining;
230 self.reservoir = self.reservoir.saturating_add(amount - to_remaining);
231 self.state_gas_spent = self.state_gas_spent.saturating_sub(amount as i64);
232 }
233
234 /// Records a refund value.
235 #[inline]
236 pub const fn record_refund(&mut self, refund: i64) {
237 self.refunded += refund;
238 }
239
240 /// Erases a gas cost from remaining (returns gas from child frame).
241 #[inline]
242 pub const fn erase_cost(&mut self, returned: u64) {
243 self.remaining += returned;
244 }
245
246 /// Spends all remaining gas excluding the reservoir.
247 #[inline]
248 pub const fn spend_all(&mut self) {
249 self.remaining = 0;
250 }
251}
252
253/// Gas cost for operations that consume zero gas.
254pub const ZERO: u64 = 0;
255/// Base gas cost for basic operations.
256pub const BASE: u64 = 2;
257
258/// Gas cost for very low-cost operations.
259pub const VERYLOW: u64 = 3;
260/// Gas cost for DATALOADN instruction.
261pub const DATA_LOADN_GAS: u64 = 3;
262
263/// Gas cost for conditional jump instructions.
264pub const CONDITION_JUMP_GAS: u64 = 4;
265/// Gas cost for RETF instruction.
266pub const RETF_GAS: u64 = 3;
267/// Gas cost for DATALOAD instruction.
268pub const DATA_LOAD_GAS: u64 = 4;
269
270/// Gas cost for low-cost operations.
271pub const LOW: u64 = 5;
272/// Gas cost for medium-cost operations.
273pub const MID: u64 = 8;
274/// Gas cost for high-cost operations.
275pub const HIGH: u64 = 10;
276/// Gas cost for JUMPDEST instruction.
277pub const JUMPDEST: u64 = 1;
278/// Gas cost for REFUND SELFDESTRUCT instruction.
279pub const SELFDESTRUCT_REFUND: i64 = 24000;
280/// Gas cost for CREATE instruction.
281pub const CREATE: u64 = 32000;
282/// Additional gas cost when a call transfers value.
283pub const CALLVALUE: u64 = 9000;
284/// Gas cost for creating a new account.
285pub const NEWACCOUNT: u64 = 25000;
286/// Base gas cost for EXP instruction.
287pub const EXP: u64 = 10;
288/// Gas cost per word for memory operations.
289pub const MEMORY: u64 = 3;
290/// Base gas cost for LOG instructions.
291pub const LOG: u64 = 375;
292/// Gas cost per byte of data in LOG instructions.
293pub const LOGDATA: u64 = 8;
294/// Gas cost per topic in LOG instructions.
295pub const LOGTOPIC: u64 = 375;
296/// Base gas cost for KECCAK256 instruction.
297pub const KECCAK256: u64 = 30;
298/// Gas cost per word for KECCAK256 instruction.
299pub const KECCAK256WORD: u64 = 6;
300/// Gas cost per word for copy operations.
301pub const COPY: u64 = 3;
302/// Gas cost for BLOCKHASH instruction.
303pub const BLOCKHASH: u64 = 20;
304/// Gas cost per byte for code deposit during contract creation.
305pub const CODEDEPOSIT: u64 = 200;
306
307/// EIP-1884: Repricing for trie-size-dependent opcodes
308pub const ISTANBUL_SLOAD_GAS: u64 = 800;
309/// Gas cost for SSTORE when setting a storage slot from zero to non-zero.
310pub const SSTORE_SET: u64 = 20000;
311/// Gas cost for SSTORE when modifying an existing non-zero storage slot.
312pub const SSTORE_RESET: u64 = 5000;
313/// Gas refund for SSTORE when clearing a storage slot (setting to zero).
314pub const REFUND_SSTORE_CLEARS: i64 = 15000;
315
316/// The standard cost of calldata token.
317pub const STANDARD_TOKEN_COST: u64 = 4;
318/// The cost of a non-zero byte in calldata.
319pub const NON_ZERO_BYTE_DATA_COST: u64 = 68;
320/// The multiplier for a non zero byte in calldata.
321pub const NON_ZERO_BYTE_MULTIPLIER: u64 = NON_ZERO_BYTE_DATA_COST / STANDARD_TOKEN_COST;
322/// The cost of a non-zero byte in calldata adjusted by [EIP-2028](https://eips.ethereum.org/EIPS/eip-2028).
323pub const NON_ZERO_BYTE_DATA_COST_ISTANBUL: u64 = 16;
324/// The multiplier for a non zero byte in calldata adjusted by [EIP-2028](https://eips.ethereum.org/EIPS/eip-2028).
325pub const NON_ZERO_BYTE_MULTIPLIER_ISTANBUL: u64 =
326 NON_ZERO_BYTE_DATA_COST_ISTANBUL / STANDARD_TOKEN_COST;
327/// The cost floor per token as defined by [EIP-7623](https://eips.ethereum.org/EIPS/eip-7623).
328pub const TOTAL_COST_FLOOR_PER_TOKEN: u64 = 10;
329
330/// Gas cost for EOF CREATE instruction.
331pub const EOF_CREATE_GAS: u64 = 32000;
332
333// Berlin EIP-2929/EIP-2930 constants
334/// Gas cost for accessing an address in the access list (EIP-2930).
335pub const ACCESS_LIST_ADDRESS: u64 = 2400;
336/// Gas cost for accessing a storage key in the access list (EIP-2930).
337pub const ACCESS_LIST_STORAGE_KEY: u64 = 1900;
338
339/// Gas cost for SLOAD when accessing a cold storage slot (EIP-2929).
340pub const COLD_SLOAD_COST: u64 = 2100;
341/// Gas cost for accessing a cold account (EIP-2929).
342pub const COLD_ACCOUNT_ACCESS_COST: u64 = 2600;
343/// Additional gas cost for accessing a cold account.
344pub const COLD_ACCOUNT_ACCESS_COST_ADDITIONAL: u64 =
345 COLD_ACCOUNT_ACCESS_COST - WARM_STORAGE_READ_COST;
346/// Gas cost for reading from a warm storage slot (EIP-2929).
347pub const WARM_STORAGE_READ_COST: u64 = 100;
348/// Gas cost for SSTORE reset operation on a warm storage slot.
349pub const WARM_SSTORE_RESET: u64 = SSTORE_RESET - COLD_SLOAD_COST;
350
351/// EIP-3860 : Limit and meter initcode
352pub const INITCODE_WORD_COST: u64 = 2;
353
354/// Gas stipend provided to the recipient of a CALL with value transfer.
355pub const CALL_STIPEND: u64 = 2300;
356
357/// Init and floor gas from transaction
358#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
359#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
360pub struct InitialAndFloorGas {
361 /// Regular (non-state) portion of the initial intrinsic gas.
362 ///
363 /// Under EIP-8037, this is the part constrained by `TX_MAX_GAS_LIMIT`;
364 /// state gas uses its own reservoir and is not subject to that cap.
365 pub initial_regular_gas: u64,
366 /// State gas component of the initial intrinsic gas.
367 /// Under EIP-8037, this includes:
368 /// - EIP-7702 auth list state gas (per-auth account creation + metadata costs)
369 /// - For CREATE transactions: `create_state_gas` (account creation + contract metadata)
370 /// - For CALL transactions: 0 (state gas is unpredictable at validation time)
371 pub initial_state_gas: u64,
372 /// EIP-7702 refund for existing authorities.
373 /// This is the refund given when an authorization is applied to an already existing account.
374 pub state_refund: u64,
375 /// If transaction is a Call and Prague is enabled
376 /// floor_gas is at least amount of gas that is going to be spent.
377 pub floor_gas: u64,
378}
379
380impl InitialAndFloorGas {
381 /***** Constructors *****/
382
383 /// Create a new InitialAndFloorGas instance.
384 #[inline]
385 pub const fn new(initial_regular_gas: u64, floor_gas: u64) -> Self {
386 Self {
387 initial_regular_gas,
388 initial_state_gas: 0,
389 state_refund: 0,
390 floor_gas,
391 }
392 }
393
394 /// Create a new InitialAndFloorGas instance with state gas tracking.
395 #[inline]
396 pub const fn new_with_state_gas(
397 initial_regular_gas: u64,
398 initial_state_gas: u64,
399 floor_gas: u64,
400 ) -> Self {
401 Self {
402 initial_regular_gas,
403 initial_state_gas,
404 state_refund: 0,
405 floor_gas,
406 }
407 }
408
409 /***** Simple getters *****/
410
411 /// Regular (non-state) portion of the initial intrinsic gas.
412 ///
413 /// Under EIP-8037, this is the part constrained by `TX_MAX_GAS_LIMIT`;
414 /// state gas uses its own reservoir and is not subject to that cap.
415 #[inline]
416 pub const fn initial_regular_gas(&self) -> u64 {
417 self.initial_regular_gas
418 }
419
420 /// State gas component of the initial intrinsic gas.
421 /// This is the state gas component of the initial intrinsic gas minus the EIP-7702 refund.
422 #[inline]
423 pub const fn initial_state_gas_final(&self) -> u64 {
424 self.initial_state_gas - self.state_refund
425 }
426
427 /// EIP-7623 floor gas.
428 #[inline]
429 pub const fn floor_gas(&self) -> u64 {
430 self.floor_gas
431 }
432
433 /// Total initial intrinsic gas: `initial_regular_gas + initial_state_gas`.
434 #[inline]
435 pub const fn initial_total_gas(&self) -> u64 {
436 self.initial_regular_gas + self.initial_state_gas_final()
437 }
438
439 /***** Simple setters *****/
440
441 /// Sets the `initial_regular_gas` field by mutable reference.
442 #[inline]
443 pub const fn set_initial_regular_gas(&mut self, initial_regular_gas: u64) {
444 self.initial_regular_gas = initial_regular_gas;
445 }
446
447 /// Sets the `initial_state_gas` field by mutable reference.
448 #[inline]
449 pub const fn set_initial_state_gas(&mut self, initial_state_gas: u64) {
450 self.initial_state_gas = initial_state_gas;
451 }
452
453 /// Sets the `floor_gas` field by mutable reference.
454 #[inline]
455 pub const fn set_floor_gas(&mut self, floor_gas: u64) {
456 self.floor_gas = floor_gas;
457 }
458
459 /***** Builder with_* methods *****/
460
461 /// Sets the `initial_regular_gas` field.
462 #[inline]
463 pub const fn with_initial_regular_gas(mut self, initial_regular_gas: u64) -> Self {
464 self.initial_regular_gas = initial_regular_gas;
465 self
466 }
467
468 /// Sets the `initial_state_gas` field.
469 #[inline]
470 pub const fn with_initial_state_gas(mut self, initial_state_gas: u64) -> Self {
471 self.initial_state_gas = initial_state_gas;
472 self
473 }
474
475 /// Sets the `floor_gas` field.
476 #[inline]
477 pub const fn with_floor_gas(mut self, floor_gas: u64) -> Self {
478 self.floor_gas = floor_gas;
479 self
480 }
481
482 /// Computes the regular gas budget and reservoir for the initial call frame.
483 ///
484 /// EIP-8037 reservoir model:
485 /// execution_gas = tx.gas_limit - intrinsic_gas (= gas_limit parameter)
486 /// regular_gas_budget = min(execution_gas, TX_MAX_GAS_LIMIT - intrinsic_gas)
487 /// reservoir = execution_gas - regular_gas_budget
488 ///
489 /// Initial state gas is then deducted from the reservoir (spilling into the
490 /// regular budget when the reservoir is insufficient), and the EIP-7702
491 /// refund for existing authorities is added back to the reservoir.
492 ///
493 /// On mainnet (state gas disabled), reservoir = 0 and gas_limit is unchanged.
494 ///
495 /// Returns `(gas_limit, reservoir)`.
496 pub fn initial_gas_and_reservoir(
497 &self,
498 tx_gas_limit: u64,
499 tx_gas_limit_cap: u64,
500 ) -> (u64, u64) {
501 let execution_gas = tx_gas_limit - self.initial_regular_gas();
502
503 // System calls pass InitialAndFloorGas with all zeros and should not be
504 // subject to the TX_MAX_GAS_LIMIT cap.
505 let tx_gas_limit_cap = if self.initial_total_gas() == 0 {
506 u64::MAX
507 } else {
508 tx_gas_limit_cap
509 };
510
511 let mut regular_gas_limit = core::cmp::min(tx_gas_limit, tx_gas_limit_cap)
512 .saturating_sub(self.initial_regular_gas());
513 let mut reservoir = execution_gas - regular_gas_limit;
514
515 // Deduct initial state gas from the reservoir. When the reservoir is
516 // insufficient, the deficit is charged from the regular gas budget.
517 if reservoir >= self.initial_state_gas {
518 reservoir -= self.initial_state_gas;
519 } else {
520 regular_gas_limit -= self.initial_state_gas - reservoir;
521 reservoir = 0;
522 }
523
524 // EIP-7702 state gas refund for existing authorities goes directly to
525 // the reservoir. In the Python spec, set_delegation adds this refund to
526 // state_gas_reservoir so it stays as state gas (not regular gas).
527 reservoir += self.state_refund;
528
529 (regular_gas_limit, reservoir)
530 }
531}
532
533/// Initial gas that is deducted for transaction to be included.
534/// Initial gas contains initial stipend gas, gas for access list and input data.
535///
536/// # Returns
537///
538/// - Intrinsic gas
539/// - Number of tokens in calldata
540#[allow(clippy::too_many_arguments)]
541pub fn calculate_initial_tx_gas(
542 spec_id: SpecId,
543 input: &[u8],
544 is_create: bool,
545 access_list_accounts: u64,
546 access_list_storages: u64,
547 authorization_list_num: u64,
548 eip2780: Option<gas_params::Eip2780TxInfo>,
549) -> InitialAndFloorGas {
550 GasParams::new_spec(spec_id).initial_tx_gas(
551 input,
552 is_create,
553 access_list_accounts,
554 access_list_storages,
555 authorization_list_num,
556 eip2780,
557 )
558}
559
560/// Initial gas that is deducted for transaction to be included.
561/// Initial gas contains initial stipend gas, gas for access list and input data.
562///
563/// # Returns
564///
565/// - Intrinsic gas
566/// - Number of tokens in calldata
567pub fn calculate_initial_tx_gas_for_tx(
568 tx: impl Transaction,
569 spec: SpecId,
570 eip2780: Option<gas_params::Eip2780TxInfo>,
571) -> InitialAndFloorGas {
572 GasParams::new_spec(spec).initial_tx_gas_for_tx(tx, eip2780)
573}
574
575/// Retrieve the total number of tokens in calldata.
576#[inline]
577pub fn get_tokens_in_calldata_istanbul(input: &[u8]) -> u64 {
578 get_tokens_in_calldata(input, NON_ZERO_BYTE_MULTIPLIER_ISTANBUL)
579}
580
581/// Retrieve the total number of tokens in calldata.
582#[inline]
583pub fn get_tokens_in_calldata(input: &[u8], non_zero_data_multiplier: u64) -> u64 {
584 let zero_data_len = input.iter().filter(|v| **v == 0).count() as u64;
585 let non_zero_data_len = input.len() as u64 - zero_data_len;
586 zero_data_len + non_zero_data_len * non_zero_data_multiplier
587}