Skip to main content

foundry_primitives/transaction/
request.rs

1use super::{CIP64_TX_TYPE, FoundryTxEnvelope, FoundryTxType, FoundryTypedTx, TxCip64};
2use crate::FoundryNetwork;
3use alloy_consensus::{BlobTransactionSidecarVariant, EthereumTypedTransaction};
4use alloy_network::{
5    BuildResult, NetworkTransactionBuilder, NetworkWallet, TransactionBuilder,
6    TransactionBuilder4844, TransactionBuilderError,
7};
8use alloy_primitives::{Address, ChainId, TxKind, U256};
9use alloy_rpc_types::{AccessList, TransactionInputKind, TransactionRequest};
10use alloy_serde::WithOtherFields;
11use core::num::NonZeroU64;
12use serde::{Deserialize, Serialize};
13use tempo_primitives::{
14    SignatureType, TEMPO_TX_TYPE_ID, TempoTxType,
15    transaction::{Call, SignedKeyAuthorization, TempoSignedAuthorization},
16};
17
18#[cfg(all(feature = "base", not(feature = "optimism")))]
19use op_alloy_consensus::{DEPOSIT_TX_TYPE_ID, TxDeposit};
20
21#[cfg(any(feature = "base", feature = "optimism"))]
22use super::DepositTransactionParts;
23#[cfg(any(feature = "base", feature = "optimism"))]
24use super::get_deposit_tx_parts;
25
26#[cfg(any(test, feature = "base", feature = "optimism"))]
27use alloy_serde::OtherFields;
28
29#[cfg(feature = "base")]
30use base_common_consensus::BASE_TX_TYPE_ID as EIP8130_TRANSACTION_TYPE;
31#[cfg(feature = "base")]
32use base_common_rpc_types::BaseTransactionRequest;
33
34#[cfg(feature = "optimism")]
35use op_alloy_consensus::{DEPOSIT_TX_TYPE_ID, POST_EXEC_TX_TYPE_ID, TxDeposit};
36
37pub use tempo_alloy::rpc::TempoTransactionRequest;
38
39/// Foundry transaction request builder.
40///
41/// This is a union of different transaction request types, instantiated from a
42/// [`WithOtherFields<TransactionRequest>`]. The specific variant is determined by the transaction
43/// type field and/or the presence of certain fields:
44/// - **Ethereum**: Default variant when no special fields are present
45/// - **Op**: When `sourceHash`, `mint`, and `isSystemTx` fields are present, or transaction type is
46///   `DEPOSIT_TX_TYPE_ID`
47/// - **Celo**: When `feeCurrency` is non-null, or transaction type is `0x7b`
48/// - **Tempo**: When a Tempo-specific field is present, or transaction type is `TEMPO_TX_TYPE_ID`
49#[derive(Clone, Debug, PartialEq, Eq)]
50#[allow(clippy::large_enum_variant)]
51pub enum FoundryTransactionRequest {
52    Ethereum(TransactionRequest),
53    #[cfg(feature = "base")]
54    Base(BaseTransactionRequest),
55    #[cfg(any(feature = "base", feature = "optimism"))]
56    Op(WithOtherFields<TransactionRequest>),
57    Tempo(Box<TempoTransactionRequest>),
58    /// CIP-64 fields alongside the ordinary transaction request.
59    Celo(Cip64TransactionRequest),
60}
61
62/// Celo CIP-64 request fields. Anvil currently charges native fees.
63#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
64#[serde(rename_all = "camelCase")]
65pub struct Cip64TransactionRequest {
66    /// Ordinary transaction request fields.
67    #[serde(flatten)]
68    pub inner: TransactionRequest,
69    /// Fee currency retained in the signed envelope.
70    pub fee_currency: Option<Address>,
71}
72
73const TEMPO_REQUEST_FIELDS: &[&str] = &[
74    "feeToken",
75    "nonceKey",
76    "calls",
77    "keyType",
78    "keyData",
79    "keyId",
80    "aaAuthorizationList",
81    "keyAuthorization",
82    "validBefore",
83    "validAfter",
84    "feePayerSignature",
85    "configurableAccountSimulation",
86    "keyAuthorizationSimulation",
87];
88
89impl FoundryTransactionRequest {
90    /// Returns `true` if this is an Ethereum transaction request.
91    pub const fn is_ethereum(&self) -> bool {
92        matches!(self, Self::Ethereum(_))
93    }
94
95    /// Returns `true` if this is a Base EIP-8130 request.
96    #[cfg(feature = "base")]
97    pub const fn is_base(&self) -> bool {
98        matches!(self, Self::Base(_))
99    }
100
101    /// Returns the native Base request.
102    #[cfg(feature = "base")]
103    pub const fn as_base(&self) -> Option<&BaseTransactionRequest> {
104        match self {
105            Self::Base(request) => Some(request),
106            _ => None,
107        }
108    }
109
110    /// Returns `true` if this is an OP stack transaction request.
111    #[cfg(any(feature = "base", feature = "optimism"))]
112    pub const fn is_op(&self) -> bool {
113        matches!(self, Self::Op(_))
114    }
115
116    /// Returns `true` if this is a Tempo transaction request.
117    pub const fn is_tempo(&self) -> bool {
118        matches!(self, Self::Tempo(_))
119    }
120
121    /// Create a new [`FoundryTransactionRequest`] from given
122    /// [`WithOtherFields<TransactionRequest>`].
123    #[inline]
124    pub fn new(inner: WithOtherFields<TransactionRequest>) -> serde_json::Result<Self> {
125        inner.try_into()
126    }
127
128    /// Consume the [`FoundryTransactionRequest`] and return the inner transaction request.
129    pub fn into_inner(self) -> TransactionRequest {
130        match self {
131            Self::Ethereum(tx) => tx,
132            Self::Celo(tx) => tx.inner,
133            #[cfg(feature = "base")]
134            Self::Base(tx) => tx.into(),
135            #[cfg(any(feature = "base", feature = "optimism"))]
136            Self::Op(tx) => tx.inner,
137            Self::Tempo(tx) => tx.inner,
138        }
139    }
140
141    /// Get the deposit transaction parts from the request, calling [`get_deposit_tx_parts`] helper
142    /// with OtherFields.
143    ///
144    /// # Returns
145    /// - Ok(deposit_tx_parts) if all necessary keys are present to build a deposit transaction.
146    /// - Err(missing) if some keys are missing to build a deposit transaction.
147    #[cfg(any(feature = "base", feature = "optimism"))]
148    pub fn get_deposit_tx_parts(&self) -> Result<DepositTransactionParts, Vec<&'static str>> {
149        match self {
150            Self::Op(tx) => get_deposit_tx_parts(&tx.other),
151            // Not a deposit transaction request, so missing at least sourceHash, mint, and
152            // isSystemTx
153            _ => Err(vec!["sourceHash", "mint", "isSystemTx"]),
154        }
155    }
156
157    /// Returns the minimal transaction type this request can be converted into based on the fields
158    /// that are set. See [`TransactionRequest::preferred_type`].
159    pub fn preferred_type(&self) -> FoundryTxType {
160        match self {
161            Self::Ethereum(tx) => tx.preferred_type().into(),
162            #[cfg(feature = "base")]
163            Self::Base(_) => FoundryTxType::Eip8130,
164            #[cfg(feature = "optimism")]
165            Self::Op(tx) if tx.inner.transaction_type == Some(POST_EXEC_TX_TYPE_ID) => {
166                FoundryTxType::PostExec
167            }
168            #[cfg(any(feature = "base", feature = "optimism"))]
169            Self::Op(_) => FoundryTxType::Deposit,
170            Self::Tempo(_) => FoundryTxType::Tempo,
171            Self::Celo(_) => FoundryTxType::Celo,
172        }
173    }
174
175    /// Check if all necessary keys are present to build a 4844 transaction,
176    /// returning a list of keys that are missing.
177    ///
178    /// **NOTE:** Inner [`TransactionRequest::complete_4844`] method but "sidecar" key is filtered
179    /// from error.
180    pub fn complete_4844(&self) -> Result<(), Vec<&'static str>> {
181        match self.as_ref().complete_4844() {
182            Ok(()) => Ok(()),
183            Err(missing) => {
184                let filtered: Vec<_> =
185                    missing.into_iter().filter(|&key| key != "sidecar").collect();
186                if filtered.is_empty() { Ok(()) } else { Err(filtered) }
187            }
188        }
189    }
190
191    /// Check if all necessary keys are present to build a Deposit transaction, returning a list of
192    /// keys that are missing.
193    #[cfg(any(feature = "base", feature = "optimism"))]
194    pub fn complete_deposit(&self) -> Result<(), Vec<&'static str>> {
195        self.get_deposit_tx_parts().map(|_| ())
196    }
197
198    /// Check if all necessary keys are present to build a Tempo transaction, returning a list of
199    /// keys that are missing.
200    pub fn complete_tempo(&self) -> Result<(), Vec<&'static str>> {
201        match self {
202            Self::Tempo(tx) => tx.complete_type(TempoTxType::AA).map(|_| ()),
203            // Not a Tempo transaction request, so missing at least feeToken and nonceKey
204            _ => Err(vec!["feeToken", "nonceKey"]),
205        }
206    }
207
208    fn check_type(&self, ty: FoundryTxType) -> Result<(), Vec<&'static str>> {
209        match ty {
210            FoundryTxType::Legacy => self.as_ref().complete_legacy(),
211            FoundryTxType::Eip2930 => self.as_ref().complete_2930(),
212            FoundryTxType::Eip1559 => self.as_ref().complete_1559(),
213            FoundryTxType::Eip4844 => self.as_ref().complete_4844(),
214            FoundryTxType::Eip7702 => self.as_ref().complete_7702(),
215            #[cfg(any(feature = "base", feature = "optimism"))]
216            FoundryTxType::Deposit => self.complete_deposit(),
217            #[cfg(feature = "optimism")]
218            FoundryTxType::PostExec => Err(vec!["not implemented for post-exec tx"]),
219            #[cfg(feature = "base")]
220            FoundryTxType::Eip8130 => {
221                Err(vec!["EIP-8130 requires a signed raw transaction envelope"])
222            }
223            FoundryTxType::Tempo => self.complete_tempo(),
224            FoundryTxType::Celo => self.as_ref().complete_1559(),
225        }
226    }
227
228    /// Check if all necessary keys are present to build a transaction.
229    ///
230    /// # Returns
231    ///
232    /// - Ok(type) if all necessary keys are present to build the preferred type.
233    /// - Err((type, missing)) if some keys are missing to build the preferred type.
234    pub fn missing_keys(&self) -> Result<FoundryTxType, (FoundryTxType, Vec<&'static str>)> {
235        let pref = self.preferred_type();
236        let result = if pref.is_eip4844() { self.complete_4844() } else { self.check_type(pref) };
237        if let Err(missing) = result { Err((pref, missing)) } else { Ok(pref) }
238    }
239
240    /// Build a typed transaction from this request.
241    ///
242    /// Converts the request into a `FoundryTypedTx`, handling all Ethereum and OP-stack transaction
243    /// types.
244    pub fn build_typed_tx(self) -> Result<FoundryTypedTx, Self> {
245        if let Self::Celo(request) = self {
246            let fee_currency = request.fee_currency;
247            return request
248                .inner
249                .clone()
250                .build_1559()
251                .map(|inner| FoundryTypedTx::Celo(TxCip64 { inner, fee_currency }))
252                .map_err(|_| Self::Celo(request));
253        }
254        #[cfg(feature = "base")]
255        if self.is_base() {
256            return Err(self);
257        }
258        #[cfg(any(feature = "base", feature = "optimism"))]
259        if let Ok(deposit_tx_parts) = self.get_deposit_tx_parts() {
260            // Build deposit transaction
261            return Ok(FoundryTypedTx::Deposit(TxDeposit {
262                from: self.from().unwrap_or_default(),
263                source_hash: deposit_tx_parts.source_hash,
264                to: self.kind().unwrap_or_default(),
265                mint: deposit_tx_parts.mint.unwrap_or_default(),
266                value: self.value().unwrap_or_default(),
267                gas_limit: self.gas_limit().unwrap_or_default(),
268                is_system_transaction: deposit_tx_parts.is_system_transaction,
269                input: self.input().cloned().unwrap_or_default(),
270            }));
271        }
272        if self.complete_tempo().is_ok()
273            && let Self::Tempo(tx_req) = self
274        {
275            // Build Tempo transaction
276            Ok(FoundryTypedTx::Tempo(
277                tx_req.build_aa().map_err(|e| Self::Tempo(Box::new(e.into_value())))?,
278            ))
279        } else if self.as_ref().has_eip4844_fields() && self.blob_sidecar().is_none() {
280            // if request has eip4844 fields but no blob sidecar (neither eip4844 nor eip7594
281            // format), try to build to eip4844 without sidecar
282            self.into_inner()
283                .build_4844_without_sidecar()
284                .map_err(|e| Self::Ethereum(e.into_value()))
285                .map(|tx| FoundryTypedTx::Eip4844(tx.into()))
286        } else {
287            // Use the inner transaction request to build EthereumTypedTransaction
288            let typed_tx = self.into_inner().build_typed_tx().map_err(Self::Ethereum)?;
289            // Convert EthereumTypedTransaction to FoundryTypedTx
290            Ok(match typed_tx {
291                EthereumTypedTransaction::Legacy(tx) => FoundryTypedTx::Legacy(tx),
292                EthereumTypedTransaction::Eip2930(tx) => FoundryTypedTx::Eip2930(tx),
293                EthereumTypedTransaction::Eip1559(tx) => FoundryTypedTx::Eip1559(tx),
294                EthereumTypedTransaction::Eip4844(tx) => FoundryTypedTx::Eip4844(tx),
295                EthereumTypedTransaction::Eip7702(tx) => FoundryTypedTx::Eip7702(tx),
296            })
297        }
298    }
299}
300
301impl Default for FoundryTransactionRequest {
302    fn default() -> Self {
303        Self::Ethereum(TransactionRequest::default())
304    }
305}
306
307impl Serialize for FoundryTransactionRequest {
308    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
309    where
310        S: serde::Serializer,
311    {
312        match self {
313            Self::Ethereum(tx) => tx.serialize(serializer),
314            #[cfg(feature = "base")]
315            Self::Base(tx) => tx.serialize(serializer),
316            #[cfg(any(feature = "base", feature = "optimism"))]
317            Self::Op(tx) => tx.serialize(serializer),
318            Self::Tempo(tx) => tx.serialize(serializer),
319            Self::Celo(tx) => tx.serialize(serializer),
320        }
321    }
322}
323
324impl<'de> Deserialize<'de> for FoundryTransactionRequest {
325    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
326    where
327        D: serde::Deserializer<'de>,
328    {
329        Self::new(WithOtherFields::<TransactionRequest>::deserialize(deserializer)?)
330            .map_err(serde::de::Error::custom)
331    }
332}
333
334impl AsRef<TransactionRequest> for FoundryTransactionRequest {
335    fn as_ref(&self) -> &TransactionRequest {
336        match self {
337            Self::Ethereum(tx) => tx,
338            #[cfg(feature = "base")]
339            Self::Base(tx) => tx.as_ref(),
340            #[cfg(any(feature = "base", feature = "optimism"))]
341            Self::Op(tx) => tx,
342            Self::Tempo(tx) => tx.as_ref(),
343            Self::Celo(tx) => &tx.inner,
344        }
345    }
346}
347
348impl AsMut<TransactionRequest> for FoundryTransactionRequest {
349    fn as_mut(&mut self) -> &mut TransactionRequest {
350        match self {
351            Self::Ethereum(tx) => tx,
352            #[cfg(feature = "base")]
353            Self::Base(tx) => tx.as_mut(),
354            #[cfg(any(feature = "base", feature = "optimism"))]
355            Self::Op(tx) => tx,
356            Self::Tempo(tx) => tx.as_mut(),
357            Self::Celo(tx) => &mut tx.inner,
358        }
359    }
360}
361
362impl TryFrom<WithOtherFields<TransactionRequest>> for FoundryTransactionRequest {
363    type Error = serde_json::Error;
364
365    fn try_from(tx: WithOtherFields<TransactionRequest>) -> Result<Self, Self::Error> {
366        if tx.transaction_type == Some(CIP64_TX_TYPE)
367            || tx.other.get("feeCurrency").is_some_and(|value| !value.is_null())
368        {
369            if tx.transaction_type.is_some_and(|ty| ty != CIP64_TX_TYPE)
370                || tx.gas_price.is_some()
371                || tx.has_eip4844_fields()
372                || tx.authorization_list.is_some()
373                || TEMPO_REQUEST_FIELDS.iter().any(|field| tx.other.contains_key(*field))
374                || [
375                    "accountChanges",
376                    "metadata",
377                    "sender",
378                    "senderAuth",
379                    "payer",
380                    "payerAuth",
381                    "sourceHash",
382                    "mint",
383                    "isSystemTx",
384                ]
385                .iter()
386                .any(|field| tx.other.get(*field).is_some_and(|value| !value.is_null()))
387            {
388                return Err(serde::de::Error::custom("conflicting CIP-64 transaction fields"));
389            }
390            let fee_currency =
391                tx.other.get_deserialized::<Option<Address>>("feeCurrency").transpose()?.flatten();
392            let mut inner = tx.inner;
393            inner.transaction_type = Some(CIP64_TX_TYPE);
394            return Ok(Self::Celo(Cip64TransactionRequest { inner, fee_currency }));
395        }
396        #[derive(Deserialize)]
397        struct NonZeroQuantity(#[serde(with = "alloy_serde::quantity::opt")] Option<NonZeroU64>);
398
399        #[cfg(feature = "base")]
400        {
401            let present = |field: &str| tx.other.get(field).is_some_and(|value| !value.is_null());
402            let base_fields =
403                ["accountChanges", "metadata", "sender", "senderAuth", "payer", "payerAuth"]
404                    .iter()
405                    .any(|field| present(field));
406            let phased_calls = tx
407                .other
408                .get("calls")
409                .and_then(serde_json::Value::as_array)
410                .is_some_and(|calls| calls.first().is_some_and(serde_json::Value::is_array));
411            let explicit_base = tx.transaction_type == Some(EIP8130_TRANSACTION_TYPE);
412            if base_fields || phased_calls || explicit_base {
413                if tx.transaction_type.is_some() && !explicit_base {
414                    return Err(serde::de::Error::custom(
415                        "Base fields conflict with transaction type",
416                    ));
417                }
418                if TEMPO_REQUEST_FIELDS.iter().any(|field| {
419                    !matches!(*field, "nonceKey" | "calls" | "validBefore" | "validAfter")
420                        && present(field)
421                }) {
422                    return Err(serde::de::Error::custom(
423                        "conflicting Base and Tempo request fields",
424                    ));
425                }
426                let mut base =
427                    serde_json::from_value::<BaseTransactionRequest>(serde_json::to_value(&tx)?)?;
428                base.as_mut().transaction_type = Some(EIP8130_TRANSACTION_TYPE);
429                return Ok(Self::Base(base));
430            }
431        }
432
433        if tx.transaction_type == Some(TEMPO_TX_TYPE_ID)
434            || TEMPO_REQUEST_FIELDS.iter().any(|field| {
435                tx.other.get(*field).is_some_and(|value| {
436                    !value.is_null()
437                        && !matches!(
438                            (*field, value),
439                            (
440                                "calls" | "aaAuthorizationList",
441                                serde_json::Value::Array(values)
442                            ) if values.is_empty()
443                        )
444                })
445            })
446        {
447            let mut tempo_tx_req: TempoTransactionRequest = tx.inner.into();
448            tempo_tx_req.fee_token =
449                tx.other.get_deserialized::<Option<Address>>("feeToken").transpose()?.flatten();
450            tempo_tx_req.nonce_key =
451                tx.other.get_deserialized::<Option<U256>>("nonceKey").transpose()?.flatten();
452            tempo_tx_req.calls =
453                tx.other.get_deserialized::<Vec<Call>>("calls").transpose()?.unwrap_or_default();
454            tempo_tx_req.key_type = tx
455                .other
456                .get_deserialized::<Option<SignatureType>>("keyType")
457                .transpose()?
458                .flatten();
459            tempo_tx_req.key_data =
460                tx.other.get_deserialized::<Option<_>>("keyData").transpose()?.flatten();
461            tempo_tx_req.key_id =
462                tx.other.get_deserialized::<Option<_>>("keyId").transpose()?.flatten();
463            tempo_tx_req.tempo_authorization_list = tx
464                .other
465                .get_deserialized::<Vec<TempoSignedAuthorization>>("aaAuthorizationList")
466                .transpose()?
467                .unwrap_or_default();
468            tempo_tx_req.key_authorization = tx
469                .other
470                .get_deserialized::<Option<SignedKeyAuthorization>>("keyAuthorization")
471                .transpose()?
472                .flatten();
473            tempo_tx_req.valid_before = tx
474                .other
475                .get_deserialized::<NonZeroQuantity>("validBefore")
476                .transpose()?
477                .and_then(|value| value.0);
478            tempo_tx_req.valid_after = tx
479                .other
480                .get_deserialized::<NonZeroQuantity>("validAfter")
481                .transpose()?
482                .and_then(|value| value.0);
483            tempo_tx_req.fee_payer_signature =
484                tx.other.get_deserialized::<Option<_>>("feePayerSignature").transpose()?.flatten();
485            tempo_tx_req.configurable_account_simulation = tx
486                .other
487                .get_deserialized::<Option<_>>("configurableAccountSimulation")
488                .transpose()?
489                .flatten();
490            tempo_tx_req.key_authorization_simulation = tx
491                .other
492                .get_deserialized::<Option<_>>("keyAuthorizationSimulation")
493                .transpose()?
494                .flatten();
495            return Ok(Self::Tempo(Box::new(tempo_tx_req)));
496        }
497        #[cfg(all(feature = "base", not(feature = "optimism")))]
498        if tx.transaction_type == Some(DEPOSIT_TX_TYPE_ID)
499            || get_deposit_tx_parts(&tx.other).is_ok()
500        {
501            return Ok(Self::Op(tx));
502        }
503        #[cfg(feature = "optimism")]
504        if tx.transaction_type == Some(DEPOSIT_TX_TYPE_ID)
505            || tx.transaction_type == Some(POST_EXEC_TX_TYPE_ID)
506            || get_deposit_tx_parts(&tx.other).is_ok()
507        {
508            return Ok(Self::Op(tx));
509        }
510        Ok(Self::Ethereum(tx.into_inner()))
511    }
512}
513
514impl From<TransactionRequest> for FoundryTransactionRequest {
515    fn from(tx: TransactionRequest) -> Self {
516        Self::Ethereum(tx)
517    }
518}
519
520impl From<FoundryTypedTx> for FoundryTransactionRequest {
521    fn from(tx: FoundryTypedTx) -> Self {
522        match tx {
523            FoundryTypedTx::Legacy(tx) => Self::Ethereum(Into::<TransactionRequest>::into(tx)),
524            FoundryTypedTx::Eip2930(tx) => Self::Ethereum(Into::<TransactionRequest>::into(tx)),
525            FoundryTypedTx::Eip1559(tx) => Self::Ethereum(Into::<TransactionRequest>::into(tx)),
526            FoundryTypedTx::Eip4844(tx) => Self::Ethereum(Into::<TransactionRequest>::into(tx)),
527            FoundryTypedTx::Eip7702(tx) => Self::Ethereum(Into::<TransactionRequest>::into(tx)),
528            #[cfg(any(feature = "base", feature = "optimism"))]
529            FoundryTypedTx::Deposit(tx) => {
530                let other = OtherFields::from_iter([
531                    ("sourceHash", serde_json::to_value(tx.source_hash).unwrap()),
532                    ("mint", serde_json::to_value(U256::from(tx.mint)).unwrap()),
533                    ("isSystemTx", serde_json::to_value(tx.is_system_transaction).unwrap()),
534                ]);
535                WithOtherFields { inner: Into::<TransactionRequest>::into(tx), other }
536                    .try_into()
537                    .expect("valid deposit transaction request")
538            }
539            #[cfg(feature = "optimism")]
540            FoundryTypedTx::PostExec(tx) => Self::new(WithOtherFields {
541                inner: Into::<TransactionRequest>::into(tx),
542                other: OtherFields::default(),
543            })
544            .expect("valid OP post-exec transaction request"),
545            #[cfg(feature = "base")]
546            FoundryTypedTx::Eip8130(tx) => {
547                Self::Base(super::base::simulation_request(tx, None, None, None))
548            }
549            FoundryTypedTx::Tempo(tx) => Self::Tempo(Box::new(tx.into())),
550            FoundryTypedTx::Celo(tx) => {
551                let mut inner: TransactionRequest = tx.inner.into();
552                inner.transaction_type = Some(CIP64_TX_TYPE);
553                Self::Celo(Cip64TransactionRequest { inner, fee_currency: tx.fee_currency })
554            }
555        }
556    }
557}
558
559impl From<FoundryTxEnvelope> for FoundryTransactionRequest {
560    fn from(tx: FoundryTxEnvelope) -> Self {
561        #[cfg(feature = "base")]
562        if let FoundryTxEnvelope::Eip8130(tx) = tx {
563            let from = tx.recover_sender().ok();
564            let sender_auth = Some(tx.sender_auth().clone());
565            let payer_auth = Some(tx.payer_auth().clone());
566            return Self::Base(super::base::simulation_request(
567                tx.into_tx(),
568                from,
569                sender_auth,
570                payer_auth,
571            ));
572        }
573        FoundryTypedTx::from(tx).into()
574    }
575}
576
577#[cfg(not(feature = "optimism"))]
578impl From<alloy_rpc_types_eth::Transaction<FoundryTxEnvelope>> for FoundryTransactionRequest {
579    fn from(tx: alloy_rpc_types_eth::Transaction<FoundryTxEnvelope>) -> Self {
580        tx.inner.into_inner().into()
581    }
582}
583
584// TransactionBuilder trait implementation for FoundryNetwork
585impl TransactionBuilder for FoundryTransactionRequest {
586    fn chain_id(&self) -> Option<ChainId> {
587        self.as_ref().chain_id
588    }
589
590    fn set_chain_id(&mut self, chain_id: ChainId) {
591        self.as_mut().chain_id = Some(chain_id);
592    }
593
594    fn nonce(&self) -> Option<u64> {
595        self.as_ref().nonce
596    }
597
598    fn set_nonce(&mut self, nonce: u64) {
599        self.as_mut().nonce = Some(nonce);
600    }
601
602    fn take_nonce(&mut self) -> Option<u64> {
603        self.as_mut().nonce.take()
604    }
605
606    fn input(&self) -> Option<&alloy_primitives::Bytes> {
607        self.as_ref().input.input()
608    }
609
610    fn set_input<T: Into<alloy_primitives::Bytes>>(&mut self, input: T) {
611        self.as_mut().input.input = Some(input.into());
612    }
613
614    fn set_input_kind<T: Into<alloy_primitives::Bytes>>(
615        &mut self,
616        input: T,
617        kind: TransactionInputKind,
618    ) {
619        let inner = self.as_mut();
620        match kind {
621            TransactionInputKind::Input => inner.input.input = Some(input.into()),
622            TransactionInputKind::Data => inner.input.data = Some(input.into()),
623            TransactionInputKind::Both => {
624                let bytes = input.into();
625                inner.input.input = Some(bytes.clone());
626                inner.input.data = Some(bytes);
627            }
628        }
629    }
630
631    fn from(&self) -> Option<Address> {
632        self.as_ref().from
633    }
634
635    fn set_from(&mut self, from: Address) {
636        self.as_mut().from = Some(from);
637    }
638
639    fn kind(&self) -> Option<TxKind> {
640        self.as_ref().to
641    }
642
643    fn clear_kind(&mut self) {
644        self.as_mut().to = None;
645    }
646
647    fn set_kind(&mut self, kind: TxKind) {
648        self.as_mut().to = Some(kind);
649    }
650
651    fn value(&self) -> Option<U256> {
652        self.as_ref().value
653    }
654
655    fn set_value(&mut self, value: U256) {
656        self.as_mut().value = Some(value);
657    }
658
659    fn gas_price(&self) -> Option<u128> {
660        self.as_ref().gas_price
661    }
662
663    fn set_gas_price(&mut self, gas_price: u128) {
664        self.as_mut().gas_price = Some(gas_price);
665    }
666
667    fn max_fee_per_gas(&self) -> Option<u128> {
668        self.as_ref().max_fee_per_gas
669    }
670
671    fn set_max_fee_per_gas(&mut self, max_fee_per_gas: u128) {
672        self.as_mut().max_fee_per_gas = Some(max_fee_per_gas);
673    }
674
675    fn max_priority_fee_per_gas(&self) -> Option<u128> {
676        self.as_ref().max_priority_fee_per_gas
677    }
678
679    fn set_max_priority_fee_per_gas(&mut self, max_priority_fee_per_gas: u128) {
680        self.as_mut().max_priority_fee_per_gas = Some(max_priority_fee_per_gas);
681    }
682
683    fn gas_limit(&self) -> Option<u64> {
684        self.as_ref().gas
685    }
686
687    fn set_gas_limit(&mut self, gas_limit: u64) {
688        self.as_mut().gas = Some(gas_limit);
689    }
690
691    fn access_list(&self) -> Option<&AccessList> {
692        self.as_ref().access_list.as_ref()
693    }
694
695    fn set_access_list(&mut self, access_list: AccessList) {
696        self.as_mut().access_list = Some(access_list);
697    }
698}
699
700impl NetworkTransactionBuilder<FoundryNetwork> for FoundryTransactionRequest {
701    fn complete_type(&self, ty: FoundryTxType) -> Result<(), Vec<&'static str>> {
702        self.check_type(ty)
703    }
704
705    fn can_submit(&self) -> bool {
706        self.from().is_some()
707    }
708
709    fn can_build(&self) -> bool {
710        #[cfg(feature = "base")]
711        if self.is_base() {
712            return false;
713        }
714        if let Self::Celo(_) = self {
715            return self.check_type(FoundryTxType::Celo).is_ok();
716        }
717        if self.as_ref().can_build() || self.complete_tempo().is_ok() {
718            return true;
719        }
720        #[cfg(any(feature = "base", feature = "optimism"))]
721        if self.complete_deposit().is_ok() {
722            return true;
723        }
724        false
725    }
726
727    fn output_tx_type(&self) -> FoundryTxType {
728        self.preferred_type()
729    }
730
731    fn output_tx_type_checked(&self) -> Option<FoundryTxType> {
732        let pref = self.preferred_type();
733        self.check_type(pref).ok()?;
734        Some(pref)
735    }
736
737    /// Prepares [`FoundryTransactionRequest`] by trimming conflicting fields, and filling with
738    /// default values the mandatory fields.
739    fn prep_for_submission(&mut self) {
740        #[cfg(feature = "base")]
741        if self.is_base() {
742            return;
743        }
744        let preferred_type = self.preferred_type();
745        let inner = self.as_mut();
746        inner.transaction_type = Some(preferred_type as u8);
747        inner.gas.is_none().then(|| inner.set_gas_limit(Default::default()));
748        let is_deposit = {
749            #[cfg(any(feature = "base", feature = "optimism"))]
750            {
751                preferred_type.is_deposit()
752            }
753            #[cfg(not(any(feature = "base", feature = "optimism")))]
754            {
755                false
756            }
757        };
758        if !is_deposit && !preferred_type.is_tempo() && !preferred_type.is_celo() {
759            inner.trim_conflicting_keys();
760            inner.populate_blob_hashes();
761        }
762        if !is_deposit {
763            inner.nonce.is_none().then(|| inner.set_nonce(Default::default()));
764        }
765        if preferred_type.is_legacy() || preferred_type.is_eip2930() {
766            inner.gas_price.is_none().then(|| inner.set_gas_price(Default::default()));
767        }
768        if preferred_type.is_eip2930() {
769            inner.access_list.is_none().then(|| inner.set_access_list(Default::default()));
770        }
771        if preferred_type.is_eip1559()
772            || preferred_type.is_eip4844()
773            || preferred_type.is_eip7702()
774            || preferred_type.is_tempo()
775            || preferred_type.is_celo()
776        {
777            inner
778                .max_priority_fee_per_gas
779                .is_none()
780                .then(|| inner.set_max_priority_fee_per_gas(Default::default()));
781            inner.max_fee_per_gas.is_none().then(|| inner.set_max_fee_per_gas(Default::default()));
782        }
783        if preferred_type.is_eip4844() {
784            inner
785                .as_ref()
786                .max_fee_per_blob_gas()
787                .is_none()
788                .then(|| inner.as_mut().set_max_fee_per_blob_gas(Default::default()));
789        }
790    }
791
792    fn build_unsigned(self) -> BuildResult<FoundryTypedTx, FoundryNetwork> {
793        if let Err((tx_type, missing)) = self.missing_keys() {
794            return Err(TransactionBuilderError::InvalidTransactionRequest(tx_type, missing)
795                .into_unbuilt(self));
796        }
797        Ok(self.build_typed_tx().expect("checked by missing_keys"))
798    }
799
800    async fn build<W: NetworkWallet<FoundryNetwork>>(
801        self,
802        wallet: &W,
803    ) -> Result<FoundryTxEnvelope, TransactionBuilderError<FoundryNetwork>> {
804        Ok(wallet.sign_request(self).await?)
805    }
806}
807
808impl TransactionBuilder4844 for FoundryTransactionRequest {
809    fn max_fee_per_blob_gas(&self) -> Option<u128> {
810        self.as_ref().max_fee_per_blob_gas()
811    }
812
813    fn set_max_fee_per_blob_gas(&mut self, max_fee_per_blob_gas: u128) {
814        self.as_mut().set_max_fee_per_blob_gas(max_fee_per_blob_gas);
815    }
816
817    fn blob_sidecar(&self) -> Option<&BlobTransactionSidecarVariant> {
818        self.as_ref().blob_sidecar()
819    }
820
821    fn set_blob_sidecar(&mut self, sidecar: BlobTransactionSidecarVariant) {
822        self.as_mut().set_blob_sidecar(sidecar);
823    }
824}
825
826#[cfg(test)]
827mod tests {
828    use super::*;
829    use alloy_primitives::{B256, Bytes, Signature};
830    use tempo_primitives::{
831        TempoSignature, TempoTransaction,
832        transaction::{Authorization, KeyAuthorization, PrimitiveSignature},
833    };
834
835    fn default_tx_req() -> TransactionRequest {
836        TransactionRequest::default()
837            .with_to(Address::random())
838            .with_nonce(1)
839            .with_value(U256::from(1000000))
840            .with_gas_limit(1000000)
841            .with_max_fee_per_gas(1000000)
842            .with_max_priority_fee_per_gas(1000000)
843    }
844
845    #[test]
846    fn request_predicates() {
847        let ethereum = FoundryTransactionRequest::default();
848        assert!(ethereum.is_ethereum());
849        assert!(!ethereum.is_tempo());
850
851        let tempo = FoundryTransactionRequest::Tempo(Box::default());
852        assert!(tempo.is_tempo());
853        assert!(!tempo.is_ethereum());
854
855        #[cfg(any(feature = "base", feature = "optimism"))]
856        {
857            let op = FoundryTransactionRequest::Op(WithOtherFields::default());
858            assert!(op.is_op());
859            assert!(!op.is_ethereum());
860            assert!(!op.is_tempo());
861        }
862    }
863
864    #[test]
865    fn test_routing_ethereum_default() {
866        let tx = default_tx_req();
867        let req: FoundryTransactionRequest = WithOtherFields::new(tx).try_into().unwrap();
868
869        assert!(req.is_ethereum());
870        assert!(matches!(req.build_unsigned(), Ok(FoundryTypedTx::Eip1559(_))));
871    }
872
873    #[test]
874    fn test_routing_tempo_by_fee_token() {
875        let tx = default_tx_req();
876        let mut other = OtherFields::default();
877        other.insert("feeToken".to_string(), serde_json::to_value(Address::random()).unwrap());
878
879        let req: FoundryTransactionRequest =
880            FoundryTransactionRequest::new(WithOtherFields { inner: tx, other }).unwrap();
881
882        assert!(req.is_tempo());
883        assert!(matches!(req.build_unsigned(), Ok(FoundryTypedTx::Tempo(_))));
884    }
885
886    #[cfg(feature = "base")]
887    #[test]
888    fn base_and_tempo_request_routing() {
889        let call = serde_json::json!({ "to": Address::ZERO, "data": "0x", "value": "0x0" });
890        for (value, expected_type) in [
891            (serde_json::json!({"calls": [call]}), FoundryTxType::Tempo),
892            (serde_json::json!({"nonceKey": "0x1"}), FoundryTxType::Tempo),
893            (serde_json::json!({"validBefore": "0x123"}), FoundryTxType::Tempo),
894            (serde_json::json!({"calls": []}), FoundryTxType::Eip1559),
895            (serde_json::json!({"calls": [[call]], "validBefore": 123}), FoundryTxType::Eip8130),
896            (serde_json::json!({"type": "0x79"}), FoundryTxType::Eip8130),
897            (serde_json::json!({"type": "0x79", "nonceKey": "0x1"}), FoundryTxType::Eip8130),
898            (serde_json::json!({"type": "0x76", "calls": [call]}), FoundryTxType::Tempo),
899            (
900                serde_json::json!({"sender": Address::ZERO, "feeToken": null}),
901                FoundryTxType::Eip8130,
902            ),
903        ] {
904            let request: FoundryTransactionRequest = serde_json::from_value(value.clone())
905                .unwrap_or_else(|err| panic!("{value}: {err}"));
906            assert_eq!(request.preferred_type(), expected_type, "{value}");
907            if expected_type.is_eip8130() {
908                assert!(request.is_base(), "{value}");
909                assert!(!request.can_build(), "{value}");
910            }
911            let roundtrip: FoundryTransactionRequest =
912                serde_json::from_value(serde_json::to_value(&request).unwrap()).unwrap();
913            assert_eq!(request, roundtrip);
914        }
915        for value in [
916            serde_json::json!({"type": "0x76", "calls": [[call]]}),
917            serde_json::json!({"type": "0x79", "feeToken": Address::ZERO}),
918            serde_json::json!({"type": "0x2", "sender": Address::ZERO}),
919            serde_json::json!({"type": "0x79", "calls": [call]}),
920        ] {
921            assert!(
922                serde_json::from_value::<FoundryTransactionRequest>(value.clone()).is_err(),
923                "{value}"
924            );
925        }
926    }
927
928    #[test]
929    fn test_routing_serialized_non_aa_tempo_request_to_ethereum() {
930        let request = TempoTransactionRequest { inner: default_tx_req(), ..Default::default() };
931        let request = serde_json::from_value::<WithOtherFields<TransactionRequest>>(
932            serde_json::to_value(request).unwrap(),
933        )
934        .unwrap();
935
936        let request = FoundryTransactionRequest::try_from(request).unwrap();
937
938        assert!(request.is_ethereum());
939        assert!(matches!(request.build_unsigned(), Ok(FoundryTypedTx::Eip1559(_))));
940    }
941
942    #[test]
943    #[cfg(any(feature = "base", feature = "optimism"))]
944    fn test_routing_op_by_deposit_fields() {
945        let tx = default_tx_req();
946        let mut other = OtherFields::default();
947        other.insert("sourceHash".to_string(), serde_json::to_value(B256::ZERO).unwrap());
948        other.insert("mint".to_string(), serde_json::to_value(U256::from(1000)).unwrap());
949        other.insert("isSystemTx".to_string(), serde_json::to_value(false).unwrap());
950
951        let req: FoundryTransactionRequest =
952            FoundryTransactionRequest::new(WithOtherFields { inner: tx, other }).unwrap();
953
954        assert!(req.is_op());
955        assert!(matches!(req.build_unsigned(), Ok(FoundryTypedTx::Deposit(_))));
956    }
957
958    #[test]
959    fn test_op_incomplete_routes_to_ethereum() {
960        let tx = default_tx_req();
961        let mut other = OtherFields::default();
962        // Only provide 2 of 3 required Op fields
963        other.insert("sourceHash".to_string(), serde_json::to_value(B256::ZERO).unwrap());
964        other.insert("mint".to_string(), serde_json::to_value(U256::from(1000)).unwrap());
965
966        let req: FoundryTransactionRequest =
967            FoundryTransactionRequest::new(WithOtherFields { inner: tx, other }).unwrap();
968
969        assert!(req.is_ethereum());
970        assert!(matches!(req.build_unsigned(), Ok(FoundryTypedTx::Eip1559(_))));
971    }
972
973    #[test]
974    fn test_ethereum_with_unrelated_other_fields() {
975        let tx = default_tx_req();
976        let mut other = OtherFields::default();
977        other.insert("anotherField".to_string(), serde_json::to_value(123).unwrap());
978
979        let req: FoundryTransactionRequest =
980            FoundryTransactionRequest::new(WithOtherFields { inner: tx, other }).unwrap();
981
982        assert!(req.is_ethereum());
983        assert!(matches!(req.build_unsigned(), Ok(FoundryTypedTx::Eip1559(_))));
984    }
985
986    #[test]
987    fn test_serialization_ethereum() {
988        let tx = default_tx_req();
989        let original: FoundryTransactionRequest = WithOtherFields::new(tx).try_into().unwrap();
990
991        let serialized = serde_json::to_string(&original).unwrap();
992        let deserialized: FoundryTransactionRequest = serde_json::from_str(&serialized).unwrap();
993
994        assert!(deserialized.is_ethereum());
995    }
996
997    #[test]
998    #[cfg(any(feature = "base", feature = "optimism"))]
999    fn test_serialization_op() {
1000        let tx = default_tx_req();
1001        let mut other = OtherFields::default();
1002        other.insert("sourceHash".to_string(), serde_json::to_value(B256::ZERO).unwrap());
1003        other.insert("mint".to_string(), serde_json::to_value(U256::from(1000)).unwrap());
1004        other.insert("isSystemTx".to_string(), serde_json::to_value(false).unwrap());
1005
1006        let original: FoundryTransactionRequest =
1007            FoundryTransactionRequest::new(WithOtherFields { inner: tx, other }).unwrap();
1008
1009        let serialized = serde_json::to_string(&original).unwrap();
1010        let deserialized: FoundryTransactionRequest = serde_json::from_str(&serialized).unwrap();
1011
1012        assert!(deserialized.is_op());
1013    }
1014
1015    #[test]
1016    fn test_serialization_tempo() {
1017        let tx = default_tx_req();
1018        let mut other = OtherFields::default();
1019        other.insert("feeToken".to_string(), serde_json::to_value(Address::ZERO).unwrap());
1020        other.insert("nonceKey".to_string(), serde_json::to_value(U256::from(42)).unwrap());
1021
1022        let original: FoundryTransactionRequest =
1023            FoundryTransactionRequest::new(WithOtherFields { inner: tx, other }).unwrap();
1024
1025        let serialized = serde_json::to_string(&original).unwrap();
1026        let deserialized: FoundryTransactionRequest = serde_json::from_str(&serialized).unwrap();
1027
1028        assert!(deserialized.is_tempo());
1029    }
1030
1031    #[test]
1032    fn test_tempo_request_decodes_all_extension_fields() {
1033        let signature = Signature::test_signature();
1034        let expected = TempoTransactionRequest {
1035            inner: TransactionRequest {
1036                transaction_type: Some(TEMPO_TX_TYPE_ID),
1037                ..default_tx_req()
1038            },
1039            fee_token: Some(Address::repeat_byte(0x11)),
1040            nonce_key: Some(U256::from(42)),
1041            calls: vec![Call {
1042                to: TxKind::Call(Address::repeat_byte(0x22)),
1043                value: U256::from(7),
1044                input: Bytes::from_static(&[0xde, 0xad]),
1045            }],
1046            key_type: Some(SignatureType::WebAuthn),
1047            key_data: Some(Bytes::from_static(&[0xbe, 0xef])),
1048            key_id: Some(Address::repeat_byte(0x33)),
1049            tempo_authorization_list: vec![TempoSignedAuthorization::new_unchecked(
1050                Authorization {
1051                    chain_id: U256::from(4217),
1052                    address: Address::repeat_byte(0x44),
1053                    nonce: 3,
1054                },
1055                TempoSignature::default(),
1056            )],
1057            key_authorization: Some(
1058                KeyAuthorization::unrestricted(
1059                    4217,
1060                    SignatureType::Secp256k1,
1061                    Address::repeat_byte(0x55),
1062                )
1063                .into_signed(PrimitiveSignature::Secp256k1(signature)),
1064            ),
1065            valid_before: NonZeroU64::new(100),
1066            valid_after: NonZeroU64::new(10),
1067            fee_payer_signature: Some(signature),
1068            configurable_account_simulation: None,
1069            key_authorization_simulation: None,
1070        };
1071        let request = serde_json::from_value::<WithOtherFields<TransactionRequest>>(
1072            serde_json::to_value(&expected).unwrap(),
1073        )
1074        .unwrap();
1075
1076        let decoded = FoundryTransactionRequest::try_from(request).unwrap();
1077
1078        let FoundryTransactionRequest::Tempo(decoded) = decoded else { panic!() };
1079        assert_eq!(*decoded, expected);
1080    }
1081
1082    #[test]
1083    fn test_malformed_tempo_field_is_rejected() {
1084        let mut other = OtherFields::default();
1085        other.insert("nonceKey".to_string(), serde_json::json!("not a quantity"));
1086
1087        let result =
1088            FoundryTransactionRequest::new(WithOtherFields { inner: default_tx_req(), other });
1089
1090        assert!(result.is_err());
1091    }
1092
1093    #[test]
1094    fn test_tempo_validity_uses_rpc_quantities() {
1095        let request = serde_json::from_value::<FoundryTransactionRequest>(serde_json::json!({
1096            "type": "0x76",
1097            "validBefore": "0x64",
1098            "validAfter": "0xa",
1099        }))
1100        .unwrap();
1101
1102        let FoundryTransactionRequest::Tempo(request) = request else { panic!() };
1103        assert_eq!(request.valid_before, NonZeroU64::new(100));
1104        assert_eq!(request.valid_after, NonZeroU64::new(10));
1105    }
1106
1107    #[test]
1108    fn test_tempo_typed_request_roundtrip_preserves_fields() {
1109        let tx = TempoTransaction {
1110            chain_id: 4217,
1111            nonce: 7,
1112            fee_payer_signature: None,
1113            valid_before: NonZeroU64::new(100),
1114            valid_after: NonZeroU64::new(10),
1115            gas_limit: 100_000,
1116            max_fee_per_gas: 20,
1117            max_priority_fee_per_gas: 2,
1118            fee_token: Some(Address::random()),
1119            access_list: Default::default(),
1120            calls: vec![Call {
1121                to: TxKind::Call(Address::random()),
1122                value: U256::from(42),
1123                input: vec![1, 2, 3].into(),
1124            }],
1125            tempo_authorization_list: Vec::new(),
1126            nonce_key: U256::from(9),
1127            key_authorization: None,
1128        };
1129
1130        let request: FoundryTransactionRequest = FoundryTypedTx::Tempo(tx.clone()).into();
1131        let rebuilt = request.build_unsigned().unwrap();
1132
1133        assert_eq!(rebuilt, FoundryTypedTx::Tempo(tx));
1134    }
1135
1136    #[test]
1137    #[cfg(any(feature = "base", feature = "optimism"))]
1138    fn test_deposit_typed_tx_roundtrip() {
1139        let deposit_tx = TxDeposit {
1140            from: Address::random(),
1141            source_hash: B256::random(),
1142            to: TxKind::Call(Address::random()),
1143            mint: 1000u128,
1144            value: U256::from(500),
1145            gas_limit: 21000,
1146            is_system_transaction: true,
1147            input: Default::default(),
1148        };
1149
1150        let req: FoundryTransactionRequest = FoundryTypedTx::Deposit(deposit_tx.clone()).into();
1151
1152        assert!(req.is_op());
1153
1154        let parts = req.get_deposit_tx_parts().expect("should parse deposit parts");
1155        assert_eq!(parts.source_hash, deposit_tx.source_hash);
1156        assert_eq!(parts.mint, Some(deposit_tx.mint));
1157        assert_eq!(parts.is_system_transaction, deposit_tx.is_system_transaction);
1158    }
1159}