Skip to main content

foundry_evm_core/evm/
base.rs

1//! Base on evm2, using `base-evm2`.
2
3use super::{
4    EvmEnv, FoundryDatabase, FoundryEvmExt, FoundryEvmFactory, FoundryEvmNetwork,
5    FoundryExecutionHooks, FoundryTxConversion, FoundryTxResultExt, SendableExt, TxPayload,
6    with_eip7702_delegations,
7};
8use crate::{constants::SYSTEM_PRECOMPILE_STUB, edgecov};
9use alloy_consensus::transaction::Recovered;
10use alloy_network::AnyRpcTransaction;
11use alloy_primitives::{Address, Bytes};
12use base_common_network::Base;
13use base_evm2::{
14    BaseEvmExt, BaseEvmFactory, BaseEvmTypes, BaseSpecId, BaseTxEnvelope, BaseTxResultExt,
15    base_tx_registry, base_version, precompiles::activation_admin_address_for_upgrade_by_chain_id,
16};
17use evm2::{
18    Evm, ExecutionConfig, TxResult, Version, bytecode::Bytecode,
19    evm::precompile::PrecompileProvider, registry::TxRegistry,
20};
21use foundry_evm_networks::{BASE_CODE_SENTINEL_ADDRESSES, is_base_precompile_active_at};
22
23/// Base EVM network.
24#[derive(Clone, Copy, Debug, Default)]
25pub struct BaseEvmNetwork;
26
27// SAFETY: `BaseEvmExt` is `Send + Sync`, as asserted below, so clones share only thread-safe state.
28unsafe impl SendableExt for BaseEvmExt {}
29
30const _: fn() = || {
31    const fn assert_send_sync<T: Send + Sync>() {}
32    assert_send_sync::<BaseEvmExt>();
33};
34
35impl FoundryEvmExt<BaseTxEnvelope> for BaseEvmExt {
36    fn replace_while_executing(&mut self, ext: Self) {
37        // Only the block-level L1 info comes from `ext`; everything else, including the cached L1
38        // cost, describes the running transaction.
39        let tx_l1_cost = self.l1_block_info.tx_l1_cost;
40        self.l1_block_info = ext.l1_block_info;
41        self.l1_block_info.tx_l1_cost = tx_l1_cost;
42    }
43}
44
45impl FoundryTxResultExt for BaseTxResultExt {
46    fn is_failed_deposit(&self) -> bool {
47        self.failed_deposit
48    }
49
50    fn eip8130_committed_phases(&self) -> Option<u64> {
51        self.eip8130_committed_phases
52    }
53}
54
55impl FoundryEvmNetwork for BaseEvmNetwork {
56    type Network = Base;
57    type EvmFactory = BaseEvmFactory;
58}
59
60impl FoundryExecutionHooks for BaseEvmTypes {}
61
62impl FoundryTxConversion<Base> for BaseEvmTypes {
63    fn evm_tx(
64        envelope: base_common_consensus::BaseTxEnvelope,
65        sender: Address,
66        payload: TxPayload,
67    ) -> eyre::Result<Recovered<BaseTxEnvelope>> {
68        let mut tx = BaseTxEnvelope::from(envelope);
69        // The L1 data and operator fees are priced over the signed encoding; simulations of
70        // unsigned requests price them at zero, like `eth_call`. An EIP-8130 simulation carries
71        // placeholder authentication, so it runs without signature checks, nonce advancement or
72        // fee settlement, as the sender's self-actor unless a caller supplies an actor hint.
73        if payload.is_simulated() {
74            tx.set_enveloped(Bytes::new());
75            tx.set_eip8130_simulation(None);
76        }
77        Ok(tx.with_signer(sender))
78    }
79
80    fn envelope_from_any_rpc(
81        tx: &AnyRpcTransaction,
82    ) -> eyre::Result<base_common_consensus::BaseTxEnvelope> {
83        if let Ok(envelope) = base_common_consensus::BaseTxEnvelope::try_from(tx.clone()) {
84            return Ok(envelope);
85        }
86        // EIP-8130 envelopes only deserialize through Base's own RPC transaction type.
87        let rpc_tx =
88            serde_json::from_value::<base_common_rpc_types::Transaction>(serde_json::to_value(tx)?)
89                .map_err(|err| super::unknown_transaction_type(tx, "Base").wrap_err(err))?;
90        Ok(rpc_tx.inner.into_inner())
91    }
92}
93
94impl FoundryEvmFactory for BaseEvmFactory {
95    type Types = BaseEvmTypes;
96
97    fn version(&self, spec: BaseSpecId, chain_id: u64) -> Version {
98        with_eip7702_delegations(base_version(spec, chain_id))
99    }
100
101    fn execution_config(
102        &self,
103        spec: BaseSpecId,
104        version: Version,
105    ) -> ExecutionConfig<BaseEvmTypes> {
106        edgecov::execution_config(spec, version)
107    }
108
109    fn tx_registry(&self, spec: BaseSpecId) -> TxRegistry<BaseEvmTypes, TxResult<BaseEvmTypes>> {
110        base_tx_registry(spec)
111    }
112
113    fn precompiles(
114        &self,
115        env: &EvmEnv<BaseEvmTypes>,
116        _ext: &BaseEvmExt,
117    ) -> Box<dyn PrecompileProvider<BaseEvmTypes>> {
118        Box::new(Self::precompiles(self, env.spec))
119    }
120
121    fn configure_for<D: FoundryDatabase + ?Sized>(
122        &self,
123        db: &D,
124        env: &EvmEnv<BaseEvmTypes>,
125    ) -> Self {
126        // Nested EVMs share the fork database, so execution chain-ID overrides must not change the
127        // source chain's activation registry admin.
128        let chain_id = db.active_fork_source_chain_id().unwrap_or(env.chain_id());
129        let admin = self.activation_admin_address().or_else(|| {
130            activation_admin_address_for_upgrade_by_chain_id(chain_id, env.spec.upgrade())
131        });
132        self.clone().with_activation_admin_address(admin)
133    }
134
135    fn initialize_evm(&self, evm: &mut Evm<'_, BaseEvmTypes>, _is_forked: bool) {
136        // Base plants a one-byte sentinel on code-less stateful precompiles, so Solidity's
137        // `extcodesize` check on high-level calls passes. Existing code, including fork code, wins.
138        let upgrade = evm.config_spec_id().upgrade();
139        let sentinel = Bytecode::new_legacy(Bytes::from_static(SYSTEM_PRECOMPILE_STUB));
140        for address in BASE_CODE_SENTINEL_ADDRESSES
141            .iter()
142            .filter(|address| is_base_precompile_active_at(**address, upgrade))
143        {
144            if let Ok(mut account) = evm.state_mut().account(address)
145                && account.is_empty_code_hash()
146            {
147                account.set_code_slow(sentinel.clone());
148            }
149        }
150        evm.state_mut().commit_transaction();
151    }
152}