Skip to main content

foundry_evm_networks/
lib.rs

1//! # foundry-evm-networks
2//!
3//! Runtime selection and shared configuration for Foundry's EVM network families.
4//!
5//! [`NetworkConfigs`] describes the active execution profile selected by configuration, CLI flags,
6//! hardforks, or fork endpoint discovery. Cargo features only determine which optional
7//! [`NetworkVariant`] values are compiled into a binary; they do not select a network at runtime.
8//!
9//! Concrete Alloy network and EVM factory types are associated by `FoundryEvmNetwork` in
10//! `foundry-evm-core`. See the [custom EVM integration guide] for the cross-crate ownership and
11//! state-lifecycle contract.
12//!
13//! [custom EVM integration guide]: https://github.com/foundry-rs/foundry/blob/master/docs/dev/networks.md
14
15use crate::celo::transfer::{CELO_TRANSFER_ADDRESS, CELO_TRANSFER_PRECOMPILE_NAME};
16use alloy_chains::{
17    Chain, NamedChain,
18    NamedChain::{Chiado, Gnosis, Moonbase, Moonbeam, MoonbeamDev, Moonriver, Rsk, RskTestnet},
19};
20use alloy_eips::{eip1559::BaseFeeParams, eip7840::BlobParams};
21use alloy_primitives::{Address, ChainId, address, map::AddressHashMap};
22use clap::Parser;
23use foundry_evm_hardforks::{
24    EthereumHardfork, ExecutionSpec, FoundryHardfork, TempoHardfork, latest_active_tempo_hardfork,
25};
26use serde::{Deserialize, Serialize, ser::SerializeStruct};
27use std::collections::BTreeMap;
28use tempo_contracts::precompiles::{
29    ACCOUNT_KEYCHAIN_ADDRESS, ADDRESS_REGISTRY_ADDRESS, CONFIGURABLE_ACCOUNT_ADDRESS,
30    CURRENT_COMMITTEE_ADDRESS, NONCE_PRECOMPILE_ADDRESS, RECEIVE_POLICY_GUARD_ADDRESS,
31    SIGNATURE_VERIFIER_ADDRESS, STABLECOIN_DEX_ADDRESS, STORAGE_CREDITS_ADDRESS,
32    TIP_FEE_MANAGER_ADDRESS, TIP20_CHANNEL_RESERVE_ADDRESS, TIP20_FACTORY_ADDRESS,
33    TIP403_REGISTRY_ADDRESS, VALIDATOR_CONFIG_ADDRESS, VALIDATOR_CONFIG_V2_ADDRESS,
34};
35
36#[cfg(feature = "base")]
37use base_common_base_tx::NonceManagerSlots;
38#[cfg(feature = "base")]
39use base_evm2::precompiles::{
40    ACTIVATION_REGISTRY_ADDRESS, B20_FACTORY_ADDRESS, POLICY_REGISTRY_ADDRESS, TX_CONTEXT_ADDRESS,
41};
42#[cfg(feature = "base")]
43use foundry_evm_hardforks::BaseUpgrade;
44
45#[cfg(feature = "optimism")]
46use foundry_evm_hardforks::OpHardfork;
47
48#[cfg(feature = "monad")]
49use foundry_evm_hardforks::MonadHardfork;
50
51/// The Monad cheatcode handler address.
52pub const MONAD_CHEATCODE_ADDRESS: Address = address!("0xc0FFeeCD43A10e1C2b0De63c6CDCFe5B7d0e0CEA");
53
54pub mod arbitrum;
55pub mod celo;
56
57#[cfg(feature = "optimism")]
58mod optimism;
59
60/// Labels of all well-known Tempo precompiles, keyed by address.
61pub const TEMPO_PRECOMPILES: &[(&str, Address)] = &[
62    ("Nonce", NONCE_PRECOMPILE_ADDRESS),
63    ("StablecoinDex", STABLECOIN_DEX_ADDRESS),
64    ("TIP20Factory", TIP20_FACTORY_ADDRESS),
65    ("TIP403Registry", TIP403_REGISTRY_ADDRESS),
66    ("FeeManager", TIP_FEE_MANAGER_ADDRESS),
67    ("ValidatorConfig", VALIDATOR_CONFIG_ADDRESS),
68    ("ValidatorConfigV2", VALIDATOR_CONFIG_V2_ADDRESS),
69    ("AccountKeychain", ACCOUNT_KEYCHAIN_ADDRESS),
70    ("SignatureVerifier", SIGNATURE_VERIFIER_ADDRESS),
71    ("AddressRegistry", ADDRESS_REGISTRY_ADDRESS),
72    ("TIP20ChannelReserve", TIP20_CHANNEL_RESERVE_ADDRESS),
73    ("ReceivePolicyGuard", RECEIVE_POLICY_GUARD_ADDRESS),
74    ("StorageCredits", STORAGE_CREDITS_ADDRESS),
75    ("CurrentCommittee", CURRENT_COMMITTEE_ADDRESS),
76    ("ConfigurableAccount", CONFIGURABLE_ACCOUNT_ADDRESS),
77];
78
79#[cfg(feature = "monad")]
80const MONAD_PRECOMPILE_LABELS: &[(&str, Address)] = &[
81    ("Staking", monad_evm2::staking::STAKING_ADDRESS),
82    ("ReserveBalance", monad_evm2::reserve_balance::RESERVE_BALANCE_ADDRESS),
83];
84
85#[cfg(feature = "monad")]
86const MONAD_PRECOMPILES: &[(&str, Address)] = &[
87    ("MonadStaking", monad_evm2::staking::STAKING_ADDRESS),
88    ("MonadReserveBalance", monad_evm2::reserve_balance::RESERVE_BALANCE_ADDRESS),
89];
90
91#[cfg(feature = "base")]
92const BASE_PRECOMPILES: &[(&str, Address)] = &[
93    ("B20Factory", B20_FACTORY_ADDRESS),
94    ("ActivationRegistry", ACTIVATION_REGISTRY_ADDRESS),
95    ("PolicyRegistry", POLICY_REGISTRY_ADDRESS),
96    ("TxContext", TX_CONTEXT_ADDRESS),
97    ("NonceManager", NonceManagerSlots::ADDRESS),
98];
99
100/// Fixed Base precompiles that expose at least one function returning no data.
101///
102/// Solidity guards high-level calls to such functions with an `extcodesize` check, which a
103/// code-less account fails in the caller, so these must carry code. Base mainnet plants a one-byte
104/// sentinel on exactly these two. The factory, nonce manager, and transaction context return data
105/// from every function and are code-less on chain, so stubbing them would diverge — a contract
106/// guarding calls with an `isContract` probe would pass locally and revert on Base.
107///
108/// The nonce manager separately receives a stub at Everest from Base's own
109/// `ensure_base_tx_system_accounts` transition, for EIP-161 state clearing rather than for
110/// `extcodesize`. That transition owns it; this list must not.
111#[cfg(feature = "base")]
112pub const BASE_CODE_SENTINEL_ADDRESSES: &[Address] =
113    &[ACTIVATION_REGISTRY_ADDRESS, POLICY_REGISTRY_ADDRESS];
114
115/// All well-known Tempo precompile addresses.
116pub const TEMPO_PRECOMPILE_ADDRESSES: &[Address] = &{
117    let mut addresses = [Address::ZERO; TEMPO_PRECOMPILES.len()];
118    let mut i = 0;
119    while i < addresses.len() {
120        addresses[i] = TEMPO_PRECOMPILES[i].1;
121        i += 1;
122    }
123    addresses
124};
125
126#[derive(
127    Clone,
128    Copy,
129    Debug,
130    Default,
131    PartialEq,
132    Eq,
133    PartialOrd,
134    Ord,
135    Hash,
136    Serialize,
137    Deserialize,
138    clap::ValueEnum,
139)]
140#[serde(rename_all = "lowercase")]
141#[clap(rename_all = "lowercase")]
142pub enum NetworkVariant {
143    #[default]
144    Ethereum,
145    #[cfg(feature = "base")]
146    Base,
147    #[cfg(feature = "optimism")]
148    Optimism,
149    Tempo,
150    #[cfg(feature = "monad")]
151    Monad,
152}
153
154/// Runtime and initcode byte-size limits for a configured network.
155#[derive(Clone, Copy, Debug, PartialEq, Eq)]
156pub struct NetworkContractSizeLimits {
157    /// Maximum deployed runtime bytecode size.
158    pub runtime: usize,
159    /// Maximum initcode bytecode size.
160    pub initcode: usize,
161}
162
163impl std::str::FromStr for NetworkVariant {
164    type Err = String;
165
166    fn from_str(s: &str) -> Result<Self, Self::Err> {
167        match s {
168            "ethereum" => Ok(Self::Ethereum),
169            #[cfg(feature = "base")]
170            "base" => Ok(Self::Base),
171            #[cfg(feature = "optimism")]
172            "optimism" => Ok(Self::Optimism),
173            "tempo" => Ok(Self::Tempo),
174            #[cfg(feature = "monad")]
175            "monad" => Ok(Self::Monad),
176            _ => Err(format!("unknown network variant: {s}")),
177        }
178    }
179}
180
181impl NetworkVariant {
182    /// Returns the network family identified by a known chain ID.
183    ///
184    /// Unknown chain IDs return `None` so callers can consult endpoint metadata instead of
185    /// assuming Ethereum. If a known chain belongs to a feature-gated family that is not enabled,
186    /// this returns an error rather than silently selecting a different EVM.
187    pub fn from_known_chain_id(chain_id: ChainId) -> Result<Option<Self>, String> {
188        let chain = Chain::from_id(chain_id);
189        if chain.is_tempo() {
190            return Ok(Some(Self::Tempo));
191        }
192        if matches!(chain.named(), Some(NamedChain::Celo | NamedChain::CeloSepolia)) {
193            return Ok(Some(Self::Ethereum));
194        }
195        // Only claim Base when the feature is on. `is_optimism()` below already covers Base chain
196        // IDs, and that is what shipped binaries resolve them to today, so erroring here would
197        // regress builds that never asked for Base. Monad errors instead because no shipped EVM
198        // approximates it.
199        #[cfg(feature = "base")]
200        if matches!(chain.named(), Some(NamedChain::Base | NamedChain::BaseSepolia)) {
201            return Ok(Some(Self::Base));
202        }
203        if matches!(chain.named(), Some(NamedChain::Monad | NamedChain::MonadTestnet)) {
204            #[cfg(feature = "monad")]
205            return Ok(Some(Self::Monad));
206            #[cfg(not(feature = "monad"))]
207            return Err("network family `monad` is not enabled in this build".to_string());
208        }
209        if chain.is_optimism() {
210            #[cfg(feature = "optimism")]
211            return Ok(Some(Self::Optimism));
212            #[cfg(not(feature = "optimism"))]
213            return Err("network family `optimism` is not enabled in this build".to_string());
214        }
215        Ok(chain.named().map(|_| Self::Ethereum))
216    }
217
218    /// Parses an explicit network family reported by `anvil_nodeInfo`.
219    pub fn from_node_info_name(network: &str) -> Result<Self, String> {
220        match network {
221            "ethereum" => Ok(Self::Ethereum),
222            #[cfg(feature = "base")]
223            "base" => Ok(Self::Base),
224            #[cfg(not(feature = "base"))]
225            "base" => Err("network family `base` is not enabled in this build".to_string()),
226            #[cfg(feature = "optimism")]
227            "optimism" => Ok(Self::Optimism),
228            #[cfg(not(feature = "optimism"))]
229            "optimism" => Err("network family `optimism` is not enabled in this build".to_string()),
230            "tempo" => Ok(Self::Tempo),
231            #[cfg(feature = "monad")]
232            "monad" => Ok(Self::Monad),
233            #[cfg(not(feature = "monad"))]
234            "monad" => Err("network family `monad` is not enabled in this build".to_string()),
235            network => {
236                Err(format!("unsupported network family `{network}` reported by fork endpoint"))
237            }
238        }
239    }
240
241    /// Parses a hardfork name reported by an RPC endpoint in this network's namespace.
242    pub fn parse_hardfork(self, hardfork: &str) -> Result<FoundryHardfork, String> {
243        format!("{}:{hardfork}", self.name()).parse()
244    }
245
246    /// Returns this network's hardfork at a historical source-chain timestamp.
247    ///
248    /// Unknown source chains return `None`; the selected network owns the lookup so a chain ID
249    /// shared by multiple execution families cannot select another family's hardfork.
250    pub fn historical_hardfork(self, chain_id: ChainId, timestamp: u64) -> Option<FoundryHardfork> {
251        match self {
252            Self::Ethereum => {
253                EthereumHardfork::from_chain_and_timestamp(Chain::from_id(chain_id), timestamp)
254                    .map(Into::into)
255            }
256            Self::Tempo => {
257                TempoHardfork::from_chain_and_timestamp(chain_id, timestamp).map(Into::into)
258            }
259            #[cfg(feature = "optimism")]
260            Self::Optimism => {
261                OpHardfork::from_chain_and_timestamp(Chain::from_id(chain_id), timestamp)
262                    .map(Into::into)
263            }
264            #[cfg(feature = "monad")]
265            Self::Monad => {
266                MonadHardfork::from_chain_and_timestamp(chain_id, timestamp).map(Into::into)
267            }
268            #[cfg(feature = "base")]
269            Self::Base => {
270                BaseUpgrade::from_chain_and_timestamp(chain_id, timestamp).map(Into::into)
271            }
272        }
273    }
274
275    /// Returns the active hardfork for this network at the given chain and timestamp.
276    ///
277    /// Unknown chain IDs fall back to the network's default hardfork. The selected network owns
278    /// the lookup so an explicit network choice is not overridden by the chain ID's family.
279    pub fn hardfork_at(self, chain_id: ChainId, timestamp: u64) -> FoundryHardfork {
280        self.historical_hardfork(chain_id, timestamp).unwrap_or_else(|| match self {
281            Self::Ethereum => EthereumHardfork::default().into(),
282            Self::Tempo => latest_active_tempo_hardfork().into(),
283            #[cfg(feature = "optimism")]
284            Self::Optimism => OpHardfork::default().into(),
285            #[cfg(feature = "monad")]
286            Self::Monad => MonadHardfork::default().into(),
287            #[cfg(feature = "base")]
288            Self::Base => BaseUpgrade::default().into(),
289        })
290    }
291
292    /// Returns `true` if this is the Ethereum network variant.
293    pub const fn is_ethereum(&self) -> bool {
294        matches!(self, Self::Ethereum)
295    }
296
297    /// Returns `true` if this is the Base network variant.
298    #[cfg(feature = "base")]
299    pub const fn is_base(&self) -> bool {
300        matches!(self, Self::Base)
301    }
302
303    /// Returns `true` if this is the Optimism network variant.
304    pub const fn is_optimism(&self) -> bool {
305        #[cfg(feature = "optimism")]
306        {
307            matches!(self, Self::Optimism)
308        }
309        #[cfg(not(feature = "optimism"))]
310        {
311            false
312        }
313    }
314
315    /// Returns `true` if this is the Tempo network variant.
316    pub const fn is_tempo(&self) -> bool {
317        matches!(self, Self::Tempo)
318    }
319
320    /// Returns `true` if this is the Monad network variant.
321    #[cfg(feature = "monad")]
322    pub const fn is_monad(&self) -> bool {
323        matches!(self, Self::Monad)
324    }
325
326    /// Returns `false` when Monad support is not compiled in.
327    #[cfg(not(feature = "monad"))]
328    pub const fn is_monad(&self) -> bool {
329        false
330    }
331
332    /// Returns the network variant name.
333    pub const fn name(&self) -> &'static str {
334        match self {
335            Self::Ethereum => "ethereum",
336            #[cfg(feature = "base")]
337            Self::Base => "base",
338            #[cfg(feature = "optimism")]
339            Self::Optimism => "optimism",
340            Self::Tempo => "tempo",
341            #[cfg(feature = "monad")]
342            Self::Monad => "monad",
343        }
344    }
345
346    /// Returns the hardfork namespace used by this network family.
347    pub const fn hardfork_namespace(&self) -> Option<&'static str> {
348        match self {
349            Self::Ethereum => None,
350            #[cfg(feature = "base")]
351            Self::Base => Some("base"),
352            #[cfg(feature = "optimism")]
353            Self::Optimism => Some("optimism"),
354            Self::Tempo => Some("tempo"),
355            #[cfg(feature = "monad")]
356            Self::Monad => Some("monad"),
357        }
358    }
359}
360
361impl std::fmt::Display for NetworkVariant {
362    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
363        f.write_str(self.name())
364    }
365}
366
367impl From<ChainId> for NetworkVariant {
368    fn from(chain_id: ChainId) -> Self {
369        Self::from_known_chain_id(chain_id).ok().flatten().unwrap_or(Self::Ethereum)
370    }
371}
372
373#[derive(Clone, Debug, Default, Parser, Deserialize, Copy, PartialEq, Eq, Hash)]
374pub struct NetworkConfigs {
375    /// Enable a specific network family.
376    #[arg(help_heading = "Networks", long, short, num_args = 1, value_name = "NETWORK", value_enum, conflicts_with_all = ["celo", "tempo"])]
377    #[cfg_attr(feature = "optimism", arg(conflicts_with = "optimism"))]
378    #[cfg_attr(feature = "monad", arg(conflicts_with = "monad"))]
379    #[serde(default)]
380    pub(crate) network: Option<NetworkVariant>,
381    /// Enable Celo network features.
382    #[arg(help_heading = "Networks", long, conflicts_with_all = ["network", "tempo"])]
383    #[cfg_attr(feature = "optimism", arg(conflicts_with = "optimism"))]
384    #[cfg_attr(feature = "monad", arg(conflicts_with = "monad"))]
385    celo: bool,
386    /// Enable Optimism network features (deprecated: use --network optimism).
387    #[cfg(feature = "optimism")]
388    #[arg(long, hide = true, conflicts_with_all = ["network", "celo", "tempo"])]
389    #[cfg_attr(feature = "monad", arg(conflicts_with = "monad"))]
390    // Deserialize-only legacy alias: accepted in foundry.toml but never serialized — the
391    // canonical form is `network = "optimism"`.
392    #[serde(default)]
393    pub(crate) optimism: bool,
394    /// Enable Tempo network features (deprecated: use --network tempo).
395    #[arg(long, hide = true, conflicts_with_all = ["network", "celo"])]
396    #[cfg_attr(feature = "optimism", arg(conflicts_with = "optimism"))]
397    #[cfg_attr(feature = "monad", arg(conflicts_with = "monad"))]
398    // Deserialize-only legacy alias: accepted in foundry.toml but never serialized — the
399    // canonical form is `network = "tempo"`.
400    #[serde(default)]
401    tempo: bool,
402    /// Enable Monad network features (deprecated: use --network monad).
403    #[cfg(feature = "monad")]
404    #[arg(long, hide = true, conflicts_with_all = ["network", "celo", "tempo"])]
405    #[cfg_attr(feature = "optimism", arg(conflicts_with = "optimism"))]
406    // Deserialize-only legacy alias: accepted in foundry.toml but never serialized - the
407    // canonical form is `network = "monad"`.
408    #[serde(default)]
409    monad: bool,
410    /// Whether to bypass prevrandao.
411    #[arg(skip)]
412    #[serde(default)]
413    bypass_prevrandao: bool,
414}
415
416// Custom `Serialize` impl: always emits the *resolved* network as the canonical
417// `network = "..."` field, and never emits legacy network aliases. This avoids contradictory
418// canonical and legacy selectors, and ensures old foundry.toml keys round-trip canonically.
419impl Serialize for NetworkConfigs {
420    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
421        let mut s = serializer.serialize_struct("NetworkConfigs", 3)?;
422        s.serialize_field("network", &self.resolved_network())?;
423        s.serialize_field("celo", &self.celo)?;
424        s.serialize_field("bypass_prevrandao", &self.bypass_prevrandao)?;
425        s.end()
426    }
427}
428
429impl NetworkConfigs {
430    /// Validates that all configured network selectors resolve to the same execution profile.
431    ///
432    /// Canonical and legacy selectors for the same family remain compatible. Selectors for
433    /// different families are rejected instead of being silently resolved by field priority.
434    pub fn validate(&self) -> Result<(), String> {
435        let mut selectors = Vec::new();
436        if let Some(network) = self.network {
437            selectors.push((network.name(), format!("network = \"{}\"", network.name())));
438        }
439        if self.celo {
440            selectors.push(("celo", "celo = true".to_string()));
441        }
442        #[cfg(feature = "optimism")]
443        if self.optimism {
444            selectors.push(("optimism", "optimism = true".to_string()));
445        }
446        if self.tempo {
447            selectors.push(("tempo", "tempo = true".to_string()));
448        }
449        #[cfg(feature = "monad")]
450        if self.monad {
451            selectors.push(("monad", "monad = true".to_string()));
452        }
453
454        if let Some((family, selector)) = selectors.first()
455            && let Some((_, conflicting)) =
456                selectors.iter().find(|(candidate, _)| candidate != family)
457        {
458            return Err(format!(
459                "network selectors `{selector}` and `{conflicting}` conflict; select only one \
460                 network"
461            ));
462        }
463
464        Ok(())
465    }
466
467    pub fn with_ethereum() -> Self {
468        Self { network: Some(NetworkVariant::Ethereum), ..Default::default() }
469    }
470
471    pub fn with_celo() -> Self {
472        Self { celo: true, ..Default::default() }
473    }
474
475    pub fn with_tempo() -> Self {
476        Self { network: Some(NetworkVariant::Tempo), tempo: true, ..Default::default() }
477    }
478
479    #[cfg(feature = "monad")]
480    pub fn with_monad() -> Self {
481        Self { network: Some(NetworkVariant::Monad), monad: true, ..Default::default() }
482    }
483
484    #[cfg(feature = "base")]
485    pub fn with_base() -> Self {
486        Self { network: Some(NetworkVariant::Base), ..Default::default() }
487    }
488
489    pub const fn is_tempo(&self) -> bool {
490        if let Some(network) = self.resolved_network() { network.is_tempo() } else { false }
491    }
492
493    /// Returns whether Optimism network features are enabled.
494    ///
495    /// Always returns `false` when built without the `optimism` feature.
496    pub const fn is_optimism(&self) -> bool {
497        if let Some(network) = self.resolved_network() { network.is_optimism() } else { false }
498    }
499
500    #[cfg(feature = "monad")]
501    pub const fn is_monad(&self) -> bool {
502        if let Some(network) = self.resolved_network() { network.is_monad() } else { false }
503    }
504
505    #[cfg(not(feature = "monad"))]
506    pub const fn is_monad(&self) -> bool {
507        false
508    }
509
510    #[cfg(feature = "base")]
511    pub const fn is_base(&self) -> bool {
512        matches!(self.resolved_network(), Some(NetworkVariant::Base))
513    }
514
515    /// Coerces `hardfork` into this network's family.
516    ///
517    /// Execution and fee rules apply the same lossy `From` conversions, so a cross-namespace
518    /// override such as `--hardfork prague` on a Tempo node runs as a Tempo hardfork. Callers that
519    /// need to describe what actually executed, like trace decoding, go through here rather than
520    /// carrying the configured value.
521    pub fn executed_hardfork(&self, hardfork: FoundryHardfork) -> FoundryHardfork {
522        if self.is_tempo() {
523            return TempoHardfork::from(hardfork).into();
524        }
525        #[cfg(feature = "monad")]
526        if self.is_monad() {
527            return MonadHardfork::from(hardfork).into();
528        }
529        #[cfg(feature = "base")]
530        if self.is_base() {
531            return BaseUpgrade::from(hardfork).into();
532        }
533        hardfork
534    }
535
536    pub const fn is_celo(&self) -> bool {
537        self.celo
538    }
539
540    /// Returns the resolved network variant, folding legacy flags.
541    pub const fn resolved_network(&self) -> Option<NetworkVariant> {
542        if let Some(n) = self.network {
543            return Some(n);
544        }
545        #[cfg(feature = "optimism")]
546        if self.optimism {
547            return Some(NetworkVariant::Optimism);
548        }
549        if self.tempo {
550            return Some(NetworkVariant::Tempo);
551        }
552        #[cfg(feature = "monad")]
553        if self.monad {
554            return Some(NetworkVariant::Monad);
555        }
556        None
557    }
558
559    /// Returns whether a network family was selected in this configuration.
560    pub const fn has_network_selection(&self) -> bool {
561        self.celo || self.resolved_network().is_some()
562    }
563
564    /// Returns the execution family represented by this configuration.
565    pub const fn execution_family_name(&self) -> &'static str {
566        self.execution_network().name()
567    }
568
569    /// Returns a label for the complete execution configuration.
570    pub const fn execution_profile_name(&self) -> &'static str {
571        if self.celo { "celo" } else { self.execution_family_name() }
572    }
573
574    /// Returns the concrete execution network, treating an unresolved configuration as Ethereum.
575    pub const fn execution_network(&self) -> NetworkVariant {
576        if let Some(network) = self.resolved_network() { network } else { NetworkVariant::Ethereum }
577    }
578
579    /// Returns whether both configurations can use the same instantiated EVM backend.
580    pub fn has_same_execution_profile(&self, other: &Self) -> bool {
581        self.celo == other.celo
582            && match (self.resolved_network(), other.resolved_network()) {
583                (Some(left), Some(right)) => left == right,
584                (Some(left), None) => left.is_ethereum(),
585                (None, Some(right)) => right.is_ethereum(),
586                (None, None) => true,
587            }
588    }
589
590    /// Returns whether this execution configuration can use `source` as a fork state source
591    /// without rebuilding the instantiated EVM.
592    ///
593    /// Monad uses a distinct EVM factory and instruction provider, so forks cannot cross the
594    /// Monad boundary. Base execution requires a Base source. Optimism execution requires an OP
595    /// Stack source for its fee accounting. Ethereum and Tempo can use OP Stack state sources
596    /// without switching engines.
597    pub const fn supports_fork_source(&self, source: &Self) -> bool {
598        match self.execution_network() {
599            #[cfg(feature = "base")]
600            NetworkVariant::Base => source.is_base(),
601            #[cfg(feature = "optimism")]
602            NetworkVariant::Optimism => match source.execution_network() {
603                NetworkVariant::Optimism => true,
604                #[cfg(feature = "base")]
605                NetworkVariant::Base => true,
606                _ => false,
607            },
608            #[cfg(feature = "monad")]
609            NetworkVariant::Monad => source.is_monad(),
610            _ => !source.is_monad(),
611        }
612    }
613
614    /// Returns the name of the currently active non-Ethereum network, or `None` for plain Ethereum.
615    pub fn active_network_name(&self) -> Option<&'static str> {
616        self.resolved_network().and_then(|network| network.hardfork_namespace())
617    }
618
619    /// Returns the base fee parameters for the configured network.
620    ///
621    /// For OP Stack networks, returns Canyon parameters if the Canyon hardfork is active at the
622    /// given timestamp, otherwise returns pre-Canyon parameters.
623    #[cfg_attr(
624        not(any(feature = "base", feature = "optimism")),
625        allow(clippy::missing_const_for_fn)
626    )]
627    pub fn base_fee_params(
628        &self,
629        #[cfg_attr(not(any(feature = "base", feature = "optimism")), allow(unused_variables))]
630        timestamp: u64,
631    ) -> BaseFeeParams {
632        #[cfg(feature = "base")]
633        if self.is_base() {
634            let canyon_active =
635                BaseUpgrade::from_chain_and_timestamp(NamedChain::Base as u64, timestamp)
636                    .is_some_and(|upgrade| upgrade >= BaseUpgrade::Canyon);
637            return if canyon_active {
638                BaseFeeParams::new(250, 6)
639            } else {
640                BaseFeeParams::new(50, 6)
641            };
642        }
643        #[cfg(feature = "optimism")]
644        if self.is_optimism() {
645            return self.op_base_fee_params(timestamp);
646        }
647        BaseFeeParams::ethereum()
648    }
649
650    /// Calculates the blob excess gas inherited by the next block.
651    ///
652    /// OP Stack headers use the blob fields for protocol metadata rather than EIP-4844 blobs, so
653    /// their excess blob gas remains zero. Other execution profiles use the configured Ethereum
654    /// blob schedule.
655    pub fn next_block_blob_excess_gas(
656        &self,
657        blob_params: BlobParams,
658        parent_excess_blob_gas: u64,
659        parent_blob_gas_used: u64,
660        parent_base_fee: u64,
661    ) -> u64 {
662        #[cfg(feature = "base")]
663        if self.is_base() {
664            return 0;
665        }
666        if self.is_optimism() {
667            return 0;
668        }
669        blob_params.next_block_excess_blob_gas_osaka(
670            parent_excess_blob_gas,
671            parent_blob_gas_used,
672            parent_base_fee,
673        )
674    }
675
676    /// Returns contract size limits for networks that override Ethereum defaults.
677    #[cfg(feature = "monad")]
678    pub fn contract_size_limits(&self) -> Option<NetworkContractSizeLimits> {
679        self.is_monad().then_some(NetworkContractSizeLimits {
680            runtime: monad_evm2::MONAD_MAX_CODE_SIZE,
681            initcode: monad_evm2::MONAD_MAX_INITCODE_SIZE,
682        })
683    }
684
685    /// Returns contract size limits for networks that override Ethereum defaults.
686    #[cfg(not(feature = "monad"))]
687    pub const fn contract_size_limits(&self) -> Option<NetworkContractSizeLimits> {
688        None
689    }
690
691    pub fn bypass_prevrandao(&self, chain_id: u64) -> bool {
692        if let Ok(
693            Moonbeam | Moonbase | Moonriver | MoonbeamDev | Rsk | RskTestnet | Gnosis | Chiado,
694        ) = NamedChain::try_from(chain_id)
695        {
696            return true;
697        }
698        self.bypass_prevrandao
699    }
700
701    /// Infers an execution profile from `chain_id` unless one was selected explicitly.
702    ///
703    /// Unknown chain IDs preserve the unresolved configuration so endpoint metadata can still
704    /// identify their execution profile. A known chain whose feature is unavailable is rejected
705    /// instead of silently falling back to Ethereum semantics.
706    pub fn try_with_chain_id(self, chain_id: u64) -> Result<Self, String> {
707        if self.has_network_selection() {
708            return Ok(self);
709        }
710
711        match NetworkVariant::from_known_chain_id(chain_id).map_err(|error| {
712            format!("cannot infer execution network from chain ID {chain_id}: {error}")
713        })? {
714            Some(network) => Ok(self.with_rpc_identity(network, chain_id)),
715            None => Ok(self),
716        }
717    }
718
719    /// Best-effort execution-profile inference for trusted, programmatic chain IDs.
720    ///
721    /// User-provided chain IDs must be handled with [`Self::try_with_chain_id`] so an unavailable
722    /// feature cannot silently select Ethereum semantics.
723    pub fn with_chain_id(self, chain_id: u64) -> Self {
724        self.try_with_chain_id(chain_id).unwrap_or(self)
725    }
726
727    /// Applies an RPC endpoint's resolved EVM family to this configuration.
728    ///
729    /// Successful endpoint metadata is authoritative, including when a local Anvil uses a
730    /// well-known chain ID as an execution override. Orthogonal settings are preserved.
731    pub fn with_rpc_network(self, network: NetworkVariant) -> Self {
732        let mut resolved = if network.is_ethereum() { Self::default() } else { network.into() };
733        resolved.bypass_prevrandao = self.bypass_prevrandao;
734        resolved
735    }
736
737    /// Applies an RPC endpoint's execution family and chain-specific Ethereum configuration.
738    ///
739    /// The reported family is authoritative. A known Celo chain ID additionally enables Celo's
740    /// precompiles because Celo shares the Ethereum EVM factory rather than having its own
741    /// [`NetworkVariant`].
742    pub fn with_rpc_identity(self, network: NetworkVariant, chain_id: ChainId) -> Self {
743        let mut resolved = self.with_rpc_network(network);
744        if network.is_ethereum()
745            && matches!(
746                Chain::from_id(chain_id).named(),
747                Some(NamedChain::Celo | NamedChain::CeloSepolia)
748            )
749        {
750            resolved.celo = true;
751        }
752        resolved
753    }
754
755    /// Returns the canonical endpoint-visible execution profile.
756    pub fn canonical_execution_profile(self) -> Self {
757        if self.is_celo() {
758            Self::with_celo()
759        } else if let Some(network) = self.resolved_network()
760            && !network.is_ethereum()
761        {
762            network.into()
763        } else {
764            Self::default()
765        }
766    }
767
768    /// Applies an authoritative execution profile while preserving orthogonal settings.
769    pub fn with_execution_profile(self, profile: Self) -> Self {
770        let mut resolved = if profile.is_celo() {
771            Self::with_celo()
772        } else {
773            profile.resolved_network().map(Into::into).unwrap_or_default()
774        };
775        resolved.bypass_prevrandao = self.bypass_prevrandao;
776        resolved
777    }
778
779    /// Applies an endpoint-reported execution profile while preserving orthogonal settings.
780    pub fn with_rpc_profile(self, profile: Self) -> Self {
781        self.with_execution_profile(profile.canonical_execution_profile())
782    }
783
784    /// Parses the execution profile reported by `anvil_nodeInfo`.
785    pub fn from_node_info_profile(profile: &str) -> Result<Self, String> {
786        if profile == "celo" {
787            return Ok(Self::with_celo());
788        }
789        let network = NetworkVariant::from_node_info_name(profile)?;
790        Ok(if network.is_ethereum() { Self::default() } else { network.into() })
791    }
792
793    /// Resolves an RPC endpoint's complete execution profile.
794    ///
795    /// Explicit metadata is authoritative. When metadata is absent or omits the profile, a
796    /// caller-supplied explicit profile takes precedence over chain-ID inference. Otherwise,
797    /// legacy Anvil responses and ordinary RPC endpoints recover Celo from a canonical Celo chain
798    /// ID and preserve the historical behavior for custom chain IDs.
799    pub fn from_rpc_identity_profile_with_fallback(
800        chain_id: ChainId,
801        node_info_profile: Option<Option<&str>>,
802        unknown_fallback: Option<Self>,
803    ) -> Result<Option<Self>, String> {
804        let known_profile = || {
805            NetworkVariant::from_known_chain_id(chain_id).map(|network| {
806                network.map(|network| Self::default().with_rpc_identity(network, chain_id))
807            })
808        };
809        let fallback_is_explicit =
810            unknown_fallback.is_some_and(|fallback| fallback.has_network_selection());
811        let fallback = unknown_fallback.map(Self::canonical_execution_profile);
812        if let Some(Some(profile)) = node_info_profile {
813            return Self::from_node_info_profile(profile).map(Some);
814        }
815        if fallback_is_explicit && let Some(fallback) = fallback {
816            return Ok(Some(fallback));
817        }
818        match node_info_profile {
819            Some(None) => Ok(known_profile()?.or(fallback).or(Some(Self::default()))),
820            None => Ok(known_profile()?.or(fallback)),
821            Some(Some(_)) => unreachable!(),
822        }
823    }
824
825    /// Validates `hardfork` against the current `NetworkConfigs` and, if consistent, returns an
826    /// updated instance with the network implied by the enabled hardfork.
827    ///
828    /// Returns `Err` when the hardfork's network family conflicts with the configured one.
829    pub fn normalize_for_hardfork(self, hardfork: FoundryHardfork) -> Result<Self, String> {
830        if self.has_network_selection() {
831            let configured = self.execution_network();
832            if configured.hardfork_namespace() != hardfork.namespace() {
833                return Err(format!(
834                    "hardfork `{}` conflicts with network config `{}`",
835                    String::from(hardfork),
836                    self.execution_profile_name(),
837                ));
838            }
839        }
840
841        let network = match hardfork {
842            FoundryHardfork::Ethereum(_) => self,
843            FoundryHardfork::Tempo(_) => Self::with_tempo(),
844            #[cfg(feature = "base")]
845            FoundryHardfork::Base(_) => Self::with_base(),
846            #[cfg(feature = "optimism")]
847            FoundryHardfork::Optimism(_) => Self::with_optimism(),
848            #[cfg(feature = "monad")]
849            FoundryHardfork::Monad(_) => Self::with_monad(),
850        };
851
852        Ok(network)
853    }
854
855    /// Returns precompiles for configured networks at the given hardfork.
856    pub fn precompiles(self, hardfork: Option<FoundryHardfork>) -> BTreeMap<String, Address> {
857        let mut precompiles = BTreeMap::new();
858        if self.is_celo() {
859            precompiles.insert(CELO_TRANSFER_PRECOMPILE_NAME.to_string(), CELO_TRANSFER_ADDRESS);
860        }
861        if self.is_tempo() {
862            let tempo_hardfork = hardfork.and_then(TempoHardfork::from_foundry_hardfork);
863            precompiles.extend(
864                TEMPO_PRECOMPILES
865                    .iter()
866                    .copied()
867                    .filter(|(_, address)| {
868                        tempo_hardfork.is_none_or(|hardfork| {
869                            is_tempo_precompile_active_at(*address, hardfork)
870                        })
871                    })
872                    .map(|(label, address)| (label.to_string(), address)),
873            );
874        }
875        #[cfg(feature = "monad")]
876        if self.is_monad() {
877            let monad_hardfork = hardfork.and_then(MonadHardfork::from_foundry_hardfork);
878            precompiles.extend(
879                MONAD_PRECOMPILES
880                    .iter()
881                    .copied()
882                    .filter(|(_, address)| {
883                        monad_hardfork.is_none_or(|hardfork| {
884                            is_monad_precompile_active_at(*address, hardfork)
885                        })
886                    })
887                    .map(|(label, address)| (label.to_string(), address)),
888            );
889        }
890        #[cfg(feature = "base")]
891        if self.is_base() {
892            let base_upgrade = hardfork.and_then(|hardfork| match hardfork {
893                FoundryHardfork::Base(upgrade) => Some(upgrade),
894                _ => None,
895            });
896            precompiles.extend(
897                BASE_PRECOMPILES
898                    .iter()
899                    .copied()
900                    .filter(|(_, address)| {
901                        base_upgrade
902                            .is_none_or(|upgrade| is_base_precompile_active_at(*address, upgrade))
903                    })
904                    .map(|(label, address)| (label.to_string(), address)),
905            );
906        }
907        precompiles
908    }
909}
910
911impl From<NetworkVariant> for NetworkConfigs {
912    fn from(network: NetworkVariant) -> Self {
913        match network {
914            NetworkVariant::Ethereum => Self::with_ethereum(),
915            NetworkVariant::Tempo => {
916                Self { network: Some(network), tempo: true, ..Default::default() }
917            }
918            #[cfg(feature = "monad")]
919            NetworkVariant::Monad => {
920                Self { network: Some(network), monad: true, ..Default::default() }
921            }
922            #[cfg(feature = "base")]
923            NetworkVariant::Base => Self { network: Some(network), ..Default::default() },
924            #[cfg(feature = "optimism")]
925            NetworkVariant::Optimism => {
926                Self { network: Some(network), optimism: true, ..Default::default() }
927            }
928        }
929    }
930}
931
932/// Returns custom precompile labels for an already resolved execution hardfork.
933/// This metadata lookup does not discover or select an execution network.
934pub fn resolved_precompile_labels(hardfork: Option<FoundryHardfork>) -> AddressHashMap<String> {
935    match hardfork {
936        Some(FoundryHardfork::Tempo(hardfork)) => TEMPO_PRECOMPILES
937            .iter()
938            .filter(|(_, address)| is_tempo_precompile_active_at(*address, hardfork))
939            .map(|(label, address)| (*address, (*label).to_string()))
940            .collect(),
941        #[cfg(feature = "monad")]
942        Some(FoundryHardfork::Monad(hardfork)) => MONAD_PRECOMPILE_LABELS
943            .iter()
944            .filter(|(_, address)| is_monad_precompile_active_at(*address, hardfork))
945            .map(|(label, address)| (*address, (*label).to_string()))
946            .collect(),
947        #[cfg(feature = "base")]
948        Some(FoundryHardfork::Base(upgrade)) => BASE_PRECOMPILES
949            .iter()
950            .filter(|(_, address)| is_base_precompile_active_at(*address, upgrade))
951            .map(|(label, address)| (*address, (*label).to_string()))
952            .collect(),
953        _ => AddressHashMap::default(),
954    }
955}
956
957/// Returns whether a well-known Tempo precompile address is active at `hardfork`.
958pub fn is_tempo_precompile_active_at(address: Address, hardfork: TempoHardfork) -> bool {
959    if address == CURRENT_COMMITTEE_ADDRESS {
960        hardfork.is_t8()
961    } else if address == TIP20_CHANNEL_RESERVE_ADDRESS {
962        hardfork.is_t5()
963    } else if address == RECEIVE_POLICY_GUARD_ADDRESS {
964        hardfork.is_t6()
965    } else if address == STORAGE_CREDITS_ADDRESS {
966        hardfork.is_t7()
967    } else if address == CONFIGURABLE_ACCOUNT_ADDRESS {
968        hardfork.is_t14()
969    } else if address == ADDRESS_REGISTRY_ADDRESS || address == SIGNATURE_VERIFIER_ADDRESS {
970        hardfork.is_t3()
971    } else {
972        true
973    }
974}
975
976/// Returns the well-known Tempo precompile addresses active at `hardfork`.
977pub fn active_tempo_precompile_addresses(hardfork: TempoHardfork) -> impl Iterator<Item = Address> {
978    TEMPO_PRECOMPILE_ADDRESSES
979        .iter()
980        .copied()
981        .filter(move |&address| is_tempo_precompile_active_at(address, hardfork))
982}
983
984/// Returns whether a well-known Monad precompile address is active at `hardfork`.
985#[cfg(feature = "monad")]
986pub fn is_monad_precompile_active_at(address: Address, hardfork: MonadHardfork) -> bool {
987    address == monad_evm2::staking::STAKING_ADDRESS
988        || (address == monad_evm2::reserve_balance::RESERVE_BALANCE_ADDRESS
989            && MonadHardfork::MonadNine.is_enabled_in(hardfork))
990}
991
992/// Returns whether a fixed Base precompile is active at `upgrade`.
993#[cfg(feature = "base")]
994pub fn is_base_precompile_active_at(address: Address, upgrade: BaseUpgrade) -> bool {
995    if matches!(address, TX_CONTEXT_ADDRESS | NonceManagerSlots::ADDRESS) {
996        upgrade >= BaseUpgrade::Cobalt
997    } else if matches!(
998        address,
999        B20_FACTORY_ADDRESS | ACTIVATION_REGISTRY_ADDRESS | POLICY_REGISTRY_ADDRESS
1000    ) {
1001        upgrade >= BaseUpgrade::Beryl
1002    } else {
1003        false
1004    }
1005}
1006
1007/// Returns the fixed Base precompiles active at `upgrade`.
1008#[cfg(feature = "base")]
1009pub fn active_base_precompiles(
1010    upgrade: BaseUpgrade,
1011) -> impl Iterator<Item = (&'static str, Address)> {
1012    BASE_PRECOMPILES
1013        .iter()
1014        .copied()
1015        .filter(move |(_, address)| is_base_precompile_active_at(*address, upgrade))
1016}
1017
1018#[cfg(test)]
1019mod tests {
1020    use super::*;
1021
1022    // --- Equivalence: new flag == legacy flag ---
1023
1024    #[test]
1025    fn network_variant_predicates() {
1026        assert!(NetworkVariant::Ethereum.is_ethereum());
1027        assert!(!NetworkVariant::Ethereum.is_optimism());
1028        assert!(!NetworkVariant::Ethereum.is_tempo());
1029        assert!(NetworkVariant::Tempo.is_tempo());
1030        assert!(!NetworkVariant::Tempo.is_ethereum());
1031        assert!(!NetworkVariant::Tempo.is_optimism());
1032
1033        #[cfg(feature = "monad")]
1034        {
1035            assert!(!NetworkVariant::Ethereum.is_monad());
1036            assert!(!NetworkVariant::Tempo.is_monad());
1037            assert!(NetworkVariant::Monad.is_monad());
1038            assert!(!NetworkVariant::Monad.is_ethereum());
1039            assert!(!NetworkVariant::Monad.is_optimism());
1040            assert!(!NetworkVariant::Monad.is_tempo());
1041        }
1042
1043        #[cfg(feature = "optimism")]
1044        {
1045            assert!(NetworkVariant::Optimism.is_optimism());
1046            assert!(!NetworkVariant::Optimism.is_ethereum());
1047            assert!(!NetworkVariant::Optimism.is_tempo());
1048
1049            #[cfg(feature = "monad")]
1050            assert!(!NetworkVariant::Optimism.is_monad());
1051        }
1052
1053        #[cfg(feature = "base")]
1054        {
1055            assert!(NetworkVariant::Base.is_base());
1056            assert!(!NetworkVariant::Base.is_ethereum());
1057            assert!(!NetworkVariant::Base.is_optimism());
1058            assert!(!NetworkVariant::Base.is_tempo());
1059        }
1060    }
1061
1062    #[test]
1063    #[cfg(all(feature = "base", feature = "optimism"))]
1064    fn historical_hardfork_uses_selected_execution_family() {
1065        let timestamp = 1_710_374_401;
1066
1067        assert_eq!(
1068            NetworkVariant::Base.historical_hardfork(NamedChain::Base as u64, timestamp),
1069            Some(BaseUpgrade::Ecotone.into())
1070        );
1071        assert_eq!(
1072            NetworkVariant::Optimism.historical_hardfork(NamedChain::Base as u64, timestamp),
1073            Some(OpHardfork::Ecotone.into())
1074        );
1075        assert_eq!(
1076            NetworkVariant::Ethereum.historical_hardfork(NamedChain::Base as u64, timestamp),
1077            None
1078        );
1079        assert_eq!(
1080            NetworkVariant::Tempo.historical_hardfork(NamedChain::Base as u64, timestamp),
1081            None
1082        );
1083    }
1084
1085    #[test]
1086    #[cfg(feature = "monad")]
1087    fn fork_sources_only_isolate_monad() {
1088        let non_monad = vec![
1089            NetworkConfigs::default(),
1090            NetworkConfigs::with_ethereum(),
1091            NetworkConfigs::with_celo(),
1092            NetworkConfigs::with_tempo(),
1093        ];
1094
1095        for execution in &non_monad {
1096            for source in &non_monad {
1097                assert!(execution.supports_fork_source(source));
1098            }
1099            assert!(!execution.supports_fork_source(&NetworkConfigs::with_monad()));
1100            assert!(!NetworkConfigs::with_monad().supports_fork_source(execution));
1101        }
1102        assert!(NetworkConfigs::with_monad().supports_fork_source(&NetworkConfigs::with_monad()));
1103    }
1104
1105    #[test]
1106    #[cfg(feature = "optimism")]
1107    fn optimism_fork_sources_require_op_stack_state() {
1108        let optimism = NetworkConfigs::with_optimism();
1109        for source in [
1110            NetworkConfigs::default(),
1111            NetworkConfigs::with_ethereum(),
1112            NetworkConfigs::with_celo(),
1113            NetworkConfigs::with_tempo(),
1114        ] {
1115            assert!(!optimism.supports_fork_source(&source));
1116            assert!(source.supports_fork_source(&optimism));
1117        }
1118        assert!(optimism.supports_fork_source(&optimism));
1119        #[cfg(feature = "monad")]
1120        assert!(!optimism.supports_fork_source(&NetworkConfigs::with_monad()));
1121    }
1122
1123    #[test]
1124    #[cfg(feature = "base")]
1125    fn fork_sources_preserve_base_state_source_compatibility() {
1126        #[cfg_attr(not(feature = "optimism"), allow(unused_mut))]
1127        let mut non_base = vec![
1128            NetworkConfigs::default(),
1129            NetworkConfigs::with_ethereum(),
1130            NetworkConfigs::with_celo(),
1131            NetworkConfigs::with_tempo(),
1132        ];
1133        #[cfg(feature = "optimism")]
1134        non_base.push(NetworkConfigs::with_optimism());
1135        for execution in &non_base {
1136            assert!(execution.supports_fork_source(&NetworkConfigs::with_base()));
1137            assert!(!NetworkConfigs::with_base().supports_fork_source(execution));
1138        }
1139        assert!(NetworkConfigs::with_base().supports_fork_source(&NetworkConfigs::with_base()));
1140
1141        #[cfg(feature = "monad")]
1142        {
1143            assert!(
1144                !NetworkConfigs::with_monad().supports_fork_source(&NetworkConfigs::with_base())
1145            );
1146            assert!(
1147                !NetworkConfigs::with_base().supports_fork_source(&NetworkConfigs::with_monad())
1148            );
1149        }
1150    }
1151
1152    #[test]
1153    fn known_chain_identity_does_not_guess_unknown_networks() {
1154        assert_eq!(NetworkVariant::from_known_chain_id(98_765_432).unwrap(), None);
1155        assert_eq!(
1156            NetworkVariant::from_known_chain_id(NamedChain::Mainnet as u64).unwrap(),
1157            Some(NetworkVariant::Ethereum)
1158        );
1159        assert_eq!(NetworkVariant::from(98_765_432), NetworkVariant::Ethereum);
1160    }
1161
1162    #[test]
1163    fn fallible_chain_id_inference_preserves_unknown_chains() {
1164        let networks = NetworkConfigs { bypass_prevrandao: true, ..Default::default() };
1165        assert_eq!(networks.try_with_chain_id(98_765_432).unwrap(), networks);
1166    }
1167
1168    #[test]
1169    #[cfg(not(feature = "monad"))]
1170    fn fallible_chain_id_inference_rejects_disabled_monad() {
1171        for chain_id in [NamedChain::Monad as u64, NamedChain::MonadTestnet as u64] {
1172            let unavailable = "network family `monad` is not enabled in this build";
1173            let expected =
1174                format!("cannot infer execution network from chain ID {chain_id}: {unavailable}");
1175            assert_eq!(
1176                NetworkConfigs::default().try_with_chain_id(chain_id).unwrap_err(),
1177                expected
1178            );
1179        }
1180    }
1181
1182    #[test]
1183    #[cfg(not(feature = "optimism"))]
1184    fn fallible_chain_id_inference_rejects_disabled_optimism() {
1185        let chain_id = NamedChain::Optimism as u64;
1186        assert_eq!(
1187            NetworkConfigs::default().try_with_chain_id(chain_id).unwrap_err(),
1188            format!(
1189                "cannot infer execution network from chain ID {chain_id}: network family \
1190                 `optimism` is not enabled in this build"
1191            )
1192        );
1193    }
1194
1195    #[test]
1196    fn explicit_ethereum_overrides_known_chain_inference() {
1197        let ethereum = NetworkConfigs::with_ethereum();
1198        for chain_id in [NamedChain::Monad as u64, NamedChain::Optimism as u64] {
1199            assert_eq!(ethereum.try_with_chain_id(chain_id).unwrap(), ethereum);
1200        }
1201    }
1202
1203    #[test]
1204    fn fallible_chain_id_inference_preserves_orthogonal_configuration() {
1205        let networks = NetworkConfigs { bypass_prevrandao: true, ..Default::default() };
1206        let inferred = networks.try_with_chain_id(NamedChain::Tempo as u64).unwrap();
1207
1208        assert!(inferred.is_tempo());
1209        assert!(inferred.bypass_prevrandao(NamedChain::Mainnet as u64));
1210    }
1211
1212    #[test]
1213    #[cfg(feature = "optimism")]
1214    fn fallible_chain_id_inference_detects_optimism() {
1215        let chain_id = NamedChain::Optimism as u64;
1216        assert_eq!(NetworkVariant::from(chain_id), NetworkVariant::Optimism);
1217        assert!(NetworkConfigs::default().try_with_chain_id(chain_id).unwrap().is_optimism());
1218    }
1219
1220    #[test]
1221    fn rpc_identity_preserves_orthogonal_configuration() {
1222        let base = NetworkConfigs { bypass_prevrandao: true, ..NetworkConfigs::default() };
1223        let ethereum = base.with_rpc_network(NetworkVariant::Ethereum);
1224        assert!(ethereum.bypass_prevrandao(NamedChain::Mainnet as u64));
1225
1226        let ethereum = NetworkConfigs::default().with_rpc_network(NetworkVariant::Ethereum);
1227        assert_eq!(ethereum, NetworkConfigs::default());
1228
1229        assert!(
1230            NetworkConfigs::default()
1231                .with_rpc_identity(NetworkVariant::Ethereum, NamedChain::Celo as u64)
1232                .is_celo()
1233        );
1234        assert!(
1235            !NetworkConfigs::default()
1236                .with_rpc_identity(NetworkVariant::Ethereum, NamedChain::Monad as u64)
1237                .is_monad()
1238        );
1239    }
1240
1241    #[test]
1242    fn rpc_metadata_overrides_known_execution_chain_identity() {
1243        assert_eq!(
1244            NetworkConfigs::from_rpc_identity_profile_with_fallback(
1245                NamedChain::Mainnet as u64,
1246                Some(Some("tempo")),
1247                None,
1248            )
1249            .unwrap(),
1250            Some(NetworkConfigs::with_tempo())
1251        );
1252        assert_eq!(
1253            NetworkConfigs::from_rpc_identity_profile_with_fallback(
1254                NamedChain::Tempo as u64,
1255                Some(None),
1256                None,
1257            )
1258            .unwrap(),
1259            Some(NetworkConfigs::with_tempo())
1260        );
1261        assert_eq!(
1262            NetworkConfigs::from_rpc_identity_profile_with_fallback(98_765_432, None, None)
1263                .unwrap(),
1264            None
1265        );
1266        assert_eq!(
1267            NetworkConfigs::from_rpc_identity_profile_with_fallback(98_765_432, Some(None), None)
1268                .unwrap(),
1269            Some(NetworkConfigs::default())
1270        );
1271        #[cfg(feature = "optimism")]
1272        assert_eq!(
1273            NetworkConfigs::from_rpc_identity_profile_with_fallback(
1274                NamedChain::Optimism as u64,
1275                Some(None),
1276                None,
1277            )
1278            .unwrap(),
1279            Some(NetworkConfigs::from(NetworkVariant::Optimism))
1280        );
1281    }
1282
1283    #[test]
1284    fn rpc_profile_distinguishes_celo_from_ethereum_factory() {
1285        let custom_chain_id = 98_765_432;
1286        assert!(
1287            NetworkConfigs::from_rpc_identity_profile_with_fallback(
1288                custom_chain_id,
1289                Some(Some("celo")),
1290                None,
1291            )
1292            .unwrap()
1293            .unwrap()
1294            .is_celo()
1295        );
1296        assert!(
1297            !NetworkConfigs::from_rpc_identity_profile_with_fallback(
1298                NamedChain::Celo as u64,
1299                Some(Some("ethereum")),
1300                None,
1301            )
1302            .unwrap()
1303            .unwrap()
1304            .is_celo()
1305        );
1306        assert!(
1307            NetworkConfigs::from_rpc_identity_profile_with_fallback(
1308                NamedChain::Celo as u64,
1309                Some(None),
1310                None,
1311            )
1312            .unwrap()
1313            .unwrap()
1314            .is_celo()
1315        );
1316        assert!(
1317            NetworkConfigs::from_rpc_identity_profile_with_fallback(
1318                custom_chain_id,
1319                None,
1320                Some(NetworkConfigs::with_celo()),
1321            )
1322            .unwrap()
1323            .unwrap()
1324            .is_celo()
1325        );
1326    }
1327
1328    #[test]
1329    fn rpc_profile_keeps_moonbeam_on_default_ethereum() {
1330        let profile = NetworkConfigs::from_rpc_identity_profile_with_fallback(
1331            NamedChain::Moonbeam as u64,
1332            None,
1333            None,
1334        )
1335        .unwrap()
1336        .unwrap();
1337
1338        assert_eq!(profile, NetworkConfigs::default());
1339        assert!(profile.bypass_prevrandao(NamedChain::Moonbeam as u64));
1340    }
1341
1342    #[test]
1343    fn default_fallback_still_infers_known_execution_profile() {
1344        for node_info in [None, Some(None)] {
1345            assert_eq!(
1346                NetworkConfigs::from_rpc_identity_profile_with_fallback(
1347                    NamedChain::Tempo as u64,
1348                    node_info,
1349                    Some(NetworkConfigs::default()),
1350                )
1351                .unwrap(),
1352                Some(NetworkConfigs::with_tempo())
1353            );
1354        }
1355    }
1356
1357    #[test]
1358    fn explicit_ethereum_overrides_known_execution_profile() {
1359        for node_info in [None, Some(None)] {
1360            assert_eq!(
1361                NetworkConfigs::from_rpc_identity_profile_with_fallback(
1362                    NamedChain::Tempo as u64,
1363                    node_info,
1364                    Some(NetworkConfigs::with_ethereum()),
1365                )
1366                .unwrap(),
1367                Some(NetworkConfigs::default())
1368            );
1369        }
1370    }
1371
1372    #[test]
1373    #[cfg(not(feature = "monad"))]
1374    fn explicit_ethereum_overrides_disabled_monad_without_node_info() {
1375        assert_eq!(
1376            NetworkConfigs::from_rpc_identity_profile_with_fallback(
1377                NamedChain::Monad as u64,
1378                None,
1379                Some(NetworkConfigs::with_ethereum()),
1380            )
1381            .unwrap(),
1382            Some(NetworkConfigs::default())
1383        );
1384    }
1385
1386    #[test]
1387    #[cfg(not(feature = "monad"))]
1388    fn explicit_ethereum_overrides_disabled_monad_with_legacy_node_info() {
1389        assert_eq!(
1390            NetworkConfigs::from_rpc_identity_profile_with_fallback(
1391                NamedChain::Monad as u64,
1392                Some(None),
1393                Some(NetworkConfigs::with_ethereum()),
1394            )
1395            .unwrap(),
1396            Some(NetworkConfigs::default())
1397        );
1398    }
1399
1400    #[test]
1401    #[cfg(not(feature = "monad"))]
1402    fn disabled_monad_without_explicit_profile_still_errors() {
1403        for node_info in [None, Some(None)] {
1404            assert_eq!(
1405                NetworkConfigs::from_rpc_identity_profile_with_fallback(
1406                    NamedChain::Monad as u64,
1407                    node_info,
1408                    None,
1409                )
1410                .unwrap_err(),
1411                "network family `monad` is not enabled in this build"
1412            );
1413        }
1414    }
1415
1416    #[test]
1417    fn network_selection_distinguishes_default_and_explicit_ethereum() {
1418        assert!(!NetworkConfigs::default().has_network_selection());
1419        assert!(NetworkConfigs::with_ethereum().has_network_selection());
1420        assert!(NetworkConfigs::with_celo().has_network_selection());
1421    }
1422
1423    #[test]
1424    fn celo_uses_ethereum_factory_with_distinct_precompiles() {
1425        assert!(
1426            !NetworkConfigs::with_celo().has_same_execution_profile(&NetworkConfigs::default())
1427        );
1428        assert!(
1429            NetworkConfigs::with_ethereum().has_same_execution_profile(&NetworkConfigs::default())
1430        );
1431        assert_eq!(NetworkConfigs::with_celo().execution_family_name(), "ethereum");
1432        assert_eq!(NetworkConfigs::with_celo().execution_profile_name(), "celo");
1433    }
1434
1435    #[test]
1436    fn authoritative_execution_profile_preserves_orthogonal_settings() {
1437        let inline = NetworkConfigs { bypass_prevrandao: true, ..NetworkConfigs::with_tempo() };
1438
1439        #[cfg_attr(not(any(feature = "optimism", feature = "monad")), allow(unused_mut))]
1440        let mut profiles = vec![
1441            NetworkConfigs::with_ethereum(),
1442            NetworkConfigs::with_tempo(),
1443            NetworkConfigs::with_celo(),
1444        ];
1445        #[cfg(feature = "optimism")]
1446        profiles.push(NetworkVariant::Optimism.into());
1447        #[cfg(feature = "monad")]
1448        profiles.push(NetworkConfigs::with_monad());
1449
1450        for profile in profiles {
1451            let resolved = inline.with_execution_profile(profile);
1452            assert!(resolved.has_same_execution_profile(&profile));
1453            assert!(resolved.has_network_selection());
1454            assert!(resolved.bypass_prevrandao(NamedChain::Mainnet as u64));
1455        }
1456
1457        let ethereum = inline.with_execution_profile(NetworkConfigs::with_ethereum());
1458        assert_eq!(
1459            ethereum.try_with_chain_id(NamedChain::Tempo as u64).unwrap(),
1460            ethereum,
1461            "an authoritative Ethereum profile must prevent later endpoint inference",
1462        );
1463
1464        let rpc_ethereum = inline.with_rpc_profile(NetworkConfigs::with_ethereum());
1465        assert!(!rpc_ethereum.has_network_selection());
1466    }
1467
1468    #[test]
1469    fn chain_id_inference_preserves_explicit_networks() {
1470        assert!(
1471            NetworkConfigs::default().try_with_chain_id(NamedChain::Celo as u64).unwrap().is_celo()
1472        );
1473        let celo = NetworkConfigs { bypass_prevrandao: true, ..Default::default() }
1474            .try_with_chain_id(NamedChain::Celo as u64)
1475            .unwrap();
1476        assert!(celo.is_celo());
1477        assert!(celo.bypass_prevrandao(NamedChain::Mainnet as u64));
1478
1479        let explicit = [
1480            NetworkConfigs::with_ethereum(),
1481            NetworkConfigs::with_tempo(),
1482            NetworkConfigs::with_celo(),
1483        ];
1484        for networks in explicit {
1485            assert_eq!(networks.try_with_chain_id(NamedChain::Celo as u64).unwrap(), networks);
1486        }
1487
1488        #[cfg(feature = "monad")]
1489        {
1490            let monad = NetworkConfigs::with_monad();
1491            assert_eq!(monad.try_with_chain_id(NamedChain::Celo as u64).unwrap(), monad);
1492        }
1493    }
1494
1495    #[test]
1496    #[cfg(feature = "monad")]
1497    fn rpc_metadata_identifies_custom_monad_networks() {
1498        assert_eq!(NetworkVariant::from_node_info_name("monad").unwrap(), NetworkVariant::Monad);
1499        assert!(NetworkConfigs::default().with_rpc_network(NetworkVariant::Monad).is_monad());
1500    }
1501
1502    #[test]
1503    #[cfg(feature = "monad")]
1504    fn parses_endpoint_hardfork_in_network_namespace() {
1505        assert_eq!(
1506            NetworkVariant::Monad.parse_hardfork("MonadEight").unwrap(),
1507            FoundryHardfork::Monad(MonadHardfork::MonadEight)
1508        );
1509    }
1510
1511    #[test]
1512    fn rpc_metadata_rejects_unknown_network_family() {
1513        assert_eq!(
1514            NetworkVariant::from_node_info_name("unknown").unwrap_err(),
1515            "unsupported network family `unknown` reported by fork endpoint"
1516        );
1517    }
1518
1519    #[test]
1520    fn explicit_ethereum_families_reject_namespaced_hardforks() {
1521        #[cfg_attr(not(feature = "monad"), allow(unused_mut))]
1522        let mut incompatible = vec![FoundryHardfork::Tempo(TempoHardfork::T0)];
1523        #[cfg(feature = "monad")]
1524        incompatible.push(FoundryHardfork::Monad(MonadHardfork::MonadEight));
1525
1526        for networks in [NetworkConfigs::with_ethereum(), NetworkConfigs::with_celo()] {
1527            for hardfork in &incompatible {
1528                assert_eq!(
1529                    networks.normalize_for_hardfork(*hardfork).unwrap_err(),
1530                    format!(
1531                        "hardfork `{}` conflicts with network config `{}`",
1532                        String::from(*hardfork),
1533                        networks.execution_profile_name()
1534                    )
1535                );
1536            }
1537        }
1538
1539        let celo = NetworkConfigs::with_celo();
1540        assert_eq!(
1541            celo.normalize_for_hardfork(FoundryHardfork::Ethereum(
1542                foundry_evm_hardforks::EthereumHardfork::Prague
1543            ))
1544            .unwrap(),
1545            celo
1546        );
1547    }
1548
1549    #[cfg(feature = "base")]
1550    #[test]
1551    fn base_precompile_labels_follow_upgrade_boundaries() {
1552        let config = NetworkConfigs::with_base();
1553
1554        assert!(resolved_precompile_labels(Some(BaseUpgrade::Azul.into())).is_empty());
1555
1556        let beryl = resolved_precompile_labels(Some(BaseUpgrade::Beryl.into()));
1557        assert_eq!(beryl.get(&B20_FACTORY_ADDRESS), Some(&"B20Factory".to_string()));
1558        assert_eq!(
1559            beryl.get(&ACTIVATION_REGISTRY_ADDRESS),
1560            Some(&"ActivationRegistry".to_string())
1561        );
1562        assert_eq!(beryl.get(&POLICY_REGISTRY_ADDRESS), Some(&"PolicyRegistry".to_string()));
1563        assert!(!beryl.contains_key(&TX_CONTEXT_ADDRESS));
1564        assert!(!beryl.contains_key(&NonceManagerSlots::ADDRESS));
1565
1566        let cobalt = resolved_precompile_labels(Some(BaseUpgrade::Cobalt.into()));
1567        assert_eq!(cobalt.len(), BASE_PRECOMPILES.len());
1568
1569        // The name-keyed precompile map must honor the same upgrade boundaries.
1570        assert!(config.precompiles(Some(BaseUpgrade::Azul.into())).is_empty());
1571        let beryl = config.precompiles(Some(BaseUpgrade::Beryl.into()));
1572        assert_eq!(beryl.get("B20Factory"), Some(&B20_FACTORY_ADDRESS));
1573        assert!(!beryl.contains_key("NonceManager"));
1574        assert_eq!(
1575            config.precompiles(Some(BaseUpgrade::Cobalt.into())).get("NonceManager"),
1576            Some(&NonceManagerSlots::ADDRESS)
1577        );
1578    }
1579
1580    #[test]
1581    fn new_tempo_flag_equivalent_to_legacy() {
1582        let via_new = NetworkConfigs { network: Some(NetworkVariant::Tempo), ..Default::default() };
1583        let via_old = NetworkConfigs { tempo: true, ..Default::default() };
1584        assert_eq!(via_new.is_tempo(), via_old.is_tempo());
1585        assert_eq!(via_new.active_network_name(), via_old.active_network_name());
1586        assert_eq!(via_new.precompiles(None), via_old.precompiles(None));
1587    }
1588
1589    #[test]
1590    fn canonical_tempo_network_reports_precompiles() {
1591        let cfg = NetworkConfigs { network: Some(NetworkVariant::Tempo), ..Default::default() };
1592
1593        assert_eq!(
1594            cfg.precompiles(None).get("TIP20ChannelReserve"),
1595            Some(&TIP20_CHANNEL_RESERVE_ADDRESS)
1596        );
1597        assert!(
1598            !cfg.precompiles(Some(TempoHardfork::T4.into())).contains_key("TIP20ChannelReserve")
1599        );
1600        assert!(
1601            !cfg.precompiles(Some(TempoHardfork::T4.into())).contains_key("ReceivePolicyGuard")
1602        );
1603        assert!(!cfg.precompiles(Some(TempoHardfork::T2.into())).contains_key("AddressRegistry"));
1604        assert!(!cfg.precompiles(Some(TempoHardfork::T2.into())).contains_key("SignatureVerifier"));
1605        assert_eq!(
1606            cfg.precompiles(Some(TempoHardfork::T3.into())).get("AddressRegistry"),
1607            Some(&ADDRESS_REGISTRY_ADDRESS)
1608        );
1609        assert_eq!(
1610            cfg.precompiles(Some(TempoHardfork::T3.into())).get("SignatureVerifier"),
1611            Some(&SIGNATURE_VERIFIER_ADDRESS)
1612        );
1613        assert_eq!(
1614            resolved_precompile_labels(Some(TempoHardfork::T5.into()))
1615                .get(&TIP20_CHANNEL_RESERVE_ADDRESS),
1616            Some(&"TIP20ChannelReserve".to_string())
1617        );
1618        assert!(
1619            !resolved_precompile_labels(Some(TempoHardfork::T5.into()))
1620                .contains_key(&RECEIVE_POLICY_GUARD_ADDRESS)
1621        );
1622        assert!(
1623            resolved_precompile_labels(Some(TempoHardfork::T6.into()))
1624                .contains_key(&RECEIVE_POLICY_GUARD_ADDRESS)
1625        );
1626    }
1627
1628    #[test]
1629    #[cfg(feature = "monad")]
1630    fn canonical_monad_network_reports_hardfork_gated_precompiles() {
1631        let cfg = NetworkConfigs { network: Some(NetworkVariant::Monad), ..Default::default() };
1632
1633        assert_eq!(
1634            cfg.precompiles(Some(MonadHardfork::MonadEight.into())).get("MonadStaking"),
1635            Some(&monad_evm2::staking::STAKING_ADDRESS)
1636        );
1637        assert!(
1638            !cfg.precompiles(Some(MonadHardfork::MonadEight.into()))
1639                .contains_key("MonadReserveBalance")
1640        );
1641        assert_eq!(
1642            cfg.precompiles(Some(MonadHardfork::MonadNine.into())).get("MonadReserveBalance"),
1643            Some(&monad_evm2::reserve_balance::RESERVE_BALANCE_ADDRESS)
1644        );
1645        assert_eq!(
1646            resolved_precompile_labels(Some(MonadHardfork::MonadNine.into()))
1647                .get(&monad_evm2::reserve_balance::RESERVE_BALANCE_ADDRESS),
1648            Some(&"ReserveBalance".to_string())
1649        );
1650        assert!(
1651            !resolved_precompile_labels(Some(MonadHardfork::MonadEight.into()))
1652                .contains_key(&monad_evm2::reserve_balance::RESERVE_BALANCE_ADDRESS)
1653        );
1654    }
1655
1656    #[test]
1657    fn storage_credits_precompile_activates_at_t7() {
1658        assert!(!is_tempo_precompile_active_at(STORAGE_CREDITS_ADDRESS, TempoHardfork::T6));
1659        assert!(is_tempo_precompile_active_at(STORAGE_CREDITS_ADDRESS, TempoHardfork::T7));
1660        assert!(TEMPO_PRECOMPILE_ADDRESSES.contains(&STORAGE_CREDITS_ADDRESS));
1661
1662        // The hardfork-filtered precompile map must honor the same T7 activation.
1663        let cfg = NetworkConfigs { network: Some(NetworkVariant::Tempo), ..Default::default() };
1664        assert!(!cfg.precompiles(Some(TempoHardfork::T6.into())).contains_key("StorageCredits"));
1665        assert!(cfg.precompiles(Some(TempoHardfork::T7.into())).contains_key("StorageCredits"));
1666    }
1667
1668    #[test]
1669    fn current_committee_precompile_activates_at_t8() {
1670        assert!(!is_tempo_precompile_active_at(CURRENT_COMMITTEE_ADDRESS, TempoHardfork::T7));
1671        assert!(is_tempo_precompile_active_at(CURRENT_COMMITTEE_ADDRESS, TempoHardfork::T8));
1672        assert!(TEMPO_PRECOMPILE_ADDRESSES.contains(&CURRENT_COMMITTEE_ADDRESS));
1673
1674        let cfg = NetworkConfigs { network: Some(NetworkVariant::Tempo), ..Default::default() };
1675        assert!(!cfg.precompiles(Some(TempoHardfork::T7.into())).contains_key("CurrentCommittee"));
1676        assert!(cfg.precompiles(Some(TempoHardfork::T8.into())).contains_key("CurrentCommittee"));
1677    }
1678
1679    #[test]
1680    fn configurable_account_precompile_activates_at_t14() {
1681        assert!(!is_tempo_precompile_active_at(CONFIGURABLE_ACCOUNT_ADDRESS, TempoHardfork::T13));
1682        assert!(is_tempo_precompile_active_at(CONFIGURABLE_ACCOUNT_ADDRESS, TempoHardfork::T14));
1683
1684        let cfg = NetworkConfigs { network: Some(NetworkVariant::Tempo), ..Default::default() };
1685        assert!(
1686            !cfg.precompiles(Some(TempoHardfork::T13.into())).contains_key("ConfigurableAccount")
1687        );
1688        assert_eq!(
1689            cfg.precompiles(Some(TempoHardfork::T14.into())).get("ConfigurableAccount"),
1690            Some(&CONFIGURABLE_ACCOUNT_ADDRESS)
1691        );
1692    }
1693
1694    // --- resolved() / active_network_name ---
1695
1696    #[test]
1697    fn active_network_name_tempo() {
1698        let cfg = NetworkConfigs::with_tempo();
1699        assert_eq!(cfg.active_network_name(), Some("tempo"));
1700    }
1701
1702    #[test]
1703    #[cfg(feature = "monad")]
1704    fn active_network_name_monad() {
1705        let cfg = NetworkConfigs::with_monad();
1706        assert_eq!(cfg.active_network_name(), Some("monad"));
1707        assert!(cfg.is_monad());
1708    }
1709
1710    #[test]
1711    #[cfg(feature = "monad")]
1712    fn contract_size_limits_monad() {
1713        let limits = NetworkConfigs::with_monad().contract_size_limits().unwrap();
1714        assert_eq!(limits.runtime, monad_evm2::MONAD_MAX_CODE_SIZE);
1715        assert_eq!(limits.initcode, monad_evm2::MONAD_MAX_INITCODE_SIZE);
1716        assert!(NetworkConfigs::default().contract_size_limits().is_none());
1717    }
1718
1719    #[test]
1720    fn active_network_name_default_is_none() {
1721        let cfg = NetworkConfigs::default();
1722        assert_eq!(cfg.active_network_name(), None);
1723        assert!(!cfg.is_optimism());
1724    }
1725
1726    /// Base chain IDs resolved to Optimism before Base support existed, and `is_optimism()` still
1727    /// covers them, so a build without the `base` feature must keep resolving them rather than
1728    /// erroring. Shipped release binaries are exactly that build.
1729    #[test]
1730    #[cfg(all(not(feature = "base"), feature = "optimism"))]
1731    fn chain_id_inference_falls_back_to_optimism_without_base() {
1732        for chain_id in [NamedChain::Base as u64, NamedChain::BaseSepolia as u64] {
1733            let configs = NetworkConfigs::default()
1734                .try_with_chain_id(chain_id)
1735                .unwrap_or_else(|error| panic!("chain ID {chain_id} must still resolve: {error}"));
1736            assert!(configs.is_optimism(), "chain ID {chain_id} must resolve to Optimism");
1737        }
1738    }
1739
1740    #[test]
1741    #[cfg(not(feature = "base"))]
1742    fn node_info_rejects_disabled_base() {
1743        assert_eq!(
1744            NetworkVariant::from_node_info_name("base").unwrap_err(),
1745            "network family `base` is not enabled in this build"
1746        );
1747    }
1748
1749    // --- Serde round-trip ---
1750
1751    #[test]
1752    fn serde_roundtrip_tempo() {
1753        let original = NetworkConfigs::with_tempo();
1754        let json = serde_json::to_string(&original).unwrap();
1755        let restored: NetworkConfigs = serde_json::from_str(&json).unwrap();
1756        assert!(restored.is_tempo());
1757    }
1758
1759    #[test]
1760    fn serde_legacy_tempo_bool_deserialized() {
1761        // Old foundry.toml format: `tempo = true`
1762        let json = r#"{"tempo": true, "celo": false, "bypass_prevrandao": false}"#;
1763        let cfg: NetworkConfigs = serde_json::from_str(json).unwrap();
1764        assert!(cfg.is_tempo());
1765    }
1766
1767    #[test]
1768    #[cfg(feature = "monad")]
1769    fn serde_roundtrip_monad() {
1770        let original = NetworkConfigs::with_monad();
1771        let json = serde_json::to_string(&original).unwrap();
1772        let restored: NetworkConfigs = serde_json::from_str(&json).unwrap();
1773        assert!(restored.is_monad());
1774        assert!(!restored.is_tempo());
1775    }
1776
1777    #[test]
1778    #[cfg(feature = "monad")]
1779    fn serde_legacy_monad_bool_deserialized() {
1780        let json = r#"{"monad": true, "celo": false, "bypass_prevrandao": false}"#;
1781        let cfg: NetworkConfigs = serde_json::from_str(json).unwrap();
1782        assert!(cfg.is_monad());
1783    }
1784
1785    #[test]
1786    fn serde_serializes_legacy_alias_as_canonical_network() {
1787        #[cfg_attr(not(feature = "monad"), allow(unused_mut))]
1788        let mut cases = vec![(NetworkConfigs { tempo: true, ..Default::default() }, "tempo")];
1789        #[cfg(feature = "monad")]
1790        cases.push((NetworkConfigs { monad: true, ..Default::default() }, "monad"));
1791
1792        for (cfg, expected) in cases {
1793            let json = serde_json::to_value(cfg).unwrap();
1794            assert_eq!(json["network"], serde_json::json!(expected));
1795            assert!(json.get("tempo").is_none(), "legacy `tempo` key should not be serialized");
1796            assert!(json.get("monad").is_none(), "legacy `monad` key should not be serialized");
1797        }
1798    }
1799
1800    #[test]
1801    fn serde_new_network_field_deserialized() {
1802        let json_tempo = r#"{"network": "tempo", "celo": false, "bypass_prevrandao": false}"#;
1803        let cfg_tempo: NetworkConfigs = serde_json::from_str(json_tempo).unwrap();
1804        assert!(cfg_tempo.is_tempo());
1805
1806        #[cfg(feature = "monad")]
1807        {
1808            let json_monad = r#"{"network": "monad", "celo": false, "bypass_prevrandao": false}"#;
1809            let cfg_monad: NetworkConfigs = serde_json::from_str(json_monad).unwrap();
1810            assert!(cfg_monad.is_monad());
1811        }
1812    }
1813
1814    #[test]
1815    fn validates_flattened_network_selectors() {
1816        let valid = [
1817            NetworkConfigs::default(),
1818            NetworkConfigs::with_ethereum(),
1819            NetworkConfigs::with_celo(),
1820            NetworkConfigs::with_tempo(),
1821            NetworkConfigs {
1822                network: Some(NetworkVariant::Tempo),
1823                tempo: true,
1824                ..Default::default()
1825            },
1826        ];
1827        for networks in valid {
1828            networks.validate().unwrap();
1829        }
1830
1831        let conflicts = [
1832            (
1833                NetworkConfigs {
1834                    network: Some(NetworkVariant::Tempo),
1835                    celo: true,
1836                    ..Default::default()
1837                },
1838                "network selectors `network = \"tempo\"` and `celo = true` conflict",
1839            ),
1840            (
1841                NetworkConfigs { celo: true, tempo: true, ..Default::default() },
1842                "network selectors `celo = true` and `tempo = true` conflict",
1843            ),
1844        ];
1845        for (networks, expected) in conflicts {
1846            assert!(networks.validate().unwrap_err().contains(expected));
1847        }
1848    }
1849
1850    #[test]
1851    #[cfg(feature = "monad")]
1852    fn validates_flattened_monad_network_selectors() {
1853        for networks in [
1854            NetworkConfigs::with_monad(),
1855            NetworkConfigs {
1856                network: Some(NetworkVariant::Monad),
1857                monad: true,
1858                ..Default::default()
1859            },
1860        ] {
1861            networks.validate().unwrap();
1862        }
1863
1864        let conflicts = [
1865            (
1866                NetworkConfigs {
1867                    network: Some(NetworkVariant::Monad),
1868                    celo: true,
1869                    ..Default::default()
1870                },
1871                "network selectors `network = \"monad\"` and `celo = true` conflict",
1872            ),
1873            (
1874                NetworkConfigs {
1875                    network: Some(NetworkVariant::Monad),
1876                    tempo: true,
1877                    ..Default::default()
1878                },
1879                "network selectors `network = \"monad\"` and `tempo = true` conflict",
1880            ),
1881            (
1882                NetworkConfigs { celo: true, monad: true, ..Default::default() },
1883                "network selectors `celo = true` and `monad = true` conflict",
1884            ),
1885            (
1886                NetworkConfigs { tempo: true, monad: true, ..Default::default() },
1887                "network selectors `tempo = true` and `monad = true` conflict",
1888            ),
1889        ];
1890        for (networks, expected) in conflicts {
1891            assert!(networks.validate().unwrap_err().contains(expected));
1892        }
1893    }
1894
1895    #[test]
1896    #[cfg(feature = "monad")]
1897    fn chain_id_detects_monad_network() {
1898        assert_eq!(NetworkVariant::from(143), NetworkVariant::Monad);
1899        assert_eq!(NetworkVariant::from(10143), NetworkVariant::Monad);
1900
1901        assert!(NetworkConfigs::default().try_with_chain_id(143).unwrap().is_monad());
1902    }
1903
1904    #[cfg(feature = "base")]
1905    mod base {
1906        use super::*;
1907
1908        #[test]
1909        fn active_network_name_base() {
1910            let cfg = NetworkConfigs::with_base();
1911            assert_eq!(cfg.active_network_name(), Some("base"));
1912        }
1913
1914        #[test]
1915        fn base_fee_params_follow_canyon_boundary() {
1916            const CANYON_TIMESTAMP: u64 = 1_704_992_401;
1917
1918            let config = NetworkConfigs::with_base();
1919            assert_eq!(config.base_fee_params(CANYON_TIMESTAMP - 1), BaseFeeParams::new(50, 6));
1920            assert_eq!(config.base_fee_params(CANYON_TIMESTAMP), BaseFeeParams::new(250, 6));
1921        }
1922
1923        #[test]
1924        fn base_does_not_inherit_ethereum_blob_excess_gas() {
1925            let params = BlobParams::prague();
1926            assert_eq!(
1927                NetworkConfigs::with_base().next_block_blob_excess_gas(
1928                    params,
1929                    0,
1930                    params.target_blob_gas_per_block() + 1,
1931                    1,
1932                ),
1933                0
1934            );
1935        }
1936
1937        #[test]
1938        fn serde_roundtrip_base() {
1939            let original = NetworkConfigs::with_base();
1940            let json = serde_json::to_string(&original).unwrap();
1941            let restored: NetworkConfigs = serde_json::from_str(&json).unwrap();
1942            assert!(restored.is_base());
1943            assert!(!restored.is_tempo());
1944        }
1945
1946        #[test]
1947        fn serde_base_field_deserialized() {
1948            let json_base = r#"{"network": "base", "celo": false, "bypass_prevrandao": false}"#;
1949            let cfg_base: NetworkConfigs = serde_json::from_str(json_base).unwrap();
1950            assert!(cfg_base.is_base());
1951        }
1952
1953        #[test]
1954        fn chain_id_detects_base_networks() {
1955            assert_eq!(NetworkVariant::from(8453), NetworkVariant::Base);
1956            assert_eq!(NetworkVariant::from(84532), NetworkVariant::Base);
1957            assert!(NetworkConfigs::default().try_with_chain_id(8453).unwrap().is_base());
1958            assert_eq!(NetworkVariant::from_node_info_name("base").unwrap(), NetworkVariant::Base);
1959        }
1960
1961        #[test]
1962        fn hardfork_infers_base_network() {
1963            assert_eq!(
1964                NetworkConfigs::default()
1965                    .normalize_for_hardfork(FoundryHardfork::Base(BaseUpgrade::Beryl))
1966                    .unwrap()
1967                    .resolved_network(),
1968                Some(NetworkVariant::Base)
1969            );
1970        }
1971    }
1972
1973    #[cfg(feature = "optimism")]
1974    mod optimism {
1975        use super::*;
1976
1977        #[test]
1978        fn new_optimism_flag_equivalent_to_legacy() {
1979            let via_new =
1980                NetworkConfigs { network: Some(NetworkVariant::Optimism), ..Default::default() };
1981            let via_old = NetworkConfigs { optimism: true, ..Default::default() };
1982            assert_eq!(via_new.is_optimism(), via_old.is_optimism());
1983            assert_eq!(via_new.is_tempo(), via_old.is_tempo());
1984            assert_eq!(via_new.active_network_name(), via_old.active_network_name());
1985        }
1986
1987        #[test]
1988        fn matching_optimism_selectors_are_valid() {
1989            NetworkConfigs::with_optimism().validate().unwrap();
1990        }
1991
1992        #[test]
1993        fn active_network_name_optimism() {
1994            let cfg = NetworkConfigs::with_optimism();
1995            assert_eq!(cfg.active_network_name(), Some("optimism"));
1996        }
1997
1998        #[test]
1999        fn conflicting_optimism_and_tempo_selectors_are_rejected() {
2000            let cfg = NetworkConfigs {
2001                network: Some(NetworkVariant::Optimism),
2002                tempo: true,
2003                ..Default::default()
2004            };
2005            assert_eq!(
2006                cfg.validate().unwrap_err(),
2007                "network selectors `network = \"optimism\"` and `tempo = true` conflict; select \
2008                 only one network"
2009            );
2010        }
2011
2012        #[test]
2013        fn serde_roundtrip_optimism() {
2014            let original = NetworkConfigs::with_optimism();
2015            let json = serde_json::to_string(&original).unwrap();
2016            let restored: NetworkConfigs = serde_json::from_str(&json).unwrap();
2017            assert!(restored.is_optimism());
2018            assert!(!restored.is_tempo());
2019        }
2020
2021        #[test]
2022        fn serde_optimism_field_deserialized() {
2023            let json_optimism =
2024                r#"{"network": "optimism", "celo": false, "bypass_prevrandao": false}"#;
2025            let cfg_optimism: NetworkConfigs = serde_json::from_str(json_optimism).unwrap();
2026            assert!(cfg_optimism.is_optimism());
2027        }
2028    }
2029
2030    #[test]
2031    fn executed_hardfork_follows_the_network_family() {
2032        // A cross-namespace override runs as the configured network's hardfork, so the value used
2033        // to describe execution has to be coerced the same way.
2034        let prague = FoundryHardfork::Ethereum(EthereumHardfork::Prague);
2035        assert_eq!(NetworkConfigs::default().executed_hardfork(prague), prague);
2036        assert_eq!(
2037            NetworkConfigs::with_tempo().executed_hardfork(prague),
2038            FoundryHardfork::Tempo(TempoHardfork::from(prague))
2039        );
2040    }
2041}