From 30d79a98aabcc6385beb6548f7cce9ebd85347ca Mon Sep 17 00:00:00 2001 From: Thomas Coratger <60488569+tcoratger@users.noreply.github.com> Date: Fri, 22 Mar 2024 15:04:54 +0100 Subject: [PATCH] Add `try_from` method for `TxType` with `U64` (#7291) --- crates/primitives/src/transaction/tx_type.rs | 41 +++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/crates/primitives/src/transaction/tx_type.rs b/crates/primitives/src/transaction/tx_type.rs index 79179128bb26..8bb6c6956e71 100644 --- a/crates/primitives/src/transaction/tx_type.rs +++ b/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}; @@ -103,6 +103,23 @@ impl TryFrom for TxType { } } +impl TryFrom for TxType { + type Error = &'static str; + + fn try_from(value: u64) -> Result { + let value: u8 = value.try_into().map_err(|_| "invalid tx type")?; + Self::try_from(value) + } +} + +impl TryFrom for TxType { + type Error = &'static str; + + fn try_from(value: U64) -> Result { + value.to::().try_into() + } +} + impl Compact for TxType { fn to_compact(self, buf: &mut B) -> usize where @@ -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![