From 092bd96a39abc2965cec9756967db6310b8fba88 Mon Sep 17 00:00:00 2001 From: Tarrence van As Date: Tue, 11 Jan 2022 01:31:09 -0800 Subject: [PATCH] feat(chain): enum values + TryFrom (#782) * feat(chain): map Chain enum to values * feat(chain): support TryFrom * chore: use parsechain error for the try_from impl Co-authored-by: Georgios Konstantopoulos --- ethers-core/src/types/chain.rs | 79 +++++++++++++++++++--------------- 1 file changed, 45 insertions(+), 34 deletions(-) diff --git a/ethers-core/src/types/chain.rs b/ethers-core/src/types/chain.rs index 217e2d3b..c522b1e5 100644 --- a/ethers-core/src/types/chain.rs +++ b/ethers-core/src/types/chain.rs @@ -1,6 +1,7 @@ use serde::Deserialize; use thiserror::Error; +use core::convert::TryFrom; use std::{fmt, str::FromStr}; use crate::types::U256; @@ -9,25 +10,26 @@ use crate::types::U256; #[error("Failed to parse chain: {0}")] pub struct ParseChainError(String); +#[repr(u64)] #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Chain { - Mainnet, - Ropsten, - Rinkeby, - Goerli, - Kovan, - XDai, - Polygon, - PolygonMumbai, - Avalanche, - AvalancheFuji, - Sepolia, - Moonbeam, - MoonbeamDev, - Moonriver, - Optimism, - OptimismKovan, + Mainnet = 1, + Ropsten = 3, + Rinkeby = 4, + Goerli = 5, + Kovan = 42, + XDai = 100, + Polygon = 137, + PolygonMumbai = 80001, + Avalanche = 43114, + AvalancheFuji = 43113, + Sepolia = 11155111, + Moonbeam = 1287, + MoonbeamDev = 1281, + Moonriver = 1285, + Optimism = 10, + OptimismKovan = 69, } impl fmt::Display for Chain { @@ -38,24 +40,7 @@ impl fmt::Display for Chain { impl From for u32 { fn from(chain: Chain) -> Self { - match chain { - Chain::Mainnet => 1, - Chain::Ropsten => 3, - Chain::Rinkeby => 4, - Chain::Goerli => 5, - Chain::Kovan => 42, - Chain::XDai => 100, - Chain::Polygon => 137, - Chain::PolygonMumbai => 80001, - Chain::Avalanche => 43114, - Chain::AvalancheFuji => 43113, - Chain::Sepolia => 11155111, - Chain::Moonbeam => 1287, - Chain::MoonbeamDev => 1281, - Chain::Moonriver => 1285, - Chain::Optimism => 10, - Chain::OptimismKovan => 69, - } + chain as u32 } } @@ -71,6 +56,32 @@ impl From for u64 { } } +impl TryFrom for Chain { + type Error = ParseChainError; + + fn try_from(chain: u64) -> Result { + match chain { + 1 => Ok(Chain::Mainnet), + 3 => Ok(Chain::Ropsten), + 4 => Ok(Chain::Rinkeby), + 5 => Ok(Chain::Goerli), + 42 => Ok(Chain::Kovan), + 100 => Ok(Chain::XDai), + 137 => Ok(Chain::Polygon), + 80001 => Ok(Chain::PolygonMumbai), + 43114 => Ok(Chain::Avalanche), + 43113 => Ok(Chain::AvalancheFuji), + 11155111 => Ok(Chain::Sepolia), + 1287 => Ok(Chain::Moonbeam), + 1281 => Ok(Chain::MoonbeamDev), + 1285 => Ok(Chain::Moonriver), + 10 => Ok(Chain::Optimism), + 69 => Ok(Chain::OptimismKovan), + _ => return Err(ParseChainError(chain.to_string())), + } + } +} + impl FromStr for Chain { type Err = ParseChainError; fn from_str(chain: &str) -> Result {