feat(chain): enum values + TryFrom<u64> (#782)

* feat(chain): map Chain enum to values

* feat(chain): support TryFrom<u64>

* chore: use parsechain error for the try_from impl

Co-authored-by: Georgios Konstantopoulos <me@gakonst.com>
This commit is contained in:
Tarrence van As 2022-01-11 01:31:09 -08:00 committed by GitHub
parent e3c86231de
commit 092bd96a39
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 45 additions and 34 deletions

View File

@ -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<Chain> 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<Chain> for u64 {
}
}
impl TryFrom<u64> for Chain {
type Error = ParseChainError;
fn try_from(chain: u64) -> Result<Chain, Self::Error> {
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<Self, Self::Err> {