Skip to main content

foundry_evm_core/evm/
tempo.rs

1//! Tempo execution integration.
2
3use super::{
4    EvmEnv, FoundryEvmExt, FoundryEvmFactory, FoundryEvmNetwork, FoundryExecutionHooks,
5    FoundryTxConversion, FoundryTxResultExt, SendableExt, TransactionRequestFor, TxEnvelopeFor,
6    TxPayload, placeholder_signature,
7};
8use crate::{
9    constants::{CALLER, SYSTEM_PRECOMPILE_STUB, TEST_CONTRACT_ADDRESS},
10    edgecov,
11    tempo::{PATH_USD_ADDRESS, initialize_tempo_test_genesis_inner},
12};
13use alloy_consensus::{SignableTransaction, transaction::Recovered};
14use alloy_eips::Typed2718;
15use alloy_network::{
16    AnyRpcTransaction, AnyTxEnvelope, NetworkTransactionBuilder, TransactionBuilder,
17};
18use alloy_primitives::{Address, Bytes};
19use evm2::{
20    Evm, EvmConfig, ExecutionConfig, OpcodeConfig, SpecId, TxResult, Version,
21    evm::precompile::PrecompileProvider, registry::TxRegistry,
22};
23use foundry_evm_networks::TEMPO_PRECOMPILE_ADDRESSES;
24use std::sync::Arc;
25use tempo_alloy::{TempoNetwork, primitives::TEMPO_TX_TYPE_ID};
26use tempo_evm::{
27    TempoEvmExt, TempoEvmFactory, TempoEvmTypes, TempoTx, TempoTxEnv, TempoTxResultExt,
28    tempo_execution_config, tempo_opcode_config, tempo_tx_registry,
29};
30use tempo_hardfork::TempoHardfork;
31use tempo_precompiles::{
32    TempoPrecompiles,
33    storage::{StorageActions, StorageCtx},
34};
35
36/// Tempo EVM network.
37#[derive(Clone, Copy, Debug, Default)]
38pub struct TempoEvmNetwork;
39
40/// Tempo envelope of Foundry's RPC types.
41type TempoNetworkTxEnvelope = TxEnvelopeFor<TempoEvmNetwork>;
42
43impl FoundryEvmExt<TempoTxEnv> for TempoEvmExt {
44    fn resume_context(&mut self, _ext: Self) {
45        // Tempo has no context state: the EVM kind, fee manager and pool flags are the same in
46        // every context, and the resolved fee token, key expiry, storage actions and
47        // non-creditable slots belong to the running transaction, the last two shared with its
48        // precompiles.
49    }
50}
51
52// SAFETY: `detached` allocates fresh transaction-local state instead of cloning or reading the
53// `Rc` handles; every other field is `Send + Sync`.
54unsafe impl SendableExt for TempoEvmExt {
55    fn detached(&self) -> Self {
56        Self {
57            fee_manager: Arc::clone(&self.fee_manager),
58            actions: if self.actions.is_enabled() {
59                StorageActions::enabled()
60            } else {
61                StorageActions::disabled()
62            },
63            skip_valid_after_check: self.skip_valid_after_check,
64            skip_liquidity_check: self.skip_liquidity_check,
65            resolved_fee_token: self.resolved_fee_token,
66            key_expiry: self.key_expiry,
67            ..Self::default()
68        }
69    }
70}
71
72impl FoundryTxResultExt for TempoTxResultExt {}
73
74impl FoundryEvmNetwork for TempoEvmNetwork {
75    type Network = TempoNetwork;
76    type EvmFactory = TempoEvmFactory;
77}
78
79impl FoundryExecutionHooks for TempoEvmTypes {
80    fn tx_call_depth_offset(tx: &TempoTxEnv) -> u16 {
81        u16::from(tx.is_aa())
82    }
83}
84
85impl FoundryTxConversion<TempoNetwork> for TempoEvmTypes {
86    fn evm_tx(
87        envelope: TempoNetworkTxEnvelope,
88        sender: Address,
89        payload: TxPayload,
90    ) -> eyre::Result<Recovered<TempoTxEnv>> {
91        tempo_tx(envelope, sender, payload, None)
92    }
93
94    fn tx_from_request(
95        request: TransactionRequestFor<TempoEvmNetwork>,
96    ) -> eyre::Result<Recovered<TempoTxEnv>> {
97        let sender =
98            request.from().ok_or_else(|| eyre::eyre!("transaction request has no sender"))?;
99        // The access key only prices simulations; the signed envelope carries its own key.
100        let key_id = request.key_id;
101        let unsigned =
102            request.build_unsigned().map_err(|err| eyre::eyre!(err.error.to_string()))?;
103        let envelope = TempoNetworkTxEnvelope::from(unsigned.into_signed(placeholder_signature()));
104        tempo_tx(envelope, sender, TxPayload::Simulated, key_id)
105    }
106
107    fn envelope_from_any_rpc(tx: &AnyRpcTransaction) -> eyre::Result<TempoNetworkTxEnvelope> {
108        match &*tx.inner.inner {
109            AnyTxEnvelope::Ethereum(envelope) => TempoNetworkTxEnvelope::try_from(envelope.clone())
110                .map_err(|_| super::unknown_transaction_type(tx, "TempoTxEnv")),
111            AnyTxEnvelope::Unknown(unknown) if unknown.ty() == TEMPO_TX_TYPE_ID => {
112                // Tempo AA transactions only deserialize through Tempo's own envelope.
113                let rpc_tx = serde_json::from_value::<
114                    alloy_rpc_types::Transaction<TempoNetworkTxEnvelope>,
115                >(serde_json::to_value(tx)?)
116                .map_err(|err| eyre::eyre!("cannot decode Tempo AA transaction: {err}"))?;
117                Ok(rpc_tx.inner.into_inner())
118            }
119            AnyTxEnvelope::Unknown(_) => Err(super::unknown_transaction_type(tx, "TempoTxEnv")),
120        }
121    }
122}
123
124/// Converts a Tempo network envelope into Tempo's evm2 transaction.
125fn tempo_tx(
126    envelope: TempoNetworkTxEnvelope,
127    sender: Address,
128    payload: TxPayload,
129    key_id: Option<Address>,
130) -> eyre::Result<Recovered<TempoTxEnv>> {
131    let mut tx = TempoTxEnv::from(Recovered::new_unchecked(envelope, sender));
132    if payload.is_simulated() {
133        let id = tx.unique_tx_identifier();
134        tx = tx.with_simulation_overrides(id, None, key_id);
135    }
136    Ok(Recovered::new_unchecked(tx, sender))
137}
138
139impl FoundryEvmFactory for TempoEvmFactory {
140    type Types = TempoEvmTypes;
141
142    fn version(&self, spec: TempoHardfork, chain_id: u64) -> Version {
143        let mut version = *tempo_execution_config(spec, chain_id).version();
144        // Match Tempo's node: the execution config keeps Ethereum's cap, and Tempo raises it.
145        version.tx_gas_limit_cap = spec.tx_gas_limit_cap().unwrap_or(u64::MAX);
146        version
147    }
148
149    fn execution_config(
150        &self,
151        spec: TempoHardfork,
152        version: Version,
153    ) -> ExecutionConfig<TempoEvmTypes> {
154        evm2::spec_to_generic!(SpecId::from(spec), |BASE_SPEC_ID| ExecutionConfig::for_config::<
155            InstrumentedTempoConfig<BASE_SPEC_ID>,
156        >()
157        .with_version(version))
158    }
159
160    fn tx_registry(
161        &self,
162        spec: TempoHardfork,
163    ) -> TxRegistry<TempoEvmTypes, TxResult<TempoEvmTypes>> {
164        tempo_tx_registry(spec.into())
165    }
166
167    fn precompiles(
168        &self,
169        env: &EvmEnv<TempoEvmTypes>,
170        ext: &TempoEvmExt,
171    ) -> Box<dyn PrecompileProvider<TempoEvmTypes>> {
172        Box::new(TempoPrecompiles::new(
173            env.spec,
174            ext.actions.clone(),
175            ext.non_creditable_slots.clone(),
176        ))
177    }
178
179    fn initialize_evm(&self, evm: &mut Evm<'_, TempoEvmTypes>, is_forked: bool) {
180        let result = StorageCtx::enter_evm(evm, || {
181            if is_forked {
182                let mut ctx = StorageCtx;
183                // Precompiles have no on-chain bytecode; seed sentinels so forks do not refetch
184                // them. Failed loads are retried, and surface, on later access.
185                for address in TEMPO_PRECOMPILE_ADDRESSES.iter().chain([&PATH_USD_ADDRESS]) {
186                    let _ = ctx.set_code(*address, Bytes::from_static(SYSTEM_PRECOMPILE_STUB));
187                }
188                Ok(())
189            } else {
190                initialize_tempo_test_genesis_inner(TEST_CONTRACT_ADDRESS, CALLER)
191            }
192        });
193        result.expect("tempo genesis initialization failed");
194        evm.state_mut().commit_transaction();
195    }
196}
197
198/// Tempo's opcode table of `BASE_SPEC_ID` with the [`edgecov`] instrumentation opcodes.
199struct InstrumentedTempoConfig<const BASE_SPEC_ID: u32>;
200
201impl<const BASE_SPEC_ID: u32> EvmConfig<TempoEvmTypes> for InstrumentedTempoConfig<BASE_SPEC_ID> {
202    const BASE_SPEC_ID: SpecId =
203        SpecId::try_from_u32(BASE_SPEC_ID).expect("invalid Tempo base spec id");
204    const OPCODE_CONFIG: &'static OpcodeConfig<TempoEvmTypes> =
205        &edgecov::with_instrumentation(tempo_opcode_config::<BASE_SPEC_ID>());
206}