revm_interpreter/gas/
calc.rs

1use super::constants::*;
2use crate::{num_words, tri, SStoreResult, SelfDestructResult, StateLoad};
3use context_interface::{
4    journaled_state::AccountLoad, transaction::AccessListItemTr as _, Transaction, TransactionType,
5};
6use primitives::{eip7702, hardfork::SpecId, U256};
7
8/// `SSTORE` opcode refund calculation.
9#[allow(clippy::collapsible_else_if)]
10#[inline]
11pub fn sstore_refund(spec_id: SpecId, vals: &SStoreResult) -> i64 {
12    if spec_id.is_enabled_in(SpecId::ISTANBUL) {
13        // EIP-3529: Reduction in refunds
14        let sstore_clears_schedule = if spec_id.is_enabled_in(SpecId::LONDON) {
15            (SSTORE_RESET - COLD_SLOAD_COST + ACCESS_LIST_STORAGE_KEY) as i64
16        } else {
17            REFUND_SSTORE_CLEARS
18        };
19        if vals.is_new_eq_present() {
20            0
21        } else {
22            if vals.is_original_eq_present() && vals.is_new_zero() {
23                sstore_clears_schedule
24            } else {
25                let mut refund = 0;
26
27                if !vals.is_original_zero() {
28                    if vals.is_present_zero() {
29                        refund -= sstore_clears_schedule;
30                    } else if vals.is_new_zero() {
31                        refund += sstore_clears_schedule;
32                    }
33                }
34
35                if vals.is_original_eq_new() {
36                    let (gas_sstore_reset, gas_sload) = if spec_id.is_enabled_in(SpecId::BERLIN) {
37                        (SSTORE_RESET - COLD_SLOAD_COST, WARM_STORAGE_READ_COST)
38                    } else {
39                        (SSTORE_RESET, sload_cost(spec_id, false))
40                    };
41                    if vals.is_original_zero() {
42                        refund += (SSTORE_SET - gas_sload) as i64;
43                    } else {
44                        refund += (gas_sstore_reset - gas_sload) as i64;
45                    }
46                }
47
48                refund
49            }
50        }
51    } else {
52        if !vals.is_present_zero() && vals.is_new_zero() {
53            REFUND_SSTORE_CLEARS
54        } else {
55            0
56        }
57    }
58}
59
60/// `CREATE2` opcode cost calculation.
61#[inline]
62pub const fn create2_cost(len: usize) -> Option<u64> {
63    CREATE.checked_add(tri!(cost_per_word(len, KECCAK256WORD)))
64}
65
66#[inline]
67const fn log2floor(value: U256) -> u64 {
68    let mut l: u64 = 256;
69    let mut i = 3;
70    loop {
71        if value.as_limbs()[i] == 0u64 {
72            l -= 64;
73        } else {
74            l -= value.as_limbs()[i].leading_zeros() as u64;
75            if l == 0 {
76                return l;
77            } else {
78                return l - 1;
79            }
80        }
81        if i == 0 {
82            break;
83        }
84        i -= 1;
85    }
86    l
87}
88
89/// `EXP` opcode cost calculation.
90#[inline]
91pub fn exp_cost(spec_id: SpecId, power: U256) -> Option<u64> {
92    if power.is_zero() {
93        Some(EXP)
94    } else {
95        // EIP-160: EXP cost increase
96        let gas_byte = U256::from(if spec_id.is_enabled_in(SpecId::SPURIOUS_DRAGON) {
97            50
98        } else {
99            10
100        });
101        let gas = U256::from(EXP)
102            .checked_add(gas_byte.checked_mul(U256::from(log2floor(power) / 8 + 1))?)?;
103
104        u64::try_from(gas).ok()
105    }
106}
107
108/// `*COPY` opcodes cost calculation.
109#[inline]
110pub const fn copy_cost_verylow(len: usize) -> Option<u64> {
111    copy_cost(VERYLOW, len)
112}
113
114/// `EXTCODECOPY` opcode cost calculation.
115#[inline]
116pub const fn extcodecopy_cost(spec_id: SpecId, len: usize, is_cold: bool) -> Option<u64> {
117    let base_gas = if spec_id.is_enabled_in(SpecId::BERLIN) {
118        warm_cold_cost(is_cold)
119    } else if spec_id.is_enabled_in(SpecId::TANGERINE) {
120        700
121    } else {
122        20
123    };
124    copy_cost(base_gas, len)
125}
126
127#[inline]
128/// Calculates the gas cost for copy operations based on data length.
129pub const fn copy_cost(base_cost: u64, len: usize) -> Option<u64> {
130    base_cost.checked_add(tri!(cost_per_word(len, COPY)))
131}
132
133/// `LOG` opcode cost calculation.
134#[inline]
135pub const fn log_cost(n: u8, len: u64) -> Option<u64> {
136    tri!(LOG.checked_add(tri!(LOGDATA.checked_mul(len)))).checked_add(LOGTOPIC * n as u64)
137}
138
139/// `KECCAK256` opcode cost calculation.
140#[inline]
141pub const fn keccak256_cost(len: usize) -> Option<u64> {
142    KECCAK256.checked_add(tri!(cost_per_word(len, KECCAK256WORD)))
143}
144
145/// Calculate the cost of buffer per word.
146#[inline]
147pub const fn cost_per_word(len: usize, multiple: u64) -> Option<u64> {
148    multiple.checked_mul(num_words(len) as u64)
149}
150
151/// EIP-3860: Limit and meter initcode
152///
153/// Apply extra gas cost of 2 for every 32-byte chunk of initcode.
154///
155/// This cannot overflow as the initcode length is assumed to be checked.
156#[inline]
157pub const fn initcode_cost(len: usize) -> u64 {
158    let Some(cost) = cost_per_word(len, INITCODE_WORD_COST) else {
159        panic!("initcode cost overflow")
160    };
161    cost
162}
163
164/// `SLOAD` opcode cost calculation.
165#[inline]
166pub const fn sload_cost(spec_id: SpecId, is_cold: bool) -> u64 {
167    if spec_id.is_enabled_in(SpecId::BERLIN) {
168        if is_cold {
169            COLD_SLOAD_COST
170        } else {
171            WARM_STORAGE_READ_COST
172        }
173    } else if spec_id.is_enabled_in(SpecId::ISTANBUL) {
174        // EIP-1884: Repricing for trie-size-dependent opcodes
175        ISTANBUL_SLOAD_GAS
176    } else if spec_id.is_enabled_in(SpecId::TANGERINE) {
177        // EIP-150: Gas cost changes for IO-heavy operations
178        200
179    } else {
180        50
181    }
182}
183
184/// `SSTORE` opcode cost calculation.
185#[inline]
186pub fn sstore_cost(spec_id: SpecId, vals: &SStoreResult, is_cold: bool) -> u64 {
187    if spec_id.is_enabled_in(SpecId::BERLIN) {
188        // Berlin specification logic
189        let mut gas_cost = istanbul_sstore_cost::<WARM_STORAGE_READ_COST, WARM_SSTORE_RESET>(vals);
190
191        if is_cold {
192            gas_cost += COLD_SLOAD_COST;
193        }
194        gas_cost
195    } else if spec_id.is_enabled_in(SpecId::ISTANBUL) {
196        // Istanbul logic
197        istanbul_sstore_cost::<ISTANBUL_SLOAD_GAS, SSTORE_RESET>(vals)
198    } else {
199        // Frontier logic
200        frontier_sstore_cost(vals)
201    }
202}
203
204/// EIP-2200: Structured Definitions for Net Gas Metering
205#[inline]
206fn istanbul_sstore_cost<const SLOAD_GAS: u64, const SSTORE_RESET_GAS: u64>(
207    vals: &SStoreResult,
208) -> u64 {
209    if vals.is_new_eq_present() {
210        SLOAD_GAS
211    } else if vals.is_original_eq_present() && vals.is_original_zero() {
212        SSTORE_SET
213    } else if vals.is_original_eq_present() {
214        SSTORE_RESET_GAS
215    } else {
216        SLOAD_GAS
217    }
218}
219
220/// Frontier sstore cost just had two cases set and reset values.
221#[inline]
222fn frontier_sstore_cost(vals: &SStoreResult) -> u64 {
223    if vals.is_present_zero() && !vals.is_new_zero() {
224        SSTORE_SET
225    } else {
226        SSTORE_RESET
227    }
228}
229
230/// `SELFDESTRUCT` opcode cost calculation.
231#[inline]
232pub const fn selfdestruct_cost(spec_id: SpecId, res: StateLoad<SelfDestructResult>) -> u64 {
233    // EIP-161: State trie clearing (invariant-preserving alternative)
234    let should_charge_topup = if spec_id.is_enabled_in(SpecId::SPURIOUS_DRAGON) {
235        res.data.had_value && !res.data.target_exists
236    } else {
237        !res.data.target_exists
238    };
239
240    // EIP-150: Gas cost changes for IO-heavy operations
241    let selfdestruct_gas_topup = if spec_id.is_enabled_in(SpecId::TANGERINE) && should_charge_topup
242    {
243        25000
244    } else {
245        0
246    };
247
248    // EIP-150: Gas cost changes for IO-heavy operations
249    let selfdestruct_gas = if spec_id.is_enabled_in(SpecId::TANGERINE) {
250        5000
251    } else {
252        0
253    };
254
255    let mut gas = selfdestruct_gas + selfdestruct_gas_topup;
256    if spec_id.is_enabled_in(SpecId::BERLIN) && res.is_cold {
257        gas += COLD_ACCOUNT_ACCESS_COST
258    }
259    gas
260}
261
262/// Calculate call gas cost for the call instruction.
263///
264/// There is three types of gas.
265/// * Account access gas. after berlin it can be cold or warm.
266/// * Transfer value gas. If value is transferred and balance of target account is updated.
267/// * If account is not existing and needs to be created. After Spurious dragon
268///   this is only accounted if value is transferred.
269///
270/// account_load.is_empty will be accounted only if hardfork is SPURIOUS_DRAGON and
271/// there is transfer value. [`bytecode::opcode::CALL`] use this field.
272///
273/// While [`bytecode::opcode::STATICCALL`], [`bytecode::opcode::DELEGATECALL`],
274/// [`bytecode::opcode::CALLCODE`] need to have this field hardcoded to false
275/// as they were present before SPURIOUS_DRAGON hardfork.
276#[inline]
277pub const fn call_cost(
278    spec_id: SpecId,
279    transfers_value: bool,
280    account_load: StateLoad<AccountLoad>,
281) -> u64 {
282    let is_empty = account_load.data.is_empty;
283    // Account access.
284    let mut gas = if spec_id.is_enabled_in(SpecId::BERLIN) {
285        warm_cold_cost_with_delegation(account_load)
286    } else if spec_id.is_enabled_in(SpecId::TANGERINE) {
287        // EIP-150: Gas cost changes for IO-heavy operations
288        700
289    } else {
290        40
291    };
292
293    // Transfer value cost
294    if transfers_value {
295        gas += CALLVALUE;
296    }
297
298    // New account cost
299    if is_empty {
300        // EIP-161: State trie clearing (invariant-preserving alternative)
301        if spec_id.is_enabled_in(SpecId::SPURIOUS_DRAGON) {
302            // Account only if there is value transferred.
303            if transfers_value {
304                gas += NEWACCOUNT;
305            }
306        } else {
307            gas += NEWACCOUNT;
308        }
309    }
310
311    gas
312}
313
314/// Berlin warm and cold storage access cost for account access.
315#[inline]
316pub const fn warm_cold_cost(is_cold: bool) -> u64 {
317    if is_cold {
318        COLD_ACCOUNT_ACCESS_COST
319    } else {
320        WARM_STORAGE_READ_COST
321    }
322}
323
324/// Berlin warm and cold storage access cost for account access.
325///
326/// If delegation is Some, add additional cost for delegation account load.
327#[inline]
328pub const fn warm_cold_cost_with_delegation(load: StateLoad<AccountLoad>) -> u64 {
329    let mut gas = warm_cold_cost(load.is_cold);
330    if let Some(is_cold) = load.data.is_delegate_account_cold {
331        gas += warm_cold_cost(is_cold);
332    }
333    gas
334}
335
336/// Memory expansion cost calculation for a given number of words.
337#[inline]
338pub const fn memory_gas(num_words: usize) -> u64 {
339    let num_words = num_words as u64;
340    MEMORY
341        .saturating_mul(num_words)
342        .saturating_add(num_words.saturating_mul(num_words) / 512)
343}
344
345/// Init and floor gas from transaction
346#[derive(Clone, Copy, Debug, Default)]
347pub struct InitialAndFloorGas {
348    /// Initial gas for transaction.
349    pub initial_gas: u64,
350    /// If transaction is a Call and Prague is enabled
351    /// floor_gas is at least amount of gas that is going to be spent.
352    pub floor_gas: u64,
353}
354
355impl InitialAndFloorGas {
356    /// Create a new InitialAndFloorGas instance.
357    #[inline]
358    pub const fn new(initial_gas: u64, floor_gas: u64) -> Self {
359        Self {
360            initial_gas,
361            floor_gas,
362        }
363    }
364}
365
366/// Initial gas that is deducted for transaction to be included.
367/// Initial gas contains initial stipend gas, gas for access list and input data.
368///
369/// # Returns
370///
371/// - Intrinsic gas
372/// - Number of tokens in calldata
373pub fn calculate_initial_tx_gas(
374    spec_id: SpecId,
375    input: &[u8],
376    is_create: bool,
377    access_list_accounts: u64,
378    access_list_storages: u64,
379    authorization_list_num: u64,
380) -> InitialAndFloorGas {
381    let mut gas = InitialAndFloorGas::default();
382
383    // Initdate stipend
384    let tokens_in_calldata = get_tokens_in_calldata(input, spec_id.is_enabled_in(SpecId::ISTANBUL));
385
386    // TODO(EOF) Tx type is removed
387    // initcode stipend
388    // for initcode in initcodes {
389    //     tokens_in_calldata += get_tokens_in_calldata(initcode.as_ref(), true);
390    // }
391
392    gas.initial_gas += tokens_in_calldata * STANDARD_TOKEN_COST;
393
394    // Get number of access list account and storages.
395    gas.initial_gas += access_list_accounts * ACCESS_LIST_ADDRESS;
396    gas.initial_gas += access_list_storages * ACCESS_LIST_STORAGE_KEY;
397
398    // Base stipend
399    gas.initial_gas += if is_create {
400        if spec_id.is_enabled_in(SpecId::HOMESTEAD) {
401            // EIP-2: Homestead Hard-fork Changes
402            53000
403        } else {
404            21000
405        }
406    } else {
407        21000
408    };
409
410    // EIP-3860: Limit and meter initcode
411    // Init code stipend for bytecode analysis
412    if spec_id.is_enabled_in(SpecId::SHANGHAI) && is_create {
413        gas.initial_gas += initcode_cost(input.len())
414    }
415
416    // EIP-7702
417    if spec_id.is_enabled_in(SpecId::PRAGUE) {
418        gas.initial_gas += authorization_list_num * eip7702::PER_EMPTY_ACCOUNT_COST;
419
420        // Calculate gas floor for EIP-7623
421        gas.floor_gas = calc_tx_floor_cost(tokens_in_calldata);
422    }
423
424    gas
425}
426
427/// Initial gas that is deducted for transaction to be included.
428/// Initial gas contains initial stipend gas, gas for access list and input data.
429///
430/// # Returns
431///
432/// - Intrinsic gas
433/// - Number of tokens in calldata
434pub fn calculate_initial_tx_gas_for_tx(tx: impl Transaction, spec: SpecId) -> InitialAndFloorGas {
435    let mut accounts = 0;
436    let mut storages = 0;
437    // legacy is only tx type that does not have access list.
438    if tx.tx_type() != TransactionType::Legacy {
439        (accounts, storages) = tx
440            .access_list()
441            .map(|al| {
442                al.fold((0, 0), |(mut num_accounts, mut num_storage_slots), item| {
443                    num_accounts += 1;
444                    num_storage_slots += item.storage_slots().count();
445
446                    (num_accounts, num_storage_slots)
447                })
448            })
449            .unwrap_or_default();
450    }
451
452    // Access initcodes only if tx is Eip7873.
453    // TODO(EOF) Tx type is removed
454    // let initcodes = if tx.tx_type() == TransactionType::Eip7873 {
455    //     tx.initcodes()
456    // } else {
457    //     &[]
458    // };
459
460    calculate_initial_tx_gas(
461        spec,
462        tx.input(),
463        tx.kind().is_create(),
464        accounts as u64,
465        storages as u64,
466        tx.authorization_list_len() as u64,
467        //initcodes,
468    )
469}
470
471/// Retrieve the total number of tokens in calldata.
472#[inline]
473pub fn get_tokens_in_calldata(input: &[u8], is_istanbul: bool) -> u64 {
474    let zero_data_len = input.iter().filter(|v| **v == 0).count() as u64;
475    let non_zero_data_len = input.len() as u64 - zero_data_len;
476    let non_zero_data_multiplier = if is_istanbul {
477        // EIP-2028: Transaction data gas cost reduction
478        NON_ZERO_BYTE_MULTIPLIER_ISTANBUL
479    } else {
480        NON_ZERO_BYTE_MULTIPLIER
481    };
482    zero_data_len + non_zero_data_len * non_zero_data_multiplier
483}
484
485/// Calculate the transaction cost floor as specified in EIP-7623.
486#[inline]
487pub fn calc_tx_floor_cost(tokens_in_calldata: u64) -> u64 {
488    tokens_in_calldata * TOTAL_COST_FLOOR_PER_TOKEN + 21_000
489}