alloy_rpc_types_eth/transaction/
mod.rs

1//! RPC types for transactions
2
3use alloy_consensus::{
4    EthereumTxEnvelope, EthereumTypedTransaction, Signed, TxEip1559, TxEip2930, TxEip4844,
5    TxEip4844Variant, TxEip7702, TxEnvelope, TxLegacy, Typed2718,
6};
7use alloy_eips::{eip2718::Encodable2718, eip7702::SignedAuthorization};
8use alloy_network_primitives::TransactionResponse;
9use alloy_primitives::{Address, BlockHash, Bytes, ChainId, TxKind, B256, U256};
10
11use alloy_consensus::transaction::Recovered;
12pub use alloy_consensus::{
13    transaction::TransactionInfo, BlobTransactionSidecar, Receipt, ReceiptEnvelope,
14    ReceiptWithBloom, Transaction as TransactionTrait,
15};
16pub use alloy_consensus_any::AnyReceiptEnvelope;
17pub use alloy_eips::{
18    eip2930::{AccessList, AccessListItem, AccessListResult},
19    eip7702::Authorization,
20};
21
22mod error;
23pub use error::ConversionError;
24
25mod receipt;
26pub use receipt::TransactionReceipt;
27
28pub mod request;
29pub use request::{TransactionInput, TransactionInputKind, TransactionRequest};
30
31/// Transaction object used in RPC.
32///
33/// This represents a transaction in RPC format (`eth_getTransactionByHash`) and contains the full
34/// transaction object and additional block metadata if the transaction has been mined.
35#[derive(Clone, Debug, PartialEq, Eq)]
36#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
37#[cfg_attr(all(any(test, feature = "arbitrary"), feature = "k256"), derive(arbitrary::Arbitrary))]
38#[cfg_attr(
39    feature = "serde",
40    serde(
41        into = "tx_serde::TransactionSerdeHelper<T>",
42        try_from = "tx_serde::TransactionSerdeHelper<T>",
43        bound = "T: TransactionTrait + Clone + serde::Serialize + serde::de::DeserializeOwned"
44    )
45)]
46#[doc(alias = "Tx")]
47pub struct Transaction<T = TxEnvelope> {
48    /// The inner transaction object
49    pub inner: Recovered<T>,
50
51    /// Hash of block where transaction was included, `None` if pending
52    pub block_hash: Option<BlockHash>,
53
54    /// Number of block where transaction was included, `None` if pending
55    pub block_number: Option<u64>,
56
57    /// Transaction Index
58    pub transaction_index: Option<u64>,
59
60    /// Deprecated effective gas price value.
61    pub effective_gas_price: Option<u128>,
62}
63
64impl<T> Default for Transaction<T>
65where
66    T: Default,
67{
68    fn default() -> Self {
69        Self {
70            inner: Recovered::new_unchecked(Default::default(), Default::default()),
71            block_hash: Default::default(),
72            block_number: Default::default(),
73            transaction_index: Default::default(),
74            effective_gas_price: Default::default(),
75        }
76    }
77}
78
79impl<T> Transaction<T> {
80    /// Consumes the type and returns the wrapped transaction.
81    pub fn into_inner(self) -> T {
82        self.inner.into_inner()
83    }
84
85    /// Consumes the type and returns a [`Recovered`] transaction with the sender
86    pub fn into_recovered(self) -> Recovered<T> {
87        self.inner
88    }
89
90    /// Returns a `Recovered<&T>` with the transaction and the sender.
91    pub const fn as_recovered(&self) -> Recovered<&T> {
92        self.inner.as_recovered_ref()
93    }
94
95    /// Converts the transaction type to the given alternative that is `From<T>`
96    pub fn convert<U>(self) -> Transaction<U>
97    where
98        U: From<T>,
99    {
100        self.map(U::from)
101    }
102
103    /// Converts the transaction to the given alternative that is `TryFrom<T>`
104    ///
105    /// Returns the transaction with the new transaction type if all conversions were successful.
106    pub fn try_convert<U>(self) -> Result<Transaction<U>, U::Error>
107    where
108        U: TryFrom<T>,
109    {
110        self.try_map(U::try_from)
111    }
112
113    /// Applies the given closure to the inner transaction type.
114    pub fn map<Tx>(self, f: impl FnOnce(T) -> Tx) -> Transaction<Tx> {
115        let Self { inner, block_hash, block_number, transaction_index, effective_gas_price } = self;
116        Transaction {
117            inner: inner.map(f),
118            block_hash,
119            block_number,
120            transaction_index,
121            effective_gas_price,
122        }
123    }
124
125    /// Applies the given fallible closure to the inner transactions.
126    pub fn try_map<Tx, E>(self, f: impl FnOnce(T) -> Result<Tx, E>) -> Result<Transaction<Tx>, E> {
127        let Self { inner, block_hash, block_number, transaction_index, effective_gas_price } = self;
128        Ok(Transaction {
129            inner: inner.try_map(f)?,
130            block_hash,
131            block_number,
132            transaction_index,
133            effective_gas_price,
134        })
135    }
136}
137
138impl<T> AsRef<T> for Transaction<T> {
139    fn as_ref(&self) -> &T {
140        &self.inner
141    }
142}
143
144impl<T> Transaction<T>
145where
146    T: TransactionTrait,
147{
148    /// Returns true if the transaction is a legacy or 2930 transaction.
149    pub fn is_legacy_gas(&self) -> bool {
150        self.inner.gas_price().is_some()
151    }
152
153    /// Converts a consensus `tx` with an additional context `tx_info` into an RPC [`Transaction`].
154    pub fn from_transaction(tx: Recovered<T>, tx_info: TransactionInfo) -> Self {
155        let TransactionInfo {
156            block_hash, block_number, index: transaction_index, base_fee, ..
157        } = tx_info;
158        let effective_gas_price = base_fee
159            .map(|base_fee| {
160                tx.effective_tip_per_gas(base_fee).unwrap_or_default() + base_fee as u128
161            })
162            .unwrap_or_else(|| tx.max_fee_per_gas());
163
164        Self {
165            inner: tx,
166            block_hash,
167            block_number,
168            transaction_index,
169            effective_gas_price: Some(effective_gas_price),
170        }
171    }
172}
173
174impl<T> Transaction<T>
175where
176    T: TransactionTrait + Encodable2718,
177{
178    /// Returns the [`TransactionInfo`] for this transaction.
179    ///
180    /// This contains various metadata about the transaction and block context if available.
181    pub fn info(&self) -> TransactionInfo {
182        TransactionInfo {
183            hash: Some(self.tx_hash()),
184            index: self.transaction_index,
185            block_hash: self.block_hash,
186            block_number: self.block_number,
187            // We don't know the base fee of the block when we're constructing this from
188            // `Transaction`
189            base_fee: None,
190        }
191    }
192}
193
194impl<T> Transaction<T>
195where
196    T: Into<TransactionRequest>,
197{
198    /// Converts [Transaction] into [TransactionRequest].
199    ///
200    /// During this conversion data for [TransactionRequest::sidecar] is not
201    /// populated as it is not part of [Transaction].
202    pub fn into_request(self) -> TransactionRequest {
203        self.inner.into_inner().into()
204    }
205}
206
207impl<Eip4844> Transaction<EthereumTxEnvelope<Eip4844>> {
208    /// Consumes the transaction and returns it as [`Signed`] with [`EthereumTypedTransaction`] as
209    /// the transaction type.
210    pub fn into_signed(self) -> Signed<EthereumTypedTransaction<Eip4844>>
211    where
212        EthereumTypedTransaction<Eip4844>: From<Eip4844>,
213    {
214        self.inner.into_inner().into_signed()
215    }
216
217    /// Consumes the transaction and returns it a [`Recovered`] signed [`EthereumTypedTransaction`].
218    pub fn into_signed_recovered(self) -> Recovered<Signed<EthereumTypedTransaction<Eip4844>>>
219    where
220        EthereumTypedTransaction<Eip4844>: From<Eip4844>,
221    {
222        self.inner.map(|tx| tx.into_signed())
223    }
224}
225
226impl<T> From<&Transaction<T>> for TransactionInfo
227where
228    T: TransactionTrait + Encodable2718,
229{
230    fn from(tx: &Transaction<T>) -> Self {
231        tx.info()
232    }
233}
234
235impl<T> From<Transaction<T>> for Recovered<T> {
236    fn from(tx: Transaction<T>) -> Self {
237        tx.into_recovered()
238    }
239}
240
241impl<Eip4844> TryFrom<Transaction<EthereumTxEnvelope<Eip4844>>> for Signed<TxLegacy> {
242    type Error = ConversionError;
243
244    fn try_from(tx: Transaction<EthereumTxEnvelope<Eip4844>>) -> Result<Self, Self::Error> {
245        match tx.inner.into_inner() {
246            EthereumTxEnvelope::Legacy(tx) => Ok(tx),
247            tx => Err(ConversionError::Custom(format!("expected Legacy, got {}", tx.tx_type()))),
248        }
249    }
250}
251
252impl<Eip4844> TryFrom<Transaction<EthereumTxEnvelope<Eip4844>>> for Signed<TxEip1559> {
253    type Error = ConversionError;
254
255    fn try_from(tx: Transaction<EthereumTxEnvelope<Eip4844>>) -> Result<Self, Self::Error> {
256        match tx.inner.into_inner() {
257            EthereumTxEnvelope::Eip1559(tx) => Ok(tx),
258            tx => Err(ConversionError::Custom(format!("expected Eip1559, got {}", tx.tx_type()))),
259        }
260    }
261}
262
263impl<Eip4844> TryFrom<Transaction<EthereumTxEnvelope<Eip4844>>> for Signed<TxEip2930> {
264    type Error = ConversionError;
265
266    fn try_from(tx: Transaction<EthereumTxEnvelope<Eip4844>>) -> Result<Self, Self::Error> {
267        match tx.inner.into_inner() {
268            EthereumTxEnvelope::Eip2930(tx) => Ok(tx),
269            tx => Err(ConversionError::Custom(format!("expected Eip2930, got {}", tx.tx_type()))),
270        }
271    }
272}
273
274impl TryFrom<Transaction> for Signed<TxEip4844> {
275    type Error = ConversionError;
276
277    fn try_from(tx: Transaction) -> Result<Self, Self::Error> {
278        let tx: Signed<TxEip4844Variant> = tx.try_into()?;
279
280        let (tx, sig, hash) = tx.into_parts();
281
282        Ok(Self::new_unchecked(tx.into(), sig, hash))
283    }
284}
285
286impl TryFrom<Transaction> for Signed<TxEip4844Variant> {
287    type Error = ConversionError;
288
289    fn try_from(tx: Transaction) -> Result<Self, Self::Error> {
290        match tx.inner.into_inner() {
291            TxEnvelope::Eip4844(tx) => Ok(tx),
292            tx => Err(ConversionError::Custom(format!(
293                "expected TxEip4844Variant, got {}",
294                tx.tx_type()
295            ))),
296        }
297    }
298}
299
300impl<Eip4844> TryFrom<Transaction<EthereumTxEnvelope<Eip4844>>> for Signed<TxEip7702> {
301    type Error = ConversionError;
302
303    fn try_from(tx: Transaction<EthereumTxEnvelope<Eip4844>>) -> Result<Self, Self::Error> {
304        match tx.inner.into_inner() {
305            EthereumTxEnvelope::Eip7702(tx) => Ok(tx),
306            tx => Err(ConversionError::Custom(format!("expected Eip7702, got {}", tx.tx_type()))),
307        }
308    }
309}
310
311impl<Eip4844, Other> From<Transaction<EthereumTxEnvelope<Eip4844>>> for EthereumTxEnvelope<Other>
312where
313    Self: From<EthereumTxEnvelope<Eip4844>>,
314{
315    fn from(tx: Transaction<EthereumTxEnvelope<Eip4844>>) -> Self {
316        tx.inner.into_inner().into()
317    }
318}
319
320impl<Eip4844, Other> From<Transaction<EthereumTypedTransaction<Eip4844>>>
321    for EthereumTypedTransaction<Other>
322where
323    Self: From<EthereumTypedTransaction<Eip4844>>,
324{
325    fn from(tx: Transaction<EthereumTypedTransaction<Eip4844>>) -> Self {
326        tx.inner.into_inner().into()
327    }
328}
329
330impl<Eip4844> From<Transaction<EthereumTxEnvelope<Eip4844>>>
331    for Signed<EthereumTypedTransaction<Eip4844>>
332where
333    EthereumTypedTransaction<Eip4844>: From<Eip4844>,
334{
335    fn from(tx: Transaction<EthereumTxEnvelope<Eip4844>>) -> Self {
336        tx.into_signed()
337    }
338}
339
340impl<T: TransactionTrait> TransactionTrait for Transaction<T> {
341    fn chain_id(&self) -> Option<ChainId> {
342        self.inner.chain_id()
343    }
344
345    fn nonce(&self) -> u64 {
346        self.inner.nonce()
347    }
348
349    fn gas_limit(&self) -> u64 {
350        self.inner.gas_limit()
351    }
352
353    fn gas_price(&self) -> Option<u128> {
354        self.inner.gas_price()
355    }
356
357    fn max_fee_per_gas(&self) -> u128 {
358        self.inner.max_fee_per_gas()
359    }
360
361    fn max_priority_fee_per_gas(&self) -> Option<u128> {
362        self.inner.max_priority_fee_per_gas()
363    }
364
365    fn max_fee_per_blob_gas(&self) -> Option<u128> {
366        self.inner.max_fee_per_blob_gas()
367    }
368
369    fn priority_fee_or_price(&self) -> u128 {
370        self.inner.priority_fee_or_price()
371    }
372
373    fn effective_gas_price(&self, base_fee: Option<u64>) -> u128 {
374        self.inner.effective_gas_price(base_fee)
375    }
376
377    fn is_dynamic_fee(&self) -> bool {
378        self.inner.is_dynamic_fee()
379    }
380
381    fn kind(&self) -> TxKind {
382        self.inner.kind()
383    }
384
385    fn is_create(&self) -> bool {
386        self.inner.is_create()
387    }
388
389    fn value(&self) -> U256 {
390        self.inner.value()
391    }
392
393    fn input(&self) -> &Bytes {
394        self.inner.input()
395    }
396
397    fn access_list(&self) -> Option<&AccessList> {
398        self.inner.access_list()
399    }
400
401    fn blob_versioned_hashes(&self) -> Option<&[B256]> {
402        self.inner.blob_versioned_hashes()
403    }
404
405    fn authorization_list(&self) -> Option<&[SignedAuthorization]> {
406        self.inner.authorization_list()
407    }
408}
409
410impl<T: TransactionTrait + Encodable2718> TransactionResponse for Transaction<T> {
411    fn tx_hash(&self) -> B256 {
412        self.inner.trie_hash()
413    }
414
415    fn block_hash(&self) -> Option<BlockHash> {
416        self.block_hash
417    }
418
419    fn block_number(&self) -> Option<u64> {
420        self.block_number
421    }
422
423    fn transaction_index(&self) -> Option<u64> {
424        self.transaction_index
425    }
426
427    fn from(&self) -> Address {
428        self.inner.signer()
429    }
430}
431
432impl<T: Typed2718> Typed2718 for Transaction<T> {
433    fn ty(&self) -> u8 {
434        self.inner.ty()
435    }
436}
437
438#[cfg(feature = "serde")]
439mod tx_serde {
440    //! Helper module for serializing and deserializing OP [`Transaction`].
441    //!
442    //! This is needed because we might need to deserialize the `gasPrice` field into both
443    //! [`crate::Transaction::effective_gas_price`] and [`alloy_consensus::TxLegacy::gas_price`].
444    use super::*;
445    use serde::{Deserialize, Serialize};
446
447    /// Helper struct which will be flattened into the transaction and will only contain `gasPrice`
448    /// field if inner [`TxEnvelope`] did not consume it.
449    #[derive(Serialize, Deserialize)]
450    struct MaybeGasPrice {
451        #[serde(
452            default,
453            rename = "gasPrice",
454            skip_serializing_if = "Option::is_none",
455            with = "alloy_serde::quantity::opt"
456        )]
457        pub effective_gas_price: Option<u128>,
458    }
459
460    #[derive(Serialize, Deserialize)]
461    #[serde(rename_all = "camelCase")]
462    pub(crate) struct TransactionSerdeHelper<T> {
463        #[serde(flatten)]
464        inner: T,
465        #[serde(default)]
466        block_hash: Option<BlockHash>,
467        #[serde(default, with = "alloy_serde::quantity::opt")]
468        block_number: Option<u64>,
469        #[serde(default, with = "alloy_serde::quantity::opt")]
470        transaction_index: Option<u64>,
471        /// Sender
472        from: Address,
473
474        #[serde(flatten)]
475        gas_price: MaybeGasPrice,
476    }
477
478    impl<T: TransactionTrait> From<Transaction<T>> for TransactionSerdeHelper<T> {
479        fn from(value: Transaction<T>) -> Self {
480            let Transaction {
481                inner,
482                block_hash,
483                block_number,
484                transaction_index,
485                effective_gas_price,
486            } = value;
487
488            let (inner, from) = inner.into_parts();
489
490            // if inner transaction has its own `gasPrice` don't serialize it in this struct.
491            let effective_gas_price = effective_gas_price.filter(|_| inner.gas_price().is_none());
492
493            Self {
494                inner,
495                block_hash,
496                block_number,
497                transaction_index,
498                from,
499                gas_price: MaybeGasPrice { effective_gas_price },
500            }
501        }
502    }
503
504    impl<T: TransactionTrait> TryFrom<TransactionSerdeHelper<T>> for Transaction<T> {
505        type Error = serde_json::Error;
506
507        fn try_from(value: TransactionSerdeHelper<T>) -> Result<Self, Self::Error> {
508            let TransactionSerdeHelper {
509                inner,
510                block_hash,
511                block_number,
512                transaction_index,
513                from,
514                gas_price,
515            } = value;
516
517            // Try to get `gasPrice` field from inner envelope or from `MaybeGasPrice`, otherwise
518            // return error
519            let effective_gas_price = inner.gas_price().or(gas_price.effective_gas_price);
520
521            Ok(Self {
522                inner: Recovered::new_unchecked(inner, from),
523                block_hash,
524                block_number,
525                transaction_index,
526                effective_gas_price,
527            })
528        }
529    }
530}
531
532#[cfg(test)]
533mod tests {
534    use super::*;
535
536    #[allow(unused)]
537    fn assert_convert_into_envelope(tx: Transaction) -> TxEnvelope {
538        tx.into()
539    }
540    #[allow(unused)]
541    fn assert_convert_into_consensus(tx: Transaction) -> EthereumTxEnvelope<TxEip4844> {
542        tx.into()
543    }
544
545    #[allow(unused)]
546    fn assert_convert_into_typed(
547        tx: Transaction<EthereumTypedTransaction<TxEip4844>>,
548    ) -> EthereumTypedTransaction<TxEip4844> {
549        tx.into()
550    }
551
552    #[test]
553    #[cfg(feature = "serde")]
554    fn into_request_legacy() {
555        // cast rpc eth_getTransactionByHash
556        // 0xe9e91f1ee4b56c0df2e9f06c2b8c27c6076195a88a7b8537ba8313d80e6f124e --rpc-url mainnet
557        let rpc_tx = r#"{"blockHash":"0x8e38b4dbf6b11fcc3b9dee84fb7986e29ca0a02cecd8977c161ff7333329681e","blockNumber":"0xf4240","hash":"0xe9e91f1ee4b56c0df2e9f06c2b8c27c6076195a88a7b8537ba8313d80e6f124e","transactionIndex":"0x1","type":"0x0","nonce":"0x43eb","input":"0x","r":"0x3b08715b4403c792b8c7567edea634088bedcd7f60d9352b1f16c69830f3afd5","s":"0x10b9afb67d2ec8b956f0e1dbc07eb79152904f3a7bf789fc869db56320adfe09","chainId":"0x0","v":"0x1c","gas":"0xc350","from":"0x32be343b94f860124dc4fee278fdcbd38c102d88","to":"0xdf190dc7190dfba737d7777a163445b7fff16133","value":"0x6113a84987be800","gasPrice":"0xdf8475800"}"#;
558
559        let tx = serde_json::from_str::<Transaction>(rpc_tx).unwrap();
560        let request = tx.into_request();
561        assert!(request.gas_price.is_some());
562        assert!(request.max_fee_per_gas.is_none());
563    }
564
565    #[test]
566    #[cfg(feature = "serde")]
567    fn into_request_eip1559() {
568        // cast rpc eth_getTransactionByHash
569        // 0x0e07d8b53ed3d91314c80e53cf25bcde02084939395845cbb625b029d568135c --rpc-url mainnet
570        let rpc_tx = r#"{"blockHash":"0x883f974b17ca7b28cb970798d1c80f4d4bb427473dc6d39b2a7fe24edc02902d","blockNumber":"0xe26e6d","hash":"0x0e07d8b53ed3d91314c80e53cf25bcde02084939395845cbb625b029d568135c","accessList":[],"transactionIndex":"0xad","type":"0x2","nonce":"0x16d","input":"0x5ae401dc00000000000000000000000000000000000000000000000000000000628ced5b000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000016000000000000000000000000000000000000000000000000000000000000000e442712a6700000000000000000000000000000000000000000000b3ff1489674e11c40000000000000000000000000000000000000000000000000000004a6ed55bbcc18000000000000000000000000000000000000000000000000000000000000000800000000000000000000000003cf412d970474804623bb4e3a42de13f9bca54360000000000000000000000000000000000000000000000000000000000000002000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc20000000000000000000000003a75941763f31c930b19c041b709742b0b31ebb600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000412210e8a00000000000000000000000000000000000000000000000000000000","r":"0x7f2153019a74025d83a73effdd91503ceecefac7e35dd933adc1901c875539aa","s":"0x334ab2f714796d13c825fddf12aad01438db3a8152b2fe3ef7827707c25ecab3","chainId":"0x1","v":"0x0","gas":"0x46a02","maxPriorityFeePerGas":"0x59682f00","from":"0x3cf412d970474804623bb4e3a42de13f9bca5436","to":"0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45","maxFeePerGas":"0x7fc1a20a8","value":"0x4a6ed55bbcc180","gasPrice":"0x50101df3a"}"#;
571
572        let tx = serde_json::from_str::<Transaction>(rpc_tx).unwrap();
573        let request = tx.into_request();
574        assert!(request.gas_price.is_none());
575        assert!(request.max_fee_per_gas.is_some());
576    }
577
578    #[test]
579    #[cfg(feature = "serde")]
580    fn serde_tx_from_contract_mod() {
581        let rpc_tx = r#"{"hash":"0x018b2331d461a4aeedf6a1f9cc37463377578244e6a35216057a8370714e798f","nonce":"0x1","blockHash":"0x6e4e53d1de650d5a5ebed19b38321db369ef1dc357904284ecf4d89b8834969c","blockNumber":"0x2","transactionIndex":"0x0","from":"0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266","to":"0x5fbdb2315678afecb367f032d93f642f64180aa3","value":"0x0","gasPrice":"0x3a29f0f8","gas":"0x1c9c380","maxFeePerGas":"0xba43b7400","maxPriorityFeePerGas":"0x5f5e100","input":"0xd09de08a","r":"0xd309309a59a49021281cb6bb41d164c96eab4e50f0c1bd24c03ca336e7bc2bb7","s":"0x28a7f089143d0a1355ebeb2a1b9f0e5ad9eca4303021c1400d61bc23c9ac5319","v":"0x0","yParity":"0x0","chainId":"0x7a69","accessList":[],"type":"0x2"}"#;
582
583        let tx = serde_json::from_str::<Transaction>(rpc_tx).unwrap();
584        assert_eq!(tx.block_number, Some(2));
585    }
586
587    #[test]
588    #[cfg(feature = "serde")]
589    fn test_gas_price_present() {
590        let blob_rpc_tx = r#"{"blockHash":"0x1732a5fe86d54098c431fa4fea34387b650e41dbff65ca554370028172fcdb6a","blockNumber":"0x3","from":"0x7435ed30a8b4aeb0877cef0c6e8cffe834eb865f","gas":"0x186a0","gasPrice":"0x281d620e","maxFeePerGas":"0x281d620e","maxPriorityFeePerGas":"0x1","maxFeePerBlobGas":"0x20000","hash":"0xb0ebf0d8fca6724d5111d0be9ac61f0e7bf174208e0fafcb653f337c72465b83","input":"0xdc4c8669df128318656d6974","nonce":"0x8","to":"0x7dcd17433742f4c0ca53122ab541d0ba67fc27df","transactionIndex":"0x0","value":"0x3","type":"0x3","accessList":[{"address":"0x7dcd17433742f4c0ca53122ab541d0ba67fc27df","storageKeys":["0x0000000000000000000000000000000000000000000000000000000000000000","0x462708a3c1cd03b21605715d090136df64e227f7e7792f74bb1bd7a8288f8801"]}],"chainId":"0xc72dd9d5e883e","blobVersionedHashes":["0x015a4cab4911426699ed34483de6640cf55a568afc5c5edffdcbd8bcd4452f68"],"v":"0x0","r":"0x478385a47075dd6ba56300b623038052a6e4bb03f8cfc53f367712f1c1d3e7de","s":"0x2f79ed9b154b0af2c97ddfc1f4f76e6c17725713b6d44ea922ca4c6bbc20775c","yParity":"0x0"}"#;
591        let legacy_rpc_tx = r#"{"blockHash":"0x7e5d03caac4eb2b613ae9c919ef3afcc8ed0e384f31ee746381d3c8739475d2a","blockNumber":"0x4","from":"0x7435ed30a8b4aeb0877cef0c6e8cffe834eb865f","gas":"0x5208","gasPrice":"0x23237dee","hash":"0x3f38cdc805c02e152bfed34471a3a13a786fed436b3aec0c3eca35d23e2cdd2c","input":"0x","nonce":"0xc","to":"0x4dde844b71bcdf95512fb4dc94e84fb67b512ed8","transactionIndex":"0x0","value":"0x1","type":"0x0","chainId":"0xc72dd9d5e883e","v":"0x18e5bb3abd10a0","r":"0x3d61f5d7e93eecd0669a31eb640ab3349e9e5868a44c2be1337c90a893b51990","s":"0xc55f44ba123af37d0e73ed75e578647c3f473805349936f64ea902ea9e03bc7"}"#;
592
593        let blob_tx = serde_json::from_str::<Transaction>(blob_rpc_tx).unwrap();
594        assert_eq!(blob_tx.block_number, Some(3));
595        assert_eq!(blob_tx.effective_gas_price, Some(0x281d620e));
596
597        let legacy_tx = serde_json::from_str::<Transaction>(legacy_rpc_tx).unwrap();
598        assert_eq!(legacy_tx.block_number, Some(4));
599        assert_eq!(legacy_tx.effective_gas_price, Some(0x23237dee));
600    }
601
602    // <https://github.com/alloy-rs/alloy/issues/1643>
603    #[test]
604    #[cfg(feature = "serde")]
605    fn deserialize_7702_v() {
606        let raw = r#"{"blockHash":"0xb14eac260f0cb7c3bbf4c9ff56034defa4f566780ed3e44b7a79b6365d02887c","blockNumber":"0xb022","from":"0x6d2d4e1c2326a069f36f5d6337470dc26adb7156","gas":"0xf8ac","gasPrice":"0xe07899f","maxFeePerGas":"0xe0789a0","maxPriorityFeePerGas":"0xe078998","hash":"0xadc3f24d05f05f1065debccb1c4b033eaa35917b69b343d88d9062cdf8ecad83","input":"0x","nonce":"0x1a","to":"0x6d2d4e1c2326a069f36f5d6337470dc26adb7156","transactionIndex":"0x0","value":"0x0","type":"0x4","accessList":[],"chainId":"0x1a5ee289c","authorizationList":[{"chainId":"0x1a5ee289c","address":"0x529f773125642b12a44bd543005650989eceaa2a","nonce":"0x1a","v":"0x0","r":"0x9b3de20cf8bd07f3c5c55c38c920c146f081bc5ab4580d0c87786b256cdab3c2","s":"0x74841956f4832bace3c02aed34b8f0a2812450da3728752edbb5b5e1da04497"}],"v":"0x1","r":"0xb3bf7d6877864913bba04d6f93d98009a5af16ee9c12295cd634962a2346b67c","s":"0x31ca4a874afa964ec7643e58c6b56b35b1bcc7698eb1b5e15e61e78b353bd42d","yParity":"0x1"}"#;
607        let tx = serde_json::from_str::<Transaction>(raw).unwrap();
608        assert!(tx.inner.is_eip7702());
609    }
610}