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

Add try_from method for TxType with U64 #7291

Merged
merged 2 commits into from Mar 22, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
41 changes: 40 additions & 1 deletion crates/primitives/src/transaction/tx_type.rs
@@ -1,4 +1,4 @@
use crate::U8;
use crate::{U64, U8};
use bytes::Buf;
use reth_codecs::{derive_arbitrary, Compact};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -103,6 +103,23 @@ impl TryFrom<u8> for TxType {
}
}

impl TryFrom<u64> for TxType {
type Error = &'static str;

fn try_from(value: u64) -> Result<Self, Self::Error> {
let value: u8 = value.try_into().map_err(|_| "invalid tx type")?;
Self::try_from(value)
}
}

impl TryFrom<U64> for TxType {
type Error = &'static str;
tcoratger marked this conversation as resolved.
Show resolved Hide resolved

fn try_from(value: U64) -> Result<Self, Self::Error> {
value.to::<u64>().try_into()
}
}

impl Compact for TxType {
fn to_compact<B>(self, buf: &mut B) -> usize
where
Expand Down Expand Up @@ -156,6 +173,28 @@ impl Compact for TxType {
mod tests {
use super::*;

#[test]
fn test_u64_to_tx_type() {
// Test for Legacy transaction
assert_eq!(TxType::try_from(U64::from(0)).unwrap(), TxType::Legacy);

// Test for EIP2930 transaction
assert_eq!(TxType::try_from(U64::from(1)).unwrap(), TxType::Eip2930);

// Test for EIP1559 transaction
assert_eq!(TxType::try_from(U64::from(2)).unwrap(), TxType::Eip1559);

// Test for EIP4844 transaction
assert_eq!(TxType::try_from(U64::from(3)).unwrap(), TxType::Eip4844);

// Test for Deposit transaction
#[cfg(feature = "optimism")]
assert_eq!(TxType::try_from(U64::from(126)).unwrap(), TxType::Deposit);

// For transactions with unsupported values
assert!(TxType::try_from(U64::from(4)).is_err());
}

#[test]
fn test_txtype_to_compat() {
let cases = vec![
Expand Down