alloy_consensus/transaction/
eip4844.rs

1use super::{RlpEcdsaDecodableTx, RlpEcdsaEncodableTx, TxEip4844Sidecar};
2use crate::{SignableTransaction, Signed, Transaction, TxType};
3use alloc::vec::Vec;
4use alloy_eips::{
5    eip2718::IsTyped2718,
6    eip2930::AccessList,
7    eip4844::{BlobTransactionSidecar, DATA_GAS_PER_BLOB},
8    eip7594::{Decodable7594, Encodable7594},
9    eip7702::SignedAuthorization,
10    Typed2718,
11};
12use alloy_primitives::{Address, Bytes, ChainId, Signature, TxKind, B256, U256};
13use alloy_rlp::{BufMut, Decodable, Encodable, Header};
14use core::fmt;
15
16#[cfg(feature = "kzg")]
17use alloy_eips::eip4844::BlobTransactionValidationError;
18use alloy_eips::eip7594::{BlobTransactionSidecarEip7594, BlobTransactionSidecarVariant};
19
20/// [EIP-4844 Blob Transaction](https://eips.ethereum.org/EIPS/eip-4844#blob-transaction)
21///
22/// A transaction with blob hashes and max blob fee.
23/// It can either be a standalone transaction, mainly seen when retrieving historical transactions,
24/// or a transaction with a sidecar, which is used when submitting a transaction to the network and
25/// when receiving and sending transactions during the gossip stage.
26#[derive(Clone, Debug, PartialEq, Eq, Hash)]
27#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
28#[cfg_attr(feature = "serde", derive(serde::Serialize))]
29#[cfg_attr(feature = "serde", serde(untagged))]
30#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
31#[doc(alias = "Eip4844TransactionVariant")]
32pub enum TxEip4844Variant<T = BlobTransactionSidecar> {
33    /// A standalone transaction with blob hashes and max blob fee.
34    TxEip4844(TxEip4844),
35    /// A transaction with a sidecar, which contains the blob data, commitments, and proofs.
36    TxEip4844WithSidecar(TxEip4844WithSidecar<T>),
37}
38
39#[cfg(feature = "serde")]
40impl<'de, T: serde::Deserialize<'de>> serde::Deserialize<'de> for TxEip4844Variant<T> {
41    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
42    where
43        D: serde::Deserializer<'de>,
44    {
45        #[derive(serde::Deserialize)]
46        struct TxEip4844SerdeHelper<Sidecar> {
47            #[serde(flatten)]
48            #[doc(alias = "transaction")]
49            tx: TxEip4844,
50            #[serde(flatten)]
51            sidecar: Option<Sidecar>,
52        }
53
54        let tx = TxEip4844SerdeHelper::<T>::deserialize(deserializer)?;
55
56        if let Some(sidecar) = tx.sidecar {
57            Ok(TxEip4844WithSidecar::from_tx_and_sidecar(tx.tx, sidecar).into())
58        } else {
59            Ok(tx.tx.into())
60        }
61    }
62}
63
64impl<T> From<Signed<TxEip4844>> for Signed<TxEip4844Variant<T>> {
65    fn from(value: Signed<TxEip4844>) -> Self {
66        let (tx, signature, hash) = value.into_parts();
67        Self::new_unchecked(TxEip4844Variant::TxEip4844(tx), signature, hash)
68    }
69}
70
71impl<T: Encodable7594> From<Signed<TxEip4844WithSidecar<T>>> for Signed<TxEip4844Variant<T>> {
72    fn from(value: Signed<TxEip4844WithSidecar<T>>) -> Self {
73        let (tx, signature, hash) = value.into_parts();
74        Self::new_unchecked(TxEip4844Variant::TxEip4844WithSidecar(tx), signature, hash)
75    }
76}
77
78impl From<TxEip4844Variant<BlobTransactionSidecar>>
79    for TxEip4844Variant<BlobTransactionSidecarVariant>
80{
81    fn from(value: TxEip4844Variant<BlobTransactionSidecar>) -> Self {
82        value.map_sidecar(Into::into)
83    }
84}
85
86impl From<TxEip4844Variant<BlobTransactionSidecarEip7594>>
87    for TxEip4844Variant<BlobTransactionSidecarVariant>
88{
89    fn from(value: TxEip4844Variant<BlobTransactionSidecarEip7594>) -> Self {
90        value.map_sidecar(Into::into)
91    }
92}
93
94impl<T> From<TxEip4844WithSidecar<T>> for TxEip4844Variant<T> {
95    fn from(tx: TxEip4844WithSidecar<T>) -> Self {
96        Self::TxEip4844WithSidecar(tx)
97    }
98}
99
100impl<T> From<TxEip4844> for TxEip4844Variant<T> {
101    fn from(tx: TxEip4844) -> Self {
102        Self::TxEip4844(tx)
103    }
104}
105
106impl From<(TxEip4844, BlobTransactionSidecar)> for TxEip4844Variant<BlobTransactionSidecar> {
107    fn from((tx, sidecar): (TxEip4844, BlobTransactionSidecar)) -> Self {
108        TxEip4844WithSidecar::from_tx_and_sidecar(tx, sidecar).into()
109    }
110}
111
112impl<T> From<TxEip4844Variant<T>> for TxEip4844 {
113    fn from(tx: TxEip4844Variant<T>) -> Self {
114        match tx {
115            TxEip4844Variant::TxEip4844(tx) => tx,
116            TxEip4844Variant::TxEip4844WithSidecar(tx) => tx.tx,
117        }
118    }
119}
120
121impl<T> AsRef<TxEip4844> for TxEip4844Variant<T> {
122    fn as_ref(&self) -> &TxEip4844 {
123        match self {
124            Self::TxEip4844(tx) => tx,
125            Self::TxEip4844WithSidecar(tx) => &tx.tx,
126        }
127    }
128}
129
130impl<T> AsMut<TxEip4844> for TxEip4844Variant<T> {
131    fn as_mut(&mut self) -> &mut TxEip4844 {
132        match self {
133            Self::TxEip4844(tx) => tx,
134            Self::TxEip4844WithSidecar(tx) => &mut tx.tx,
135        }
136    }
137}
138
139impl AsRef<Self> for TxEip4844 {
140    fn as_ref(&self) -> &Self {
141        self
142    }
143}
144
145impl AsMut<Self> for TxEip4844 {
146    fn as_mut(&mut self) -> &mut Self {
147        self
148    }
149}
150
151impl<T> TxEip4844Variant<T> {
152    /// Get the transaction type.
153    #[doc(alias = "transaction_type")]
154    pub const fn tx_type() -> TxType {
155        TxType::Eip4844
156    }
157
158    /// Get access to the inner tx [TxEip4844].
159    #[doc(alias = "transaction")]
160    pub const fn tx(&self) -> &TxEip4844 {
161        match self {
162            Self::TxEip4844(tx) => tx,
163            Self::TxEip4844WithSidecar(tx) => tx.tx(),
164        }
165    }
166
167    /// Strips the sidecar from this variant type leaving [`Self::TxEip4844`].
168    ///
169    /// Returns the sidecar if it was [`Self::TxEip4844WithSidecar`].
170    pub fn take_sidecar(&mut self) -> Option<T> {
171        // Use a placeholder to temporarily replace self
172        let placeholder = Self::TxEip4844(TxEip4844::default());
173        match core::mem::replace(self, placeholder) {
174            tx @ Self::TxEip4844(_) => {
175                // Put the original transaction back
176                *self = tx;
177                None
178            }
179            Self::TxEip4844WithSidecar(tx) => {
180                let (tx, sidecar) = tx.into_parts();
181                *self = Self::TxEip4844(tx);
182                Some(sidecar)
183            }
184        }
185    }
186
187    /// Strips the sidecar from the variant and returns both the transaction and the sidecar
188    /// separately, keeping the same sidecar type parameter.
189    ///
190    /// This method consumes the variant and returns:
191    /// - A [`TxEip4844Variant<T>`] containing only the transaction (always
192    ///   [`TxEip4844Variant::TxEip4844`])
193    /// - An [`Option<T>`] containing the sidecar if it existed
194    ///
195    /// This is a convenience wrapper around [`strip_sidecar_into`](Self::strip_sidecar_into)
196    /// that keeps the same type parameter.
197    ///
198    /// # Examples
199    ///
200    /// ```
201    /// # use alloy_consensus::TxEip4844Variant;
202    /// # use alloy_eips::eip4844::BlobTransactionSidecar;
203    /// # fn example(variant: TxEip4844Variant<BlobTransactionSidecar>) {
204    /// // Strip and extract the sidecar (type parameter stays the same)
205    /// let (tx_variant, maybe_sidecar) = variant.strip_sidecar();
206    ///
207    /// if let Some(sidecar) = maybe_sidecar {
208    ///     // Process the sidecar separately
209    ///     println!("Sidecar has {} blobs", sidecar.blobs.len());
210    /// }
211    /// # }
212    /// ```
213    pub fn strip_sidecar(self) -> (Self, Option<T>) {
214        self.strip_sidecar_into()
215    }
216
217    /// Strips the sidecar from the variant and returns both the transaction and the sidecar
218    /// separately, converting to a different sidecar type parameter.
219    ///
220    /// This method consumes the variant and returns:
221    /// - A [`TxEip4844Variant<U>`] containing only the transaction (always
222    ///   [`TxEip4844Variant::TxEip4844`])
223    /// - An [`Option<T>`] containing the sidecar if it existed
224    ///
225    /// This is useful when you need to:
226    /// - Extract the sidecar for separate processing
227    /// - Convert to a variant with a different sidecar type parameter
228    /// - Separate the transaction data from blob data
229    ///
230    /// # Examples
231    ///
232    /// ```
233    /// # use alloy_consensus::TxEip4844Variant;
234    /// # use alloy_eips::eip4844::BlobTransactionSidecar;
235    /// # use alloy_eips::eip7594::BlobTransactionSidecarVariant;
236    /// # fn example(variant: TxEip4844Variant<BlobTransactionSidecar>) {
237    /// // Strip and convert to a different type parameter
238    /// let (tx_variant, maybe_sidecar): (TxEip4844Variant<BlobTransactionSidecarVariant>, _) =
239    ///     variant.strip_sidecar_into();
240    ///
241    /// if let Some(sidecar) = maybe_sidecar {
242    ///     // Process the sidecar separately
243    ///     println!("Sidecar has {} blobs", sidecar.blobs.len());
244    /// }
245    /// # }
246    /// ```
247    pub fn strip_sidecar_into<U>(self) -> (TxEip4844Variant<U>, Option<T>) {
248        match self {
249            Self::TxEip4844(tx) => (TxEip4844Variant::TxEip4844(tx), None),
250            Self::TxEip4844WithSidecar(tx) => {
251                let (tx, sidecar) = tx.into_parts();
252                (TxEip4844Variant::TxEip4844(tx), Some(sidecar))
253            }
254        }
255    }
256
257    /// Drops the sidecar from the variant and returns only the transaction, keeping the same
258    /// sidecar type parameter.
259    ///
260    /// This is a convenience method that discards the sidecar, returning only the transaction
261    /// without a sidecar (always [`TxEip4844Variant::TxEip4844`]).
262    ///
263    /// This is equivalent to calling [`strip_sidecar`](Self::strip_sidecar) and taking only the
264    /// first element of the tuple.
265    ///
266    /// # Examples
267    ///
268    /// ```
269    /// # use alloy_consensus::TxEip4844Variant;
270    /// # use alloy_eips::eip4844::BlobTransactionSidecar;
271    /// # fn example(variant: TxEip4844Variant<BlobTransactionSidecar>) {
272    /// // Drop the sidecar, keeping only the transaction
273    /// let tx_without_sidecar = variant.drop_sidecar();
274    /// # }
275    /// ```
276    pub fn drop_sidecar(self) -> Self {
277        self.strip_sidecar().0
278    }
279
280    /// Drops the sidecar from the variant and returns only the transaction, converting to a
281    /// different sidecar type parameter.
282    ///
283    /// This is a convenience method that discards the sidecar, returning only the transaction
284    /// without a sidecar (always [`TxEip4844Variant::TxEip4844`]).
285    ///
286    /// This is equivalent to calling [`strip_sidecar_into`](Self::strip_sidecar_into) and taking
287    /// only the first element of the tuple.
288    ///
289    /// # Examples
290    ///
291    /// ```
292    /// # use alloy_consensus::TxEip4844Variant;
293    /// # use alloy_eips::eip4844::BlobTransactionSidecar;
294    /// # use alloy_eips::eip7594::BlobTransactionSidecarVariant;
295    /// # fn example(variant: TxEip4844Variant<BlobTransactionSidecar>) {
296    /// // Drop the sidecar and convert to a different type parameter
297    /// let tx_without_sidecar: TxEip4844Variant<BlobTransactionSidecarVariant> =
298    ///     variant.drop_sidecar_into();
299    /// # }
300    /// ```
301    pub fn drop_sidecar_into<U>(self) -> TxEip4844Variant<U> {
302        self.strip_sidecar_into().0
303    }
304
305    /// Returns the [`TxEip4844WithSidecar`] if it has a sidecar
306    pub const fn as_with_sidecar(&self) -> Option<&TxEip4844WithSidecar<T>> {
307        match self {
308            Self::TxEip4844WithSidecar(tx) => Some(tx),
309            _ => None,
310        }
311    }
312
313    /// Tries to unwrap the [`TxEip4844WithSidecar`] returns the transaction as error if it is not a
314    /// [`TxEip4844WithSidecar`]
315    pub fn try_into_4844_with_sidecar(self) -> Result<TxEip4844WithSidecar<T>, Self> {
316        match self {
317            Self::TxEip4844WithSidecar(tx) => Ok(tx),
318            _ => Err(self),
319        }
320    }
321
322    /// Returns the sidecar if this is [`TxEip4844Variant::TxEip4844WithSidecar`].
323    pub const fn sidecar(&self) -> Option<&T> {
324        match self {
325            Self::TxEip4844WithSidecar(tx) => Some(tx.sidecar()),
326            _ => None,
327        }
328    }
329
330    /// Maps the sidecar to a new type.
331    pub fn map_sidecar<U>(self, f: impl FnOnce(T) -> U) -> TxEip4844Variant<U> {
332        match self {
333            Self::TxEip4844(tx) => TxEip4844Variant::TxEip4844(tx),
334            Self::TxEip4844WithSidecar(tx) => {
335                TxEip4844Variant::TxEip4844WithSidecar(tx.map_sidecar(f))
336            }
337        }
338    }
339
340    /// Maps the sidecar to a new type, returning an error if the mapping fails.
341    pub fn try_map_sidecar<U, E>(
342        self,
343        f: impl FnOnce(T) -> Result<U, E>,
344    ) -> Result<TxEip4844Variant<U>, E> {
345        match self {
346            Self::TxEip4844(tx) => Ok(TxEip4844Variant::TxEip4844(tx)),
347            Self::TxEip4844WithSidecar(tx) => {
348                tx.try_map_sidecar(f).map(TxEip4844Variant::TxEip4844WithSidecar)
349            }
350        }
351    }
352}
353
354impl<T: TxEip4844Sidecar> TxEip4844Variant<T> {
355    /// Verifies that the transaction's blob data, commitments, and proofs are all valid.
356    ///
357    /// See also [TxEip4844::validate_blob]
358    #[cfg(feature = "kzg")]
359    pub fn validate(
360        &self,
361        proof_settings: &c_kzg::KzgSettings,
362    ) -> Result<(), BlobTransactionValidationError> {
363        match self {
364            Self::TxEip4844(_) => Err(BlobTransactionValidationError::MissingSidecar),
365            Self::TxEip4844WithSidecar(tx) => tx.validate_blob(proof_settings),
366        }
367    }
368
369    /// Calculates a heuristic for the in-memory size of the [TxEip4844Variant] transaction.
370    #[inline]
371    pub fn size(&self) -> usize {
372        match self {
373            Self::TxEip4844(tx) => tx.size(),
374            Self::TxEip4844WithSidecar(tx) => tx.size(),
375        }
376    }
377}
378
379impl TxEip4844Variant<BlobTransactionSidecar> {
380    /// Converts this legacy EIP-4844 sidecar into an EIP-7594 sidecar with the default settings.
381    ///
382    /// This requires computing cell KZG proofs from the blob data using the KZG trusted setup.
383    /// Each blob produces `CELLS_PER_EXT_BLOB` cell proofs.
384    #[cfg(feature = "kzg")]
385    pub fn try_into_7594(
386        self,
387    ) -> Result<TxEip4844Variant<alloy_eips::eip7594::BlobTransactionSidecarEip7594>, c_kzg::Error>
388    {
389        self.try_into_7594_with_settings(
390            alloy_eips::eip4844::env_settings::EnvKzgSettings::Default.get(),
391        )
392    }
393
394    /// Converts this legacy EIP-4844 sidecar into an EIP-7594 sidecar with the given settings.
395    ///
396    /// This requires computing cell KZG proofs from the blob data using the KZG trusted setup.
397    /// Each blob produces `CELLS_PER_EXT_BLOB` cell proofs.
398    #[cfg(feature = "kzg")]
399    pub fn try_into_7594_with_settings(
400        self,
401        settings: &c_kzg::KzgSettings,
402    ) -> Result<TxEip4844Variant<alloy_eips::eip7594::BlobTransactionSidecarEip7594>, c_kzg::Error>
403    {
404        self.try_map_sidecar(|sidecar| sidecar.try_into_7594(settings))
405    }
406}
407
408#[cfg(feature = "kzg")]
409impl TxEip4844Variant<alloy_eips::eip7594::BlobTransactionSidecarVariant> {
410    /// Attempts to convert this transaction's sidecar into the EIP-7594 format using default KZG
411    /// settings.
412    ///
413    /// For EIP-4844 sidecars, this computes cell KZG proofs from the blob data. If the sidecar is
414    /// already in EIP-7594 format, it returns itself unchanged.
415    ///
416    /// # Returns
417    ///
418    /// - `Ok(TxEip4844Variant<alloy_eips::eip7594::BlobTransactionSidecarVariant>)` - The
419    ///   transaction with converted sidecar
420    /// - `Err(c_kzg::Error)` - If KZG proof computation fails
421    pub fn try_convert_into_eip7594(self) -> Result<Self, c_kzg::Error> {
422        self.try_convert_into_eip7594_with_settings(
423            alloy_eips::eip4844::env_settings::EnvKzgSettings::Default.get(),
424        )
425    }
426
427    /// Attempts to convert this transaction's sidecar into the EIP-7594 format using custom KZG
428    /// settings.
429    ///
430    /// For EIP-4844 sidecars, this computes cell KZG proofs from the blob data using the
431    /// provided KZG settings. If the sidecar is already in EIP-7594 format, it returns itself
432    /// unchanged.
433    ///
434    /// # Arguments
435    ///
436    /// * `settings` - The KZG settings to use for computing cell proofs
437    ///
438    /// # Returns
439    ///
440    /// - `Ok(TxEip4844Variant<alloy_eips::eip7594::BlobTransactionSidecarVariant>)` - The
441    ///   transaction with converted sidecar
442    /// - `Err(c_kzg::Error)` - If KZG proof computation fails
443    pub fn try_convert_into_eip7594_with_settings(
444        self,
445        settings: &c_kzg::KzgSettings,
446    ) -> Result<Self, c_kzg::Error> {
447        self.try_map_sidecar(|sidecar| sidecar.try_convert_into_eip7594_with_settings(settings))
448    }
449}
450
451impl<T> Transaction for TxEip4844Variant<T>
452where
453    T: fmt::Debug + Send + Sync + 'static,
454{
455    #[inline]
456    fn chain_id(&self) -> Option<ChainId> {
457        match self {
458            Self::TxEip4844(tx) => Some(tx.chain_id),
459            Self::TxEip4844WithSidecar(tx) => Some(tx.tx().chain_id),
460        }
461    }
462
463    #[inline]
464    fn nonce(&self) -> u64 {
465        match self {
466            Self::TxEip4844(tx) => tx.nonce,
467            Self::TxEip4844WithSidecar(tx) => tx.tx().nonce,
468        }
469    }
470
471    #[inline]
472    fn gas_limit(&self) -> u64 {
473        match self {
474            Self::TxEip4844(tx) => tx.gas_limit,
475            Self::TxEip4844WithSidecar(tx) => tx.tx().gas_limit,
476        }
477    }
478
479    #[inline]
480    fn gas_price(&self) -> Option<u128> {
481        None
482    }
483
484    #[inline]
485    fn max_fee_per_gas(&self) -> u128 {
486        match self {
487            Self::TxEip4844(tx) => tx.max_fee_per_gas(),
488            Self::TxEip4844WithSidecar(tx) => tx.max_fee_per_gas(),
489        }
490    }
491
492    #[inline]
493    fn max_priority_fee_per_gas(&self) -> Option<u128> {
494        match self {
495            Self::TxEip4844(tx) => tx.max_priority_fee_per_gas(),
496            Self::TxEip4844WithSidecar(tx) => tx.max_priority_fee_per_gas(),
497        }
498    }
499
500    #[inline]
501    fn max_fee_per_blob_gas(&self) -> Option<u128> {
502        match self {
503            Self::TxEip4844(tx) => tx.max_fee_per_blob_gas(),
504            Self::TxEip4844WithSidecar(tx) => tx.max_fee_per_blob_gas(),
505        }
506    }
507
508    #[inline]
509    fn priority_fee_or_price(&self) -> u128 {
510        match self {
511            Self::TxEip4844(tx) => tx.priority_fee_or_price(),
512            Self::TxEip4844WithSidecar(tx) => tx.priority_fee_or_price(),
513        }
514    }
515
516    fn effective_gas_price(&self, base_fee: Option<u64>) -> u128 {
517        match self {
518            Self::TxEip4844(tx) => tx.effective_gas_price(base_fee),
519            Self::TxEip4844WithSidecar(tx) => tx.effective_gas_price(base_fee),
520        }
521    }
522
523    #[inline]
524    fn is_dynamic_fee(&self) -> bool {
525        match self {
526            Self::TxEip4844(tx) => tx.is_dynamic_fee(),
527            Self::TxEip4844WithSidecar(tx) => tx.is_dynamic_fee(),
528        }
529    }
530
531    #[inline]
532    fn kind(&self) -> TxKind {
533        match self {
534            Self::TxEip4844(tx) => tx.to,
535            Self::TxEip4844WithSidecar(tx) => tx.tx.to,
536        }
537        .into()
538    }
539
540    #[inline]
541    fn is_create(&self) -> bool {
542        false
543    }
544
545    #[inline]
546    fn value(&self) -> U256 {
547        match self {
548            Self::TxEip4844(tx) => tx.value,
549            Self::TxEip4844WithSidecar(tx) => tx.tx.value,
550        }
551    }
552
553    #[inline]
554    fn input(&self) -> &Bytes {
555        match self {
556            Self::TxEip4844(tx) => tx.input(),
557            Self::TxEip4844WithSidecar(tx) => tx.tx().input(),
558        }
559    }
560
561    #[inline]
562    fn access_list(&self) -> Option<&AccessList> {
563        match self {
564            Self::TxEip4844(tx) => tx.access_list(),
565            Self::TxEip4844WithSidecar(tx) => tx.access_list(),
566        }
567    }
568
569    #[inline]
570    fn blob_versioned_hashes(&self) -> Option<&[B256]> {
571        match self {
572            Self::TxEip4844(tx) => tx.blob_versioned_hashes(),
573            Self::TxEip4844WithSidecar(tx) => tx.blob_versioned_hashes(),
574        }
575    }
576
577    #[inline]
578    fn authorization_list(&self) -> Option<&[SignedAuthorization]> {
579        None
580    }
581}
582impl Typed2718 for TxEip4844 {
583    fn ty(&self) -> u8 {
584        TxType::Eip4844 as u8
585    }
586}
587
588impl<T: Encodable7594> RlpEcdsaEncodableTx for TxEip4844Variant<T> {
589    fn rlp_encoded_fields_length(&self) -> usize {
590        match self {
591            Self::TxEip4844(inner) => inner.rlp_encoded_fields_length(),
592            Self::TxEip4844WithSidecar(inner) => inner.rlp_encoded_fields_length(),
593        }
594    }
595
596    fn rlp_encode_fields(&self, out: &mut dyn alloy_rlp::BufMut) {
597        match self {
598            Self::TxEip4844(inner) => inner.rlp_encode_fields(out),
599            Self::TxEip4844WithSidecar(inner) => inner.rlp_encode_fields(out),
600        }
601    }
602
603    fn rlp_header_signed(&self, signature: &Signature) -> Header {
604        match self {
605            Self::TxEip4844(inner) => inner.rlp_header_signed(signature),
606            Self::TxEip4844WithSidecar(inner) => inner.rlp_header_signed(signature),
607        }
608    }
609
610    fn rlp_encode_signed(&self, signature: &Signature, out: &mut dyn BufMut) {
611        match self {
612            Self::TxEip4844(inner) => inner.rlp_encode_signed(signature, out),
613            Self::TxEip4844WithSidecar(inner) => inner.rlp_encode_signed(signature, out),
614        }
615    }
616
617    fn tx_hash_with_type(&self, signature: &Signature, ty: u8) -> alloy_primitives::TxHash {
618        match self {
619            Self::TxEip4844(inner) => inner.tx_hash_with_type(signature, ty),
620            Self::TxEip4844WithSidecar(inner) => inner.tx_hash_with_type(signature, ty),
621        }
622    }
623}
624
625impl<T: Encodable7594 + Decodable7594> RlpEcdsaDecodableTx for TxEip4844Variant<T> {
626    const DEFAULT_TX_TYPE: u8 = { Self::tx_type() as u8 };
627
628    fn rlp_decode_fields(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
629        let needle = &mut &**buf;
630
631        // We also need to do a trial decoding of WithSidecar to see if it
632        // works. The trial ref is consumed to look for a WithSidecar.
633        let trial = &mut &**buf;
634
635        // If the next bytes are a header, one of 3 things is true:
636        // - If the header is a list, this is a WithSidecar tx
637        // - If there is no header, this is a non-sidecar tx with a single-byte chain ID.
638        // - If there is a string header, this is a non-sidecar tx with a multi-byte chain ID.
639        // To check these, we first try to decode the header. If it fails or is
640        // not a list, we lmow that it is a non-sidecar transaction.
641        if Header::decode(needle).is_ok_and(|h| h.list) {
642            if let Ok(tx) = TxEip4844WithSidecar::rlp_decode_fields(trial) {
643                *buf = *trial;
644                return Ok(tx.into());
645            }
646        }
647        TxEip4844::rlp_decode_fields(buf).map(Into::into)
648    }
649
650    fn rlp_decode_with_signature(buf: &mut &[u8]) -> alloy_rlp::Result<(Self, Signature)> {
651        // We need to determine if this has a sidecar tx or not. The needle ref
652        // is consumed to look for headers.
653        let needle = &mut &**buf;
654
655        // We also need to do a trial decoding of WithSidecar to see if it
656        // works. The original ref is consumed to look for a WithSidecar.
657        let trial = &mut &**buf;
658
659        // First we decode the outer header
660        Header::decode(needle)?;
661
662        // If the next bytes are a header, one of 3 things is true:
663        // - If the header is a list, this is a WithSidecar tx
664        // - If there is no header, this is a non-sidecar tx with a single-byte chain ID.
665        // - If there is a string header, this is a non-sidecar tx with a multi-byte chain ID.
666        // To check these, we first try to decode the header. If it fails or is
667        // not a list, we lmow that it is a non-sidecar transaction.
668        if Header::decode(needle).is_ok_and(|h| h.list) {
669            if let Ok((tx, signature)) = TxEip4844WithSidecar::rlp_decode_with_signature(trial) {
670                // If successful, we need to consume the trial buffer up to
671                // the same point.
672                *buf = *trial;
673                return Ok((tx.into(), signature));
674            }
675        }
676        TxEip4844::rlp_decode_with_signature(buf).map(|(tx, signature)| (tx.into(), signature))
677    }
678}
679
680impl<T> Typed2718 for TxEip4844Variant<T> {
681    fn ty(&self) -> u8 {
682        TxType::Eip4844 as u8
683    }
684}
685
686impl IsTyped2718 for TxEip4844 {
687    fn is_type(type_id: u8) -> bool {
688        matches!(type_id, 0x03)
689    }
690}
691
692impl<T> SignableTransaction<Signature> for TxEip4844Variant<T>
693where
694    T: fmt::Debug + Send + Sync + 'static,
695{
696    fn set_chain_id(&mut self, chain_id: ChainId) {
697        match self {
698            Self::TxEip4844(inner) => {
699                inner.set_chain_id(chain_id);
700            }
701            Self::TxEip4844WithSidecar(inner) => {
702                inner.set_chain_id(chain_id);
703            }
704        }
705    }
706
707    fn encode_for_signing(&self, out: &mut dyn alloy_rlp::BufMut) {
708        // A signature for a [TxEip4844WithSidecar] is a signature over the [TxEip4844Variant]
709        // EIP-2718 payload fields:
710        // (BLOB_TX_TYPE ||
711        //   rlp([chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, to, value,
712        //     data, access_list, max_fee_per_blob_gas, blob_versioned_hashes]))
713        self.tx().encode_for_signing(out);
714    }
715
716    fn payload_len_for_signature(&self) -> usize {
717        self.tx().payload_len_for_signature()
718    }
719}
720
721/// [EIP-4844 Blob Transaction](https://eips.ethereum.org/EIPS/eip-4844#blob-transaction)
722///
723/// A transaction with blob hashes and max blob fee. It does not have the Blob sidecar.
724#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
725#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
726#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
727#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
728#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
729#[doc(alias = "Eip4844Transaction", alias = "TransactionEip4844", alias = "Eip4844Tx")]
730pub struct TxEip4844 {
731    /// Added as EIP-pub 155: Simple replay attack protection
732    #[cfg_attr(feature = "serde", serde(with = "alloy_serde::quantity"))]
733    pub chain_id: ChainId,
734    /// A scalar value equal to the number of transactions sent by the sender; formally Tn.
735    #[cfg_attr(feature = "serde", serde(with = "alloy_serde::quantity"))]
736    pub nonce: u64,
737    /// A scalar value equal to the maximum
738    /// amount of gas that should be used in executing
739    /// this transaction. This is paid up-front, before any
740    /// computation is done and may not be increased
741    /// later; formally Tg.
742    #[cfg_attr(
743        feature = "serde",
744        serde(with = "alloy_serde::quantity", rename = "gas", alias = "gasLimit")
745    )]
746    pub gas_limit: u64,
747    /// A scalar value equal to the maximum total fee per unit of gas
748    /// the sender is willing to pay. The actual fee paid per gas is
749    /// the minimum of this and `base_fee + max_priority_fee_per_gas`.
750    ///
751    /// As ethereum circulation is around 120mil eth as of 2022 that is around
752    /// 120000000000000000000000000 wei we are safe to use u128 as its max number is:
753    /// 340282366920938463463374607431768211455
754    ///
755    /// This is also known as `GasFeeCap`
756    #[cfg_attr(feature = "serde", serde(with = "alloy_serde::quantity"))]
757    pub max_fee_per_gas: u128,
758    /// Max Priority fee that transaction is paying
759    ///
760    /// As ethereum circulation is around 120mil eth as of 2022 that is around
761    /// 120000000000000000000000000 wei we are safe to use u128 as its max number is:
762    /// 340282366920938463463374607431768211455
763    ///
764    /// This is also known as `GasTipCap`
765    #[cfg_attr(feature = "serde", serde(with = "alloy_serde::quantity"))]
766    pub max_priority_fee_per_gas: u128,
767    /// The 160-bit address of the message call’s recipient.
768    pub to: Address,
769    /// A scalar value equal to the number of Wei to
770    /// be transferred to the message call’s recipient or,
771    /// in the case of contract creation, as an endowment
772    /// to the newly created account; formally Tv.
773    pub value: U256,
774    /// The accessList specifies a list of addresses and storage keys;
775    /// these addresses and storage keys are added into the `accessed_addresses`
776    /// and `accessed_storage_keys` global sets (introduced in EIP-2929).
777    /// A gas cost is charged, though at a discount relative to the cost of
778    /// accessing outside the list.
779    pub access_list: AccessList,
780
781    /// It contains a vector of fixed size hash(32 bytes)
782    pub blob_versioned_hashes: Vec<B256>,
783
784    /// Max fee per data gas
785    ///
786    /// aka BlobFeeCap or blobGasFeeCap
787    #[cfg_attr(feature = "serde", serde(with = "alloy_serde::quantity"))]
788    pub max_fee_per_blob_gas: u128,
789
790    /// Input has two uses depending if transaction is Create or Call (if `to` field is None or
791    /// Some). pub init: An unlimited size byte array specifying the
792    /// EVM-code for the account initialisation procedure CREATE,
793    /// data: An unlimited size byte array specifying the
794    /// input data of the message call, formally Td.
795    pub input: Bytes,
796}
797
798impl TxEip4844 {
799    /// Returns the total gas for all blobs in this transaction.
800    #[inline]
801    pub const fn blob_gas(&self) -> u64 {
802        // SAFETY: we don't expect u64::MAX / DATA_GAS_PER_BLOB hashes in a single transaction
803        self.blob_versioned_hashes.len() as u64 * DATA_GAS_PER_BLOB
804    }
805
806    /// Verifies that the given blob data, commitments, and proofs are all valid for this
807    /// transaction.
808    ///
809    /// Takes as input the [KzgSettings](c_kzg::KzgSettings), which should contain the parameters
810    /// derived from the KZG trusted setup.
811    ///
812    /// This ensures that the blob transaction payload has the same number of blob data elements,
813    /// commitments, and proofs. Each blob data element is verified against its commitment and
814    /// proof.
815    ///
816    /// Returns [BlobTransactionValidationError::InvalidProof] if any blob KZG proof in the response
817    /// fails to verify, or if the versioned hashes in the transaction do not match the actual
818    /// commitment versioned hashes.
819    #[cfg(feature = "kzg")]
820    pub fn validate_blob<T: TxEip4844Sidecar>(
821        &self,
822        sidecar: &T,
823        proof_settings: &c_kzg::KzgSettings,
824    ) -> Result<(), BlobTransactionValidationError> {
825        sidecar.validate(&self.blob_versioned_hashes, proof_settings)
826    }
827
828    /// Get transaction type.
829    #[doc(alias = "transaction_type")]
830    pub const fn tx_type() -> TxType {
831        TxType::Eip4844
832    }
833
834    /// Attaches the blob sidecar to the transaction
835    pub const fn with_sidecar<T>(self, sidecar: T) -> TxEip4844WithSidecar<T> {
836        TxEip4844WithSidecar::from_tx_and_sidecar(self, sidecar)
837    }
838
839    /// Calculates a heuristic for the in-memory size of the [TxEip4844Variant] transaction.
840    #[inline]
841    pub fn size(&self) -> usize {
842        size_of::<Self>()
843            + self.access_list.size()
844            + self.input.len()
845            + self.blob_versioned_hashes.capacity() * size_of::<B256>()
846    }
847}
848
849impl RlpEcdsaEncodableTx for TxEip4844 {
850    fn rlp_encoded_fields_length(&self) -> usize {
851        self.chain_id.length()
852            + self.nonce.length()
853            + self.gas_limit.length()
854            + self.max_fee_per_gas.length()
855            + self.max_priority_fee_per_gas.length()
856            + self.to.length()
857            + self.value.length()
858            + self.access_list.length()
859            + self.blob_versioned_hashes.length()
860            + self.max_fee_per_blob_gas.length()
861            + self.input.0.length()
862    }
863
864    fn rlp_encode_fields(&self, out: &mut dyn alloy_rlp::BufMut) {
865        self.chain_id.encode(out);
866        self.nonce.encode(out);
867        self.max_priority_fee_per_gas.encode(out);
868        self.max_fee_per_gas.encode(out);
869        self.gas_limit.encode(out);
870        self.to.encode(out);
871        self.value.encode(out);
872        self.input.0.encode(out);
873        self.access_list.encode(out);
874        self.max_fee_per_blob_gas.encode(out);
875        self.blob_versioned_hashes.encode(out);
876    }
877}
878
879impl RlpEcdsaDecodableTx for TxEip4844 {
880    const DEFAULT_TX_TYPE: u8 = { Self::tx_type() as u8 };
881
882    fn rlp_decode_fields(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
883        Ok(Self {
884            chain_id: Decodable::decode(buf)?,
885            nonce: Decodable::decode(buf)?,
886            max_priority_fee_per_gas: Decodable::decode(buf)?,
887            max_fee_per_gas: Decodable::decode(buf)?,
888            gas_limit: Decodable::decode(buf)?,
889            to: Decodable::decode(buf)?,
890            value: Decodable::decode(buf)?,
891            input: Decodable::decode(buf)?,
892            access_list: Decodable::decode(buf)?,
893            max_fee_per_blob_gas: Decodable::decode(buf)?,
894            blob_versioned_hashes: Decodable::decode(buf)?,
895        })
896    }
897}
898
899impl SignableTransaction<Signature> for TxEip4844 {
900    fn set_chain_id(&mut self, chain_id: ChainId) {
901        self.chain_id = chain_id;
902    }
903
904    fn encode_for_signing(&self, out: &mut dyn alloy_rlp::BufMut) {
905        out.put_u8(Self::tx_type() as u8);
906        self.encode(out);
907    }
908
909    fn payload_len_for_signature(&self) -> usize {
910        self.length() + 1
911    }
912}
913
914impl Transaction for TxEip4844 {
915    #[inline]
916    fn chain_id(&self) -> Option<ChainId> {
917        Some(self.chain_id)
918    }
919
920    #[inline]
921    fn nonce(&self) -> u64 {
922        self.nonce
923    }
924
925    #[inline]
926    fn gas_limit(&self) -> u64 {
927        self.gas_limit
928    }
929
930    #[inline]
931    fn gas_price(&self) -> Option<u128> {
932        None
933    }
934
935    #[inline]
936    fn max_fee_per_gas(&self) -> u128 {
937        self.max_fee_per_gas
938    }
939
940    #[inline]
941    fn max_priority_fee_per_gas(&self) -> Option<u128> {
942        Some(self.max_priority_fee_per_gas)
943    }
944
945    #[inline]
946    fn max_fee_per_blob_gas(&self) -> Option<u128> {
947        Some(self.max_fee_per_blob_gas)
948    }
949
950    #[inline]
951    fn priority_fee_or_price(&self) -> u128 {
952        self.max_priority_fee_per_gas
953    }
954
955    fn effective_gas_price(&self, base_fee: Option<u64>) -> u128 {
956        alloy_eips::eip1559::calc_effective_gas_price(
957            self.max_fee_per_gas,
958            self.max_priority_fee_per_gas,
959            base_fee,
960        )
961    }
962
963    #[inline]
964    fn is_dynamic_fee(&self) -> bool {
965        true
966    }
967
968    #[inline]
969    fn kind(&self) -> TxKind {
970        self.to.into()
971    }
972
973    #[inline]
974    fn is_create(&self) -> bool {
975        false
976    }
977
978    #[inline]
979    fn value(&self) -> U256 {
980        self.value
981    }
982
983    #[inline]
984    fn input(&self) -> &Bytes {
985        &self.input
986    }
987
988    #[inline]
989    fn access_list(&self) -> Option<&AccessList> {
990        Some(&self.access_list)
991    }
992
993    #[inline]
994    fn blob_versioned_hashes(&self) -> Option<&[B256]> {
995        Some(&self.blob_versioned_hashes)
996    }
997
998    #[inline]
999    fn authorization_list(&self) -> Option<&[SignedAuthorization]> {
1000        None
1001    }
1002}
1003
1004impl Encodable for TxEip4844 {
1005    fn encode(&self, out: &mut dyn BufMut) {
1006        self.rlp_encode(out);
1007    }
1008
1009    fn length(&self) -> usize {
1010        self.rlp_encoded_length()
1011    }
1012}
1013
1014impl Decodable for TxEip4844 {
1015    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
1016        Self::rlp_decode(buf)
1017    }
1018}
1019
1020impl<T> From<TxEip4844WithSidecar<T>> for TxEip4844 {
1021    /// Consumes the [TxEip4844WithSidecar] and returns the inner [TxEip4844].
1022    fn from(tx_with_sidecar: TxEip4844WithSidecar<T>) -> Self {
1023        tx_with_sidecar.tx
1024    }
1025}
1026
1027/// [EIP-4844 Blob Transaction](https://eips.ethereum.org/EIPS/eip-4844#blob-transaction)
1028///
1029/// A transaction with blob hashes and max blob fee, which also includes the
1030/// [BlobTransactionSidecar]. This is the full type sent over the network as a raw transaction. It
1031/// wraps a [TxEip4844] to include the sidecar and the ability to decode it properly.
1032///
1033/// This is defined in [EIP-4844](https://eips.ethereum.org/EIPS/eip-4844#networking) as an element
1034/// of a `PooledTransactions` response, and is also used as the format for sending raw transactions
1035/// through the network (eth_sendRawTransaction/eth_sendTransaction).
1036#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
1037#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
1038#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1039#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
1040#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
1041#[doc(alias = "Eip4844TransactionWithSidecar", alias = "Eip4844TxWithSidecar")]
1042pub struct TxEip4844WithSidecar<T = BlobTransactionSidecar> {
1043    /// The actual transaction.
1044    #[cfg_attr(feature = "serde", serde(flatten))]
1045    #[doc(alias = "transaction")]
1046    pub tx: TxEip4844,
1047    /// The sidecar.
1048    #[cfg_attr(feature = "serde", serde(flatten))]
1049    pub sidecar: T,
1050}
1051
1052impl<T> TxEip4844WithSidecar<T> {
1053    /// Constructs a new [TxEip4844WithSidecar] from a [TxEip4844] and a sidecar.
1054    #[doc(alias = "from_transaction_and_sidecar")]
1055    pub const fn from_tx_and_sidecar(tx: TxEip4844, sidecar: T) -> Self {
1056        Self { tx, sidecar }
1057    }
1058
1059    /// Get the transaction type.
1060    #[doc(alias = "transaction_type")]
1061    pub const fn tx_type() -> TxType {
1062        TxEip4844::tx_type()
1063    }
1064
1065    /// Get access to the inner tx [TxEip4844].
1066    #[doc(alias = "transaction")]
1067    pub const fn tx(&self) -> &TxEip4844 {
1068        &self.tx
1069    }
1070
1071    /// Get access to the inner sidecar.
1072    pub const fn sidecar(&self) -> &T {
1073        &self.sidecar
1074    }
1075
1076    /// Consumes the [TxEip4844WithSidecar] and returns the inner sidecar.
1077    pub fn into_sidecar(self) -> T {
1078        self.sidecar
1079    }
1080
1081    /// Consumes the [TxEip4844WithSidecar] and returns the inner [TxEip4844] and a sidecar.
1082    pub fn into_parts(self) -> (TxEip4844, T) {
1083        (self.tx, self.sidecar)
1084    }
1085
1086    /// Maps the sidecar to a new type.
1087    pub fn map_sidecar<U>(self, f: impl FnOnce(T) -> U) -> TxEip4844WithSidecar<U> {
1088        TxEip4844WithSidecar { tx: self.tx, sidecar: f(self.sidecar) }
1089    }
1090
1091    /// Maps the sidecar to a new type, returning an error if the mapping fails.
1092    pub fn try_map_sidecar<U, E>(
1093        self,
1094        f: impl FnOnce(T) -> Result<U, E>,
1095    ) -> Result<TxEip4844WithSidecar<U>, E> {
1096        Ok(TxEip4844WithSidecar { tx: self.tx, sidecar: f(self.sidecar)? })
1097    }
1098}
1099
1100impl TxEip4844WithSidecar<BlobTransactionSidecar> {
1101    /// Converts this legacy EIP-4844 sidecar into an EIP-7594 sidecar with the default settings.
1102    ///
1103    /// This requires computing cell KZG proofs from the blob data using the KZG trusted setup.
1104    /// Each blob produces `CELLS_PER_EXT_BLOB` cell proofs.
1105    #[cfg(feature = "kzg")]
1106    pub fn try_into_7594(
1107        self,
1108    ) -> Result<
1109        TxEip4844WithSidecar<alloy_eips::eip7594::BlobTransactionSidecarEip7594>,
1110        c_kzg::Error,
1111    > {
1112        self.try_into_7594_with_settings(
1113            alloy_eips::eip4844::env_settings::EnvKzgSettings::Default.get(),
1114        )
1115    }
1116
1117    /// Converts this legacy EIP-4844 sidecar into an EIP-7594 sidecar with the given settings.
1118    ///
1119    /// This requires computing cell KZG proofs from the blob data using the KZG trusted setup.
1120    /// Each blob produces `CELLS_PER_EXT_BLOB` cell proofs.
1121    #[cfg(feature = "kzg")]
1122    pub fn try_into_7594_with_settings(
1123        self,
1124        settings: &c_kzg::KzgSettings,
1125    ) -> Result<
1126        TxEip4844WithSidecar<alloy_eips::eip7594::BlobTransactionSidecarEip7594>,
1127        c_kzg::Error,
1128    > {
1129        self.try_map_sidecar(|sidecar| sidecar.try_into_7594(settings))
1130    }
1131}
1132
1133impl<T: TxEip4844Sidecar> TxEip4844WithSidecar<T> {
1134    /// Verifies that the transaction's blob data, commitments, and proofs are all valid.
1135    ///
1136    /// See also [TxEip4844::validate_blob]
1137    #[cfg(feature = "kzg")]
1138    pub fn validate_blob(
1139        &self,
1140        proof_settings: &c_kzg::KzgSettings,
1141    ) -> Result<(), BlobTransactionValidationError> {
1142        self.tx.validate_blob(&self.sidecar, proof_settings)
1143    }
1144
1145    /// Calculates a heuristic for the in-memory size of the [TxEip4844WithSidecar] transaction.
1146    #[inline]
1147    pub fn size(&self) -> usize {
1148        self.tx.size() + self.sidecar.size()
1149    }
1150}
1151
1152impl<T> SignableTransaction<Signature> for TxEip4844WithSidecar<T>
1153where
1154    T: fmt::Debug + Send + Sync + 'static,
1155{
1156    fn set_chain_id(&mut self, chain_id: ChainId) {
1157        self.tx.chain_id = chain_id;
1158    }
1159
1160    fn encode_for_signing(&self, out: &mut dyn alloy_rlp::BufMut) {
1161        // A signature for a [TxEip4844WithSidecar] is a signature over the [TxEip4844] EIP-2718
1162        // payload fields:
1163        // (BLOB_TX_TYPE ||
1164        //   rlp([chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, to, value,
1165        //     data, access_list, max_fee_per_blob_gas, blob_versioned_hashes]))
1166        self.tx.encode_for_signing(out);
1167    }
1168
1169    fn payload_len_for_signature(&self) -> usize {
1170        // The payload length is the length of the `transaction_payload_body` list.
1171        // The sidecar is NOT included.
1172        self.tx.payload_len_for_signature()
1173    }
1174}
1175
1176impl<T> Transaction for TxEip4844WithSidecar<T>
1177where
1178    T: fmt::Debug + Send + Sync + 'static,
1179{
1180    #[inline]
1181    fn chain_id(&self) -> Option<ChainId> {
1182        self.tx.chain_id()
1183    }
1184
1185    #[inline]
1186    fn nonce(&self) -> u64 {
1187        self.tx.nonce()
1188    }
1189
1190    #[inline]
1191    fn gas_limit(&self) -> u64 {
1192        self.tx.gas_limit()
1193    }
1194
1195    #[inline]
1196    fn gas_price(&self) -> Option<u128> {
1197        self.tx.gas_price()
1198    }
1199
1200    #[inline]
1201    fn max_fee_per_gas(&self) -> u128 {
1202        self.tx.max_fee_per_gas()
1203    }
1204
1205    #[inline]
1206    fn max_priority_fee_per_gas(&self) -> Option<u128> {
1207        self.tx.max_priority_fee_per_gas()
1208    }
1209
1210    #[inline]
1211    fn max_fee_per_blob_gas(&self) -> Option<u128> {
1212        self.tx.max_fee_per_blob_gas()
1213    }
1214
1215    #[inline]
1216    fn priority_fee_or_price(&self) -> u128 {
1217        self.tx.priority_fee_or_price()
1218    }
1219
1220    fn effective_gas_price(&self, base_fee: Option<u64>) -> u128 {
1221        self.tx.effective_gas_price(base_fee)
1222    }
1223
1224    #[inline]
1225    fn is_dynamic_fee(&self) -> bool {
1226        self.tx.is_dynamic_fee()
1227    }
1228
1229    #[inline]
1230    fn kind(&self) -> TxKind {
1231        self.tx.kind()
1232    }
1233
1234    #[inline]
1235    fn is_create(&self) -> bool {
1236        false
1237    }
1238
1239    #[inline]
1240    fn value(&self) -> U256 {
1241        self.tx.value()
1242    }
1243
1244    #[inline]
1245    fn input(&self) -> &Bytes {
1246        self.tx.input()
1247    }
1248
1249    #[inline]
1250    fn access_list(&self) -> Option<&AccessList> {
1251        Some(&self.tx.access_list)
1252    }
1253
1254    #[inline]
1255    fn blob_versioned_hashes(&self) -> Option<&[B256]> {
1256        self.tx.blob_versioned_hashes()
1257    }
1258
1259    #[inline]
1260    fn authorization_list(&self) -> Option<&[SignedAuthorization]> {
1261        None
1262    }
1263}
1264
1265impl<T> Typed2718 for TxEip4844WithSidecar<T> {
1266    fn ty(&self) -> u8 {
1267        TxType::Eip4844 as u8
1268    }
1269}
1270
1271impl<T: Encodable7594> RlpEcdsaEncodableTx for TxEip4844WithSidecar<T> {
1272    fn rlp_encoded_fields_length(&self) -> usize {
1273        self.sidecar.encode_7594_len() + self.tx.rlp_encoded_length()
1274    }
1275
1276    fn rlp_encode_fields(&self, out: &mut dyn alloy_rlp::BufMut) {
1277        self.tx.rlp_encode(out);
1278        self.sidecar.encode_7594(out);
1279    }
1280
1281    fn rlp_header_signed(&self, signature: &Signature) -> Header {
1282        let payload_length =
1283            self.tx.rlp_encoded_length_with_signature(signature) + self.sidecar.encode_7594_len();
1284        Header { list: true, payload_length }
1285    }
1286
1287    fn rlp_encode_signed(&self, signature: &Signature, out: &mut dyn BufMut) {
1288        self.rlp_header_signed(signature).encode(out);
1289        self.tx.rlp_encode_signed(signature, out);
1290        self.sidecar.encode_7594(out);
1291    }
1292
1293    fn tx_hash_with_type(&self, signature: &Signature, ty: u8) -> alloy_primitives::TxHash {
1294        // eip4844 tx_hash is always based on the non-sidecar encoding
1295        self.tx.tx_hash_with_type(signature, ty)
1296    }
1297}
1298
1299impl<T: Encodable7594 + Decodable7594> RlpEcdsaDecodableTx for TxEip4844WithSidecar<T> {
1300    const DEFAULT_TX_TYPE: u8 = { Self::tx_type() as u8 };
1301
1302    fn rlp_decode_fields(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
1303        let tx = TxEip4844::rlp_decode(buf)?;
1304        let sidecar = T::decode_7594(buf)?;
1305        Ok(Self { tx, sidecar })
1306    }
1307
1308    fn rlp_decode_with_signature(buf: &mut &[u8]) -> alloy_rlp::Result<(Self, Signature)> {
1309        let header = Header::decode(buf)?;
1310        if !header.list {
1311            return Err(alloy_rlp::Error::UnexpectedString);
1312        }
1313        let remaining = buf.len();
1314
1315        let (tx, signature) = TxEip4844::rlp_decode_with_signature(buf)?;
1316        let sidecar = T::decode_7594(buf)?;
1317
1318        if buf.len() + header.payload_length != remaining {
1319            return Err(alloy_rlp::Error::UnexpectedLength);
1320        }
1321
1322        Ok((Self { tx, sidecar }, signature))
1323    }
1324}
1325
1326#[cfg(test)]
1327mod tests {
1328    use super::{BlobTransactionSidecar, TxEip4844, TxEip4844WithSidecar};
1329    use crate::{
1330        transaction::{eip4844::TxEip4844Variant, RlpEcdsaDecodableTx},
1331        SignableTransaction, TxEnvelope,
1332    };
1333    use alloy_eips::{
1334        eip2930::AccessList, eip4844::env_settings::EnvKzgSettings,
1335        eip7594::BlobTransactionSidecarVariant, Encodable2718 as _,
1336    };
1337    use alloy_primitives::{address, b256, bytes, hex, Signature, U256};
1338    use alloy_rlp::{Decodable, Encodable};
1339    use assert_matches::assert_matches;
1340    use std::path::PathBuf;
1341
1342    #[test]
1343    fn different_sidecar_same_hash() {
1344        // this should make sure that the hash calculated for the `into_signed` conversion does not
1345        // change if the sidecar is different
1346        let tx = TxEip4844 {
1347            chain_id: 1,
1348            nonce: 1,
1349            max_priority_fee_per_gas: 1,
1350            max_fee_per_gas: 1,
1351            gas_limit: 1,
1352            to: Default::default(),
1353            value: U256::from(1),
1354            access_list: Default::default(),
1355            blob_versioned_hashes: vec![Default::default()],
1356            max_fee_per_blob_gas: 1,
1357            input: Default::default(),
1358        };
1359        let sidecar = BlobTransactionSidecar {
1360            blobs: vec![[2; 131072].into()],
1361            commitments: vec![[3; 48].into()],
1362            proofs: vec![[4; 48].into()],
1363        };
1364        let mut tx = TxEip4844WithSidecar { tx, sidecar };
1365        let signature = Signature::test_signature();
1366
1367        // turn this transaction into_signed
1368        let expected_signed = tx.clone().into_signed(signature);
1369
1370        // change the sidecar, adding a single (blob, commitment, proof) pair
1371        tx.sidecar = BlobTransactionSidecar {
1372            blobs: vec![[1; 131072].into()],
1373            commitments: vec![[1; 48].into()],
1374            proofs: vec![[1; 48].into()],
1375        };
1376
1377        // turn this transaction into_signed
1378        let actual_signed = tx.into_signed(signature);
1379
1380        // the hashes should be the same
1381        assert_eq!(expected_signed.hash(), actual_signed.hash());
1382
1383        // convert to envelopes
1384        let expected_envelope: TxEnvelope = expected_signed.into();
1385        let actual_envelope: TxEnvelope = actual_signed.into();
1386
1387        // now encode the transaction and check the length
1388        let len = expected_envelope.length();
1389        let mut buf = Vec::with_capacity(len);
1390        expected_envelope.encode(&mut buf);
1391        assert_eq!(buf.len(), len);
1392
1393        // ensure it's also the same size that `actual` claims to be, since we just changed the
1394        // sidecar values.
1395        assert_eq!(buf.len(), actual_envelope.length());
1396
1397        // now decode the transaction and check the values
1398        let decoded = TxEnvelope::decode(&mut &buf[..]).unwrap();
1399        assert_eq!(decoded, expected_envelope);
1400    }
1401
1402    #[test]
1403    fn test_4844_variant_into_signed_correct_hash() {
1404        // Taken from <https://etherscan.io/tx/0x93fc9daaa0726c3292a2e939df60f7e773c6a6a726a61ce43f4a217c64d85e87>
1405        let tx =
1406            TxEip4844 {
1407                chain_id: 1,
1408                nonce: 15435,
1409                gas_limit: 8000000,
1410                max_fee_per_gas: 10571233596,
1411                max_priority_fee_per_gas: 1000000000,
1412                to: address!("a8cb082a5a689e0d594d7da1e2d72a3d63adc1bd"),
1413                value: U256::ZERO,
1414                access_list: AccessList::default(),
1415                blob_versioned_hashes: vec![
1416                    b256!("01e5276d91ac1ddb3b1c2d61295211220036e9a04be24c00f76916cc2659d004"),
1417                    b256!("0128eb58aff09fd3a7957cd80aa86186d5849569997cdfcfa23772811b706cc2"),
1418                ],
1419                max_fee_per_blob_gas: 1,
1420                input: bytes!("701f58c50000000000000000000000000000000000000000000000000000000000073fb1ed12e288def5b439ea074b398dbb4c967f2852baac3238c5fe4b62b871a59a6d00000000000000000000000000000000000000000000000000000000123971da000000000000000000000000000000000000000000000000000000000000000ac39b2a24e1dbdd11a1e7bd7c0f4dfd7d9b9cfa0997d033ad05f961ba3b82c6c83312c967f10daf5ed2bffe309249416e03ee0b101f2b84d2102b9e38b0e4dfdf0000000000000000000000000000000000000000000000000000000066254c8b538dcc33ecf5334bbd294469f9d4fd084a3090693599a46d6c62567747cbc8660000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000073fb20000000000000000000000000000000000000000000000000000000066254da10000000000000000000000000000000000000000000000000000000012397d5e20b09b263779fda4171c341e720af8fa469621ff548651f8dbbc06c2d320400c000000000000000000000000000000000000000000000000000000000000000b50a833bb11af92814e99c6ff7cf7ba7042827549d6f306a04270753702d897d8fc3c411b99159939ac1c16d21d3057ddc8b2333d1331ab34c938cff0eb29ce2e43241c170344db6819f76b1f1e0ab8206f3ec34120312d275c4f5bbea7f5c55700000000000000000000000000000000000000000000000000000000000001400000000000000000000000000000000000000000000000000000000000000480000000000000000000000000000000000000000000000000000000000000031800000000000000000000000000000000000000000000800b0000000000000000000000000000000000000000000000000000000000000004ed12e288def5b439ea074b398dbb4c967f2852baac3238c5fe4b62b871a59a6d00000ca8000000000000000000000000000000000000800b000000000000000000000000000000000000000000000000000000000000000300000000000000000000000066254da100000000000000000000000066254e9d00010ca80000000000000000000000000000000000008001000000000000000000000000000000000000000000000000000000000000000550a833bb11af92814e99c6ff7cf7ba7042827549d6f306a04270753702d897d800010ca800000000000000000000000000000000000080010000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000b00010ca8000000000000000000000000000000000000801100000000000000000000000000000000000000000000000000000000000000075c1cd5bd0fd333ce9d7c8edfc79f43b8f345b4a394f6aba12a2cc78ce4012ed700010ca80000000000000000000000000000000000008011000000000000000000000000000000000000000000000000000000000000000845392775318aa47beaafbdc827da38c9f1e88c3bdcabba2cb493062e17cbf21e00010ca800000000000000000000000000000000000080080000000000000000000000000000000000000000000000000000000000000000c094e20e7ac9b433f44a5885e3bdc07e51b309aeb993caa24ba84a661ac010c100010ca800000000000000000000000000000000000080080000000000000000000000000000000000000000000000000000000000000001ab42db8f4ed810bdb143368a2b641edf242af6e3d0de8b1486e2b0e7880d431100010ca8000000000000000000000000000000000000800800000000000000000000000000000000000000000000000000000000000000022d94e4cc4525e4e2d81e8227b6172e97076431a2cf98792d978035edd6e6f3100000000000000000000000000000000000000000000000000000000000000000000000000000012101c74dfb80a80fccb9a4022b2406f79f56305e6a7c931d30140f5d372fe793837e93f9ec6b8d89a9d0ab222eeb27547f66b90ec40fbbdd2a4936b0b0c19ca684ff78888fbf5840d7c8dc3c493b139471750938d7d2c443e2d283e6c5ee9fde3765a756542c42f002af45c362b4b5b1687a8fc24cbf16532b903f7bb289728170dcf597f5255508c623ba247735538376f494cdcdd5bd0c4cb067526eeda0f4745a28d8baf8893ecc1b8cee80690538d66455294a028da03ff2add9d8a88e6ee03ba9ffe3ad7d91d6ac9c69a1f28c468f00fe55eba5651a2b32dc2458e0d14b4dd6d0173df255cd56aa01e8e38edec17ea8933f68543cbdc713279d195551d4211bed5c91f77259a695e6768f6c4b110b2158fcc42423a96dcc4e7f6fddb3e2369d00000000000000000000000000000000000000000000000000000000000000") };
1421        let variant = TxEip4844Variant::<BlobTransactionSidecar>::TxEip4844(tx);
1422
1423        let signature = Signature::new(
1424            b256!("6c173c3c8db3e3299f2f728d293b912c12e75243e3aa66911c2329b58434e2a4").into(),
1425            b256!("7dd4d1c228cedc5a414a668ab165d9e888e61e4c3b44cd7daf9cdcc4cec5d6b2").into(),
1426            false,
1427        );
1428
1429        let signed = variant.into_signed(signature);
1430        assert_eq!(
1431            *signed.hash(),
1432            b256!("93fc9daaa0726c3292a2e939df60f7e773c6a6a726a61ce43f4a217c64d85e87")
1433        );
1434    }
1435
1436    #[test]
1437    fn decode_raw_7594_rlp() {
1438        let kzg_settings = EnvKzgSettings::default();
1439        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("testdata/7594rlp");
1440        let dir = std::fs::read_dir(path).expect("Unable to read folder");
1441        for entry in dir {
1442            let entry = entry.unwrap();
1443            let content = std::fs::read_to_string(entry.path()).unwrap();
1444            let raw = hex::decode(content.trim()).unwrap();
1445            let tx = TxEip4844WithSidecar::<BlobTransactionSidecarVariant>::eip2718_decode(
1446                &mut raw.as_ref(),
1447            )
1448            .map_err(|err| {
1449                panic!("Failed to decode transaction: {:?} {:?}", err, entry.path());
1450            })
1451            .unwrap();
1452
1453            // Test roundtrip
1454            let encoded = tx.encoded_2718();
1455            assert_eq!(encoded.as_slice(), &raw[..], "{:?}", entry.path());
1456
1457            let TxEip4844WithSidecar { tx, sidecar } = tx.tx();
1458            assert_matches!(sidecar, BlobTransactionSidecarVariant::Eip7594(_));
1459
1460            let result = sidecar.validate(&tx.blob_versioned_hashes, kzg_settings.get());
1461            assert_matches!(result, Ok(()));
1462        }
1463    }
1464
1465    #[test]
1466    fn decode_raw_7594_rlp_invalid() {
1467        let kzg_settings = EnvKzgSettings::default();
1468        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("testdata/7594rlp-invalid");
1469        let dir = std::fs::read_dir(path).expect("Unable to read folder");
1470        for entry in dir {
1471            let entry = entry.unwrap();
1472
1473            if entry.path().file_name().and_then(|f| f.to_str()) == Some("0.rlp") {
1474                continue;
1475            }
1476
1477            let content = std::fs::read_to_string(entry.path()).unwrap();
1478            let raw = hex::decode(content.trim()).unwrap();
1479            let tx = TxEip4844WithSidecar::<BlobTransactionSidecarVariant>::eip2718_decode(
1480                &mut raw.as_ref(),
1481            )
1482            .map_err(|err| {
1483                panic!("Failed to decode transaction: {:?} {:?}", err, entry.path());
1484            })
1485            .unwrap();
1486
1487            // Test roundtrip
1488            let encoded = tx.encoded_2718();
1489            assert_eq!(encoded.as_slice(), &raw[..], "{:?}", entry.path());
1490
1491            let TxEip4844WithSidecar { tx, sidecar } = tx.tx();
1492            assert_matches!(sidecar, BlobTransactionSidecarVariant::Eip7594(_));
1493
1494            let result = sidecar.validate(&tx.blob_versioned_hashes, kzg_settings.get());
1495            assert_matches!(result, Err(_));
1496        }
1497    }
1498}