Skip to main content

foundry_evm_core/
utils.rs

1use crate::{evm::EvmEnv, hardfork::FoundryHardfork};
2use alloy_chains::Chain;
3use alloy_consensus::{BlockHeader, private::alloy_eips::eip7840::BlobParams};
4use alloy_eips::eip2930::AccessList;
5use alloy_hardforks::EthereumHardfork;
6use alloy_json_abi::{Function, JsonAbi};
7use alloy_primitives::{Address, ChainId, Selector, U256};
8use alloy_provider::{Network, network::BlockResponse};
9use evm2::{EvmFeatures, EvmTypesHost, OpcodeSet, SpecId, env::BlockEnv};
10use foundry_config::NamedChain::{
11    self, Avalanche, AvalancheFuji, BinanceSmartChain, BinanceSmartChainTestnet, Polygon,
12    PolygonAmoy,
13};
14use foundry_evm_networks::{NetworkConfigs, arbitrum};
15
16/// Hints to the compiler that this is a cold path, i.e. unlikely to be taken.
17#[cold]
18#[inline(always)]
19pub const fn cold_path() {
20    // TODO: remove `#[cold]` and call `std::hint::cold_path` once stable.
21}
22
23/// Constructs a block environment from a block header.
24///
25/// A header without `mixHash` leaves `prevrandao` at zero.
26pub fn block_env_from_header<T: EvmTypesHost>(header: &impl BlockHeader) -> BlockEnv<T> {
27    BlockEnv::<T> {
28        number: U256::from(header.number()),
29        beneficiary: header.beneficiary(),
30        timestamp: U256::from(header.timestamp()),
31        gas_limit: U256::from(header.gas_limit()),
32        basefee: U256::from(header.base_fee_per_gas().unwrap_or_default()),
33        difficulty: header.difficulty(),
34        prevrandao: header.mix_hash().unwrap_or_default().into(),
35        slot_num: U256::from(header.slot_number().unwrap_or_default()),
36        ..Default::default()
37    }
38}
39
40/// Applies replay normalization for the provided source chain.
41///
42/// This keeps fork-specific transaction validation independent from an execution `CHAINID`
43/// override.
44pub fn apply_chain_specific_tx_replay_env_changes_for_chain<T: EvmTypesHost>(
45    evm_env: &mut EvmEnv<T>,
46    source_chain_id: ChainId,
47) {
48    let chain = NamedChain::try_from(source_chain_id);
49    if chain.is_ok_and(|chain| chain.is_arbitrum()) {
50        // Arbitrum does not enforce the EIP-1559 priority fee ordering constraint.
51        evm_env.set_feature(EvmFeatures::PRIORITY_FEE_CHECK, false);
52    }
53    if matches!(chain, Ok(NamedChain::Celo | NamedChain::CeloSepolia)) {
54        // CIP-64 fee caps are denominated in the fee currency, not in the native base fee.
55        evm_env.set_feature(EvmFeatures::BASE_FEE_CHECK, false);
56    }
57}
58
59/// Applies block normalization for the provided source chain.
60///
61/// This keeps fork-specific header handling independent from an execution `CHAINID` override.
62pub fn apply_chain_and_block_specific_env_changes_for_chain<N: Network, T: EvmTypesHost>(
63    evm_env: &mut EvmEnv<T>,
64    block: &N::BlockResponse,
65    source_chain_id: ChainId,
66    configs: NetworkConfigs,
67) {
68    let header = block.header();
69    // The blob fee market is priced from the header's excess blob gas and the source chain's
70    // blob schedule at the block timestamp. Headers without the field (pre-Cancun blocks and
71    // chains without EIP-4844) keep the default blob environment.
72    if let Some(excess_blob_gas) = header.excess_blob_gas() {
73        evm_env.set_blob_excess_gas(
74            excess_blob_gas,
75            get_blob_base_fee_update_fraction(source_chain_id, header.timestamp()),
76        );
77    }
78
79    let block_env = &mut evm_env.block;
80    if let Ok(chain) = NamedChain::try_from(source_chain_id) {
81        match chain {
82            BinanceSmartChain
83            | BinanceSmartChainTestnet
84            | Polygon
85            | PolygonAmoy
86            | Avalanche
87            | AvalancheFuji => {
88                // https://github.com/foundry-rs/foundry/issues/9942
89                // As far as observed from the source code of bnb-chain/bsc, the `difficulty` field
90                // is still in use and returned by the corresponding opcode but `prevrandao`
91                // (`mixHash`) is always zero, even though bsc adopts the newer EVM
92                // specification. Polygon and Avalanche behave the same way.
93                block_env.prevrandao = block_env.difficulty;
94                return;
95            }
96            c if c.is_arbitrum() => {
97                // on arbitrum `block.number` is the L1 block which is included in the
98                // `l1BlockNumber` field
99                if let Some(l1_block_number) = block
100                    .other_fields()
101                    .and_then(|other| other.get("l1BlockNumber").cloned())
102                    .and_then(|l1_block_number| {
103                        serde_json::from_value::<U256>(l1_block_number).ok()
104                    })
105                {
106                    block_env.number = l1_block_number;
107                }
108
109                // `mixHash` carries L1 metadata rather than randomness here, while the
110                // `PREVRANDAO` opcode returns `difficulty` like it does on the chains above.
111                block_env.prevrandao = block_env.difficulty;
112            }
113            _ => {}
114        }
115    }
116
117    if configs.bypass_prevrandao(source_chain_id) && header.mix_hash().is_none() {
118        // Chains without randomness keep the historical DIFFICULTY opcode semantics.
119        // <https://github.com/foundry-rs/foundry/issues/4232>
120        block_env.prevrandao = block_env.difficulty;
121    }
122
123    // if difficulty is `0` we assume it's past merge
124    if header.difficulty().is_zero() {
125        block_env.difficulty = block_env.prevrandao;
126    }
127}
128
129/// Derives the active [`BlobParams`] based on the given timestamp.
130///
131/// This falls back to regular ethereum blob params if no hardforks for the given chain id are
132/// detected.
133pub fn get_blob_params(chain_id: ChainId, timestamp: u64) -> BlobParams {
134    let hardfork = EthereumHardfork::from_chain_and_timestamp(Chain::from_id(chain_id), timestamp)
135        .unwrap_or_default();
136
137    match hardfork {
138        EthereumHardfork::Prague => BlobParams::prague(),
139        EthereumHardfork::Osaka => BlobParams::osaka(),
140        EthereumHardfork::Bpo1 => BlobParams::bpo1(),
141        EthereumHardfork::Bpo2 => BlobParams::bpo2(),
142
143        // future hardforks/unknown settings: update once decided
144        EthereumHardfork::Bpo3 => BlobParams::bpo2(),
145        EthereumHardfork::Bpo4 => BlobParams::bpo2(),
146        EthereumHardfork::Bpo5 => BlobParams::bpo2(),
147        EthereumHardfork::Amsterdam => BlobParams::bpo2(),
148
149        // fallback
150        _ => BlobParams::cancun(),
151    }
152}
153
154/// Derive the blob base fee update fraction based on the chain and timestamp by checking the
155/// hardfork.
156pub fn get_blob_base_fee_update_fraction(chain_id: ChainId, timestamp: u64) -> u64 {
157    get_blob_params(chain_id, timestamp).update_fraction as u64
158}
159
160/// Returns the blob params based on the spec id.
161pub fn get_blob_params_by_spec_id(spec: SpecId) -> BlobParams {
162    if spec >= SpecId::AMSTERDAM {
163        BlobParams::bpo2()
164    } else if spec >= SpecId::OSAKA {
165        BlobParams::osaka()
166    } else if spec >= SpecId::PRAGUE {
167        BlobParams::prague()
168    } else {
169        BlobParams::cancun()
170    }
171}
172
173/// Returns the blob parameters selected by an explicit Foundry hardfork.
174pub fn get_blob_params_by_hardfork(hardfork: FoundryHardfork) -> BlobParams {
175    match hardfork {
176        FoundryHardfork::Ethereum(EthereumHardfork::Prague) => BlobParams::prague(),
177        FoundryHardfork::Ethereum(EthereumHardfork::Osaka) => BlobParams::osaka(),
178        FoundryHardfork::Ethereum(EthereumHardfork::Bpo1) => BlobParams::bpo1(),
179        FoundryHardfork::Ethereum(EthereumHardfork::Bpo2) => BlobParams::bpo2(),
180        FoundryHardfork::Ethereum(
181            EthereumHardfork::Bpo3
182            | EthereumHardfork::Bpo4
183            | EthereumHardfork::Bpo5
184            | EthereumHardfork::Amsterdam,
185        ) => BlobParams::bpo2(),
186        _ => get_blob_params_by_spec_id(hardfork.into()),
187    }
188}
189
190/// Returns the blob base fee update fraction based on the spec id.
191pub fn get_blob_base_fee_update_fraction_by_spec_id(spec: SpecId) -> u64 {
192    get_blob_params_by_spec_id(spec).update_fraction as u64
193}
194
195/// Given an ABI and selector, it tries to find the respective function.
196pub fn get_function<'a>(
197    contract_name: &str,
198    selector: Selector,
199    abi: &'a JsonAbi,
200) -> eyre::Result<&'a Function> {
201    abi.functions()
202        .find(|func| func.selector() == selector)
203        .ok_or_else(|| eyre::eyre!("{contract_name} does not have the selector {selector}"))
204}
205
206/// Returns the addresses a transaction in `env` with `access_list` warms when it starts and that
207/// `vm.cool` keeps warm: the EIP-3651 coinbase, Arbitrum's ArbSys on Arbitrum chains, and the
208/// access list.
209pub fn tx_warm_addresses<T: EvmTypesHost>(
210    env: &EvmEnv<T>,
211    access_list: Option<&AccessList>,
212) -> Vec<Address> {
213    let coinbase = env.version.feature(EvmFeatures::EIP3651).then_some(env.block.beneficiary);
214    let arb_sys =
215        arbitrum::is_arbitrum_chain(env.version.chain_id).then_some(arbitrum::ARB_SYS_ADDRESS);
216    let access_list = access_list.into_iter().flat_map(|list| list.iter().map(|item| item.address));
217    coinbase.into_iter().chain(arb_sys).chain(access_list).collect()
218}
219
220/// Returns the set of `ops`.
221pub const fn opcodes<const N: usize>(ops: [u8; N]) -> OpcodeSet {
222    let mut set = OpcodeSet::EMPTY;
223    let mut i = 0;
224    while i < N {
225        set.insert(ops[i]);
226        i += 1;
227    }
228    set
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234    use alloy_network::{AnyHeader, AnyNetwork, AnyRpcBlock, AnyRpcHeader};
235    use alloy_primitives::B256;
236    use alloy_rpc_types::{Block, BlockTransactions};
237    use evm2::{BaseEvmTypes, Version};
238
239    fn env(block: BlockEnv<BaseEvmTypes>) -> EvmEnv<BaseEvmTypes> {
240        EvmEnv::new(SpecId::PRAGUE, Version::new(SpecId::PRAGUE), block)
241    }
242
243    #[test]
244    fn block_env_preserves_slot_number() {
245        for slot_number in [None, Some(0), Some(42), Some(u64::MAX)] {
246            let header = AnyHeader { slot_number, ..Default::default() };
247            let block = block_env_from_header::<BaseEvmTypes>(&header);
248            assert_eq!(block.slot_num, U256::from(slot_number.unwrap_or_default()));
249        }
250    }
251
252    #[test]
253    fn block_normalization_uses_source_chain() {
254        let header = AnyHeader { number: 500, ..Default::default() };
255        let mut block = AnyRpcBlock::new(
256            Block::new(
257                AnyRpcHeader::from_sealed(header.seal(B256::ZERO)),
258                BlockTransactions::Full(Vec::new()),
259            )
260            .into(),
261        );
262        block.other.insert("l1BlockNumber".to_string(), serde_json::json!("0x64"));
263
264        let mut evm_env =
265            env(BlockEnv::<BaseEvmTypes> { number: U256::from(500), ..Default::default() });
266        evm_env.set_chain_id(NamedChain::Mainnet as u64);
267
268        apply_chain_and_block_specific_env_changes_for_chain::<AnyNetwork, _>(
269            &mut evm_env,
270            &block,
271            NamedChain::Arbitrum as u64,
272            NetworkConfigs::default(),
273        );
274
275        assert_eq!(evm_env.chain_id(), NamedChain::Mainnet as u64);
276        assert_eq!(evm_env.block.number, U256::from(100));
277    }
278
279    #[test]
280    fn block_normalization_sets_blob_excess_gas_from_header() {
281        // Mainnet block 22_000_000 (Cancun): 22_151_168 excess blob gas prices blobs at 761 wei.
282        let header = AnyHeader {
283            timestamp: 1_741_410_875,
284            excess_blob_gas: Some(22_151_168),
285            ..Default::default()
286        };
287        let block = AnyRpcBlock::new(
288            Block::new(
289                AnyRpcHeader::from_sealed(header.seal(B256::ZERO)),
290                BlockTransactions::Full(Vec::new()),
291            )
292            .into(),
293        );
294        let mut evm_env = env(BlockEnv::<BaseEvmTypes>::default());
295        // The execution chain id can be overridden; the blob schedule follows the source chain.
296        evm_env.set_chain_id(1337);
297
298        apply_chain_and_block_specific_env_changes_for_chain::<AnyNetwork, _>(
299            &mut evm_env,
300            &block,
301            NamedChain::Mainnet as u64,
302            NetworkConfigs::default(),
303        );
304
305        assert_eq!(evm_env.block.blob_basefee, U256::from(761));
306    }
307
308    #[test]
309    fn block_normalization_keeps_default_blob_env_without_header_field() {
310        let header = AnyHeader { excess_blob_gas: None, ..Default::default() };
311        let block = AnyRpcBlock::new(
312            Block::new(
313                AnyRpcHeader::from_sealed(header.seal(B256::ZERO)),
314                BlockTransactions::Full(Vec::new()),
315            )
316            .into(),
317        );
318        let mut evm_env = env(BlockEnv::<BaseEvmTypes>::default());
319
320        apply_chain_and_block_specific_env_changes_for_chain::<AnyNetwork, _>(
321            &mut evm_env,
322            &block,
323            NamedChain::Mainnet as u64,
324            NetworkConfigs::default(),
325        );
326
327        assert_eq!(evm_env.block.blob_basefee, BlockEnv::<BaseEvmTypes>::default().blob_basefee);
328    }
329
330    #[test]
331    fn block_normalization_handles_missing_prevrandao_deterministically() {
332        for (chain, configs, bypass) in [
333            (NamedChain::Moonbeam as u64, NetworkConfigs::default(), true),
334            (NamedChain::Gnosis as u64, NetworkConfigs::default(), true),
335            (NamedChain::Rsk as u64, NetworkConfigs::default(), true),
336            (98_765_432, NetworkConfigs::default(), false),
337            (
338                98_765_432,
339                serde_json::from_str(r#"{"bypass_prevrandao":true,"celo":false}"#).unwrap(),
340                true,
341            ),
342        ] {
343            for difficulty in [U256::ZERO, U256::from(42)] {
344                let header = AnyHeader { difficulty, mix_hash: None, ..Default::default() };
345                let block = AnyRpcBlock::new(
346                    Block::new(
347                        AnyRpcHeader::from_sealed(header.seal(B256::ZERO)),
348                        BlockTransactions::Full(Vec::new()),
349                    )
350                    .into(),
351                );
352                let mut previous = None;
353                for _ in 0..2 {
354                    let mut evm_env = env(block_env_from_header::<BaseEvmTypes>(block.header()));
355                    apply_chain_and_block_specific_env_changes_for_chain::<AnyNetwork, _>(
356                        &mut evm_env,
357                        &block,
358                        chain,
359                        configs,
360                    );
361                    let expected = if bypass { difficulty } else { U256::ZERO };
362                    assert_eq!(evm_env.block.prevrandao, expected);
363                    assert_eq!(evm_env.block.difficulty, difficulty);
364                    if let Some(previous) = &previous {
365                        assert_eq!(&evm_env.block, previous);
366                    }
367                    previous = Some(evm_env.block);
368                }
369            }
370        }
371    }
372
373    #[test]
374    fn block_normalization_preserves_header_prevrandao() {
375        let randao = B256::repeat_byte(0xab);
376        let header = AnyHeader { mix_hash: Some(randao), ..Default::default() };
377        let block = AnyRpcBlock::new(
378            Block::new(
379                AnyRpcHeader::from_sealed(header.seal(B256::ZERO)),
380                BlockTransactions::Full(Vec::new()),
381            )
382            .into(),
383        );
384        let mut evm_env = env(block_env_from_header::<BaseEvmTypes>(block.header()));
385        apply_chain_and_block_specific_env_changes_for_chain::<AnyNetwork, _>(
386            &mut evm_env,
387            &block,
388            NamedChain::Gnosis as u64,
389            NetworkConfigs::default(),
390        );
391        assert_eq!(evm_env.block.prevrandao, U256::from_be_bytes(randao.0));
392    }
393
394    #[test]
395    fn block_normalization_preserves_mainnet_merge_boundary() {
396        let randao = B256::repeat_byte(0xab);
397        for number in [15_537_350, 15_537_351, 15_537_393, 15_537_394] {
398            let difficulty = if number < 15_537_394 { U256::from(42) } else { U256::ZERO };
399            let header =
400                AnyHeader { number, difficulty, mix_hash: Some(randao), ..Default::default() };
401            let block = AnyRpcBlock::new(
402                Block::new(
403                    AnyRpcHeader::from_sealed(header.seal(B256::ZERO)),
404                    BlockTransactions::Full(Vec::new()),
405                )
406                .into(),
407            );
408            let mut evm_env = env(block_env_from_header::<BaseEvmTypes>(block.header()));
409            apply_chain_and_block_specific_env_changes_for_chain::<AnyNetwork, _>(
410                &mut evm_env,
411                &block,
412                NamedChain::Mainnet as u64,
413                NetworkConfigs::default(),
414            );
415            let expected = if difficulty.is_zero() { randao.into() } else { difficulty };
416            assert_eq!(evm_env.block.difficulty, expected, "block {number}");
417            assert_eq!(evm_env.block.prevrandao, U256::from_be_bytes(randao.0));
418        }
419    }
420
421    #[test]
422    fn block_normalization_uses_difficulty_as_prevrandao() {
423        // These chains keep using `difficulty` and return it from `PREVRANDAO`, so a header
424        // `mixHash` of zero (or, on Arbitrum, packed L1 metadata) must not reach the block env.
425        for (chain, mix_hash) in [
426            (NamedChain::BinanceSmartChain, B256::ZERO),
427            (NamedChain::Polygon, B256::ZERO),
428            (NamedChain::PolygonAmoy, B256::ZERO),
429            (NamedChain::Avalanche, B256::ZERO),
430            (NamedChain::AvalancheFuji, B256::ZERO),
431            (NamedChain::Arbitrum, B256::repeat_byte(0xab)),
432            (NamedChain::ArbitrumNova, B256::repeat_byte(0xab)),
433            (NamedChain::ArbitrumSepolia, B256::repeat_byte(0xab)),
434        ] {
435            let header =
436                AnyHeader { difficulty: U256::ONE, mix_hash: Some(mix_hash), ..Default::default() };
437            let block = AnyRpcBlock::new(
438                Block::new(
439                    AnyRpcHeader::from_sealed(header.seal(B256::ZERO)),
440                    BlockTransactions::Full(Vec::new()),
441                )
442                .into(),
443            );
444            let mut evm_env = env(BlockEnv::<BaseEvmTypes> {
445                difficulty: U256::ONE,
446                prevrandao: mix_hash.into(),
447                ..Default::default()
448            });
449
450            apply_chain_and_block_specific_env_changes_for_chain::<AnyNetwork, _>(
451                &mut evm_env,
452                &block,
453                chain as u64,
454                NetworkConfigs::default(),
455            );
456
457            assert_eq!(
458                evm_env.block.prevrandao,
459                U256::ONE,
460                "{chain:?} should expose `difficulty` as `PREVRANDAO`"
461            );
462        }
463    }
464
465    #[test]
466    fn tx_replay_env_changes_relax_fee_checks_per_source_chain() {
467        let mut evm_env = env(BlockEnv::<BaseEvmTypes>::default());
468        evm_env.set_chain_id(NamedChain::Mainnet as u64);
469        assert!(evm_env.version.feature(EvmFeatures::PRIORITY_FEE_CHECK));
470
471        apply_chain_specific_tx_replay_env_changes_for_chain(
472            &mut evm_env,
473            NamedChain::Arbitrum as u64,
474        );
475        assert_eq!(evm_env.chain_id(), NamedChain::Mainnet as u64);
476        assert!(!evm_env.version.feature(EvmFeatures::PRIORITY_FEE_CHECK));
477
478        evm_env.set_feature(EvmFeatures::PRIORITY_FEE_CHECK, true);
479        apply_chain_specific_tx_replay_env_changes_for_chain(
480            &mut evm_env,
481            NamedChain::Mainnet as u64,
482        );
483        assert!(evm_env.version.feature(EvmFeatures::PRIORITY_FEE_CHECK));
484        assert!(evm_env.version.feature(EvmFeatures::BASE_FEE_CHECK));
485
486        apply_chain_specific_tx_replay_env_changes_for_chain(&mut evm_env, NamedChain::Celo as u64);
487        assert!(!evm_env.version.feature(EvmFeatures::BASE_FEE_CHECK));
488        assert!(evm_env.version.feature(EvmFeatures::PRIORITY_FEE_CHECK));
489    }
490
491    #[test]
492    fn blob_params_by_spec_id_tracks_latest_known_blob_schedule() {
493        assert_eq!(get_blob_params_by_spec_id(SpecId::CANCUN), BlobParams::cancun());
494        assert_eq!(get_blob_params_by_spec_id(SpecId::PRAGUE), BlobParams::prague());
495        assert_eq!(get_blob_params_by_spec_id(SpecId::OSAKA), BlobParams::osaka());
496        assert_eq!(get_blob_params_by_spec_id(SpecId::AMSTERDAM), BlobParams::bpo2());
497        assert_eq!(
498            get_blob_base_fee_update_fraction_by_spec_id(SpecId::AMSTERDAM),
499            BlobParams::bpo2().update_fraction as u64
500        );
501    }
502
503    #[test]
504    fn blob_params_by_explicit_hardfork() {
505        for (hardfork, expected) in [
506            (EthereumHardfork::Cancun, BlobParams::cancun()),
507            (EthereumHardfork::Prague, BlobParams::prague()),
508            (EthereumHardfork::Osaka, BlobParams::osaka()),
509            (EthereumHardfork::Bpo1, BlobParams::bpo1()),
510            (EthereumHardfork::Bpo2, BlobParams::bpo2()),
511            (EthereumHardfork::Amsterdam, BlobParams::bpo2()),
512        ] {
513            assert_eq!(get_blob_params_by_hardfork(hardfork.into()), expected);
514        }
515    }
516}