use std::{path::PathBuf, sync::Arc};
use alloy_genesis::Genesis;
use reth_chainspec::ChainSpec;
#[cfg(not(feature = "optimism"))]
use reth_chainspec::{DEV, HOLESKY, MAINNET, SEPOLIA};
use reth_cli::chainspec::ChainSpecParser;
use reth_fs_util as fs;
#[cfg(feature = "optimism")]
use reth_optimism_chainspec::{BASE_MAINNET, BASE_SEPOLIA, OP_DEV, OP_MAINNET, OP_SEPOLIA};
#[cfg(feature = "optimism")]
pub const SUPPORTED_CHAINS: &[&str] =
&["optimism", "optimism-sepolia", "base", "base-sepolia", "dev"];
#[cfg(not(feature = "optimism"))]
pub const SUPPORTED_CHAINS: &[&str] = &["mainnet", "sepolia", "holesky", "dev"];
#[cfg(not(feature = "optimism"))]
pub fn chain_value_parser(s: &str) -> eyre::Result<Arc<ChainSpec>, eyre::Error> {
Ok(match s {
"mainnet" => MAINNET.clone(),
"sepolia" => SEPOLIA.clone(),
"holesky" => HOLESKY.clone(),
"dev" => DEV.clone(),
_ => Arc::new(parse_custom_chain_spec(s)?),
})
}
#[cfg(feature = "optimism")]
pub fn chain_value_parser(s: &str) -> eyre::Result<Arc<ChainSpec>, eyre::Error> {
Ok(Arc::new(match s {
"optimism" => OP_MAINNET.inner.clone(),
"optimism_sepolia" | "optimism-sepolia" => OP_SEPOLIA.inner.clone(),
"base" => BASE_MAINNET.inner.clone(),
"base_sepolia" | "base-sepolia" => BASE_SEPOLIA.inner.clone(),
"dev" => OP_DEV.inner.clone(),
_ => parse_custom_chain_spec(s)?,
}))
}
pub fn parse_custom_chain_spec(s: &str) -> eyre::Result<ChainSpec, eyre::Error> {
let raw = match fs::read_to_string(PathBuf::from(shellexpand::full(s)?.into_owned())) {
Ok(raw) => raw,
Err(io_err) => {
if s.contains('{') {
s.to_string()
} else {
return Err(io_err.into()) }
}
};
let genesis: Genesis = serde_json::from_str(&raw)?;
Ok(genesis.into())
}
#[derive(Debug, Clone, Default)]
pub struct DefaultChainSpecParser;
impl ChainSpecParser for DefaultChainSpecParser {
type ChainSpec = ChainSpec;
const SUPPORTED_CHAINS: &'static [&'static str] = SUPPORTED_CHAINS;
fn parse(s: &str) -> eyre::Result<Arc<ChainSpec>> {
chain_value_parser(s)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_known_chain_spec() {
for chain in SUPPORTED_CHAINS {
chain_value_parser(chain).unwrap();
}
}
}