Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: support u64 hex from str for BlockId #1396

Merged
merged 1 commit into from
Sep 28, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion crates/eips/src/eip1898.rs
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,8 @@ impl Display for BlockId {
pub enum ParseBlockIdError {
/// Failed to parse a block id from a number.
ParseIntError(ParseIntError),
/// Failed to parse hex number
ParseError(ParseError),
/// Failed to parse a block id as a hex string.
FromHexError(FromHexError),
}
Expand All @@ -552,6 +554,7 @@ impl Display for ParseBlockIdError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::ParseIntError(err) => write!(f, "{err}"),
Self::ParseError(err) => write!(f, "{err}"),
Self::FromHexError(err) => write!(f, "{err}"),
}
}
Expand All @@ -563,6 +566,7 @@ impl std::error::Error for ParseBlockIdError {
match self {
Self::ParseIntError(err) => std::error::Error::source(err),
Self::FromHexError(err) => std::error::Error::source(err),
Self::ParseError(err) => std::error::Error::source(err),
}
}
}
Expand All @@ -583,7 +587,11 @@ impl FromStr for BlockId {
type Err = ParseBlockIdError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.starts_with("0x") {
return B256::from_str(s).map(Into::into).map_err(ParseBlockIdError::FromHexError);
return if s.len() == 66 {
B256::from_str(s).map(Into::into).map_err(ParseBlockIdError::FromHexError)
} else {
U64::from_str(s).map(Into::into).map_err(ParseBlockIdError::ParseError)
};
}

match s {
Expand Down Expand Up @@ -796,6 +804,18 @@ mod tests {

const HASH: B256 = b256!("1a15e3c30cf094a99826869517b16d185d45831d3a494f01030b0001a9d3ebb9");

#[test]
fn block_id_from_str() {
assert_eq!("0x0".parse::<BlockId>().unwrap(), BlockId::number(0));
assert_eq!("0x24A931".parse::<BlockId>().unwrap(), BlockId::number(2402609));
assert_eq!(
"0x1a15e3c30cf094a99826869517b16d185d45831d3a494f01030b0001a9d3ebb9"
.parse::<BlockId>()
.unwrap(),
HASH.into()
);
}

#[test]
#[cfg(feature = "serde")]
fn compact_block_number_serde() {
Expand Down