From 96ef787230d57686b65547ae1e3c464fde1081f0 Mon Sep 17 00:00:00 2001 From: "odyslam.eth" Date: Tue, 4 Jan 2022 01:51:01 +0300 Subject: [PATCH] feat: add FromStr impl for Chain (#756) * feat: add FromStr impl for Chain * fix(core): return error if chain not found Co-authored-by: Georgios Konstantopoulos --- ethers-core/src/types/chain.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/ethers-core/src/types/chain.rs b/ethers-core/src/types/chain.rs index 30b85093..2a1ad903 100644 --- a/ethers-core/src/types/chain.rs +++ b/ethers-core/src/types/chain.rs @@ -1,6 +1,12 @@ use std::fmt; +use thiserror::Error; use crate::types::U256; +use std::str::FromStr; + +#[derive(Debug, Clone, Error)] +#[error("Failed to parse chain: {0}")] +pub struct ParseChainError(String); #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum Chain { @@ -62,3 +68,28 @@ impl From for u64 { u32::from(chain).into() } } + +impl FromStr for Chain { + type Err = ParseChainError; + fn from_str(chain: &str) -> Result { + Ok(match chain { + "mainnet" => Chain::Mainnet, + "ropsten" => Chain::Ropsten, + "rinkeby" => Chain::Rinkeby, + "goerli" => Chain::Goerli, + "kovan" => Chain::Kovan, + "xdai" => Chain::XDai, + "polygon" => Chain::Polygon, + "polygon-mumbai" => Chain::PolygonMumbai, + "avalanche" => Chain::Avalanche, + "avalanche-fuji" => Chain::AvalancheFuji, + "sepolia" => Chain::Sepolia, + "moonbeam" => Chain::Moonbeam, + "moonbeam-dev" => Chain::MoonbeamDev, + "moonriver" => Chain::Moonriver, + "optimism" => Chain::Optimism, + "optimism-kovan" => Chain::OptimismKovan, + _ => return Err(ParseChainError(chain.to_owned())), + }) + } +}