op_revm/transaction/
abstraction.rs

1//! Optimism transaction abstraction containing the `[OpTxTr]` trait and corresponding `[OpTransaction]` type.
2use super::deposit::{DepositTransactionParts, DEPOSIT_TRANSACTION_TYPE};
3use auto_impl::auto_impl;
4use revm::{
5    context::{
6        tx::{TxEnvBuildError, TxEnvBuilder},
7        TxEnv,
8    },
9    context_interface::transaction::Transaction,
10    handler::SystemCallTx,
11    primitives::{Address, Bytes, TxKind, B256, U256},
12};
13use std::vec;
14
15/// Optimism Transaction trait.
16#[auto_impl(&, &mut, Box, Arc)]
17pub trait OpTxTr: Transaction {
18    /// Enveloped transaction bytes.
19    fn enveloped_tx(&self) -> Option<&Bytes>;
20
21    /// Source hash of the deposit transaction.
22    fn source_hash(&self) -> Option<B256>;
23
24    /// Mint of the deposit transaction
25    fn mint(&self) -> Option<u128>;
26
27    /// Whether the transaction is a system transaction
28    fn is_system_transaction(&self) -> bool;
29
30    /// Returns `true` if transaction is of type [`DEPOSIT_TRANSACTION_TYPE`].
31    fn is_deposit(&self) -> bool {
32        self.tx_type() == DEPOSIT_TRANSACTION_TYPE
33    }
34}
35
36/// Optimism transaction.
37#[derive(Clone, Debug, PartialEq, Eq)]
38#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
39pub struct OpTransaction<T: Transaction> {
40    /// Base transaction fields.
41    pub base: T,
42    /// An enveloped EIP-2718 typed transaction
43    ///
44    /// This is used to compute the L1 tx cost using the L1 block info, as
45    /// opposed to requiring downstream apps to compute the cost
46    /// externally.
47    pub enveloped_tx: Option<Bytes>,
48    /// Deposit transaction parts.
49    pub deposit: DepositTransactionParts,
50}
51
52impl<T: Transaction> AsRef<T> for OpTransaction<T> {
53    fn as_ref(&self) -> &T {
54        &self.base
55    }
56}
57
58impl<T: Transaction> OpTransaction<T> {
59    /// Create a new Optimism transaction.
60    pub fn new(base: T) -> Self {
61        Self {
62            base,
63            enveloped_tx: None,
64            deposit: DepositTransactionParts::default(),
65        }
66    }
67}
68
69impl OpTransaction<TxEnv> {
70    /// Create a new Optimism transaction.
71    pub fn builder() -> OpTransactionBuilder {
72        OpTransactionBuilder::new()
73    }
74}
75
76impl Default for OpTransaction<TxEnv> {
77    fn default() -> Self {
78        Self {
79            base: TxEnv::default(),
80            enveloped_tx: Some(vec![0x00].into()),
81            deposit: DepositTransactionParts::default(),
82        }
83    }
84}
85
86impl<TX: Transaction + SystemCallTx> SystemCallTx for OpTransaction<TX> {
87    fn new_system_tx_with_caller(
88        caller: Address,
89        system_contract_address: Address,
90        data: Bytes,
91    ) -> Self {
92        OpTransaction::new(TX::new_system_tx_with_caller(
93            caller,
94            system_contract_address,
95            data,
96        ))
97    }
98}
99
100impl<T: Transaction> Transaction for OpTransaction<T> {
101    type AccessListItem<'a>
102        = T::AccessListItem<'a>
103    where
104        T: 'a;
105    type Authorization<'a>
106        = T::Authorization<'a>
107    where
108        T: 'a;
109
110    fn tx_type(&self) -> u8 {
111        // If this is a deposit transaction (has source_hash set), return deposit type
112        if self.deposit.source_hash != B256::ZERO {
113            DEPOSIT_TRANSACTION_TYPE
114        } else {
115            self.base.tx_type()
116        }
117    }
118
119    fn caller(&self) -> Address {
120        self.base.caller()
121    }
122
123    fn gas_limit(&self) -> u64 {
124        self.base.gas_limit()
125    }
126
127    fn value(&self) -> U256 {
128        self.base.value()
129    }
130
131    fn input(&self) -> &Bytes {
132        self.base.input()
133    }
134
135    fn nonce(&self) -> u64 {
136        self.base.nonce()
137    }
138
139    fn kind(&self) -> TxKind {
140        self.base.kind()
141    }
142
143    fn chain_id(&self) -> Option<u64> {
144        self.base.chain_id()
145    }
146
147    fn access_list(&self) -> Option<impl Iterator<Item = Self::AccessListItem<'_>>> {
148        self.base.access_list()
149    }
150
151    fn max_priority_fee_per_gas(&self) -> Option<u128> {
152        self.base.max_priority_fee_per_gas()
153    }
154
155    fn max_fee_per_gas(&self) -> u128 {
156        self.base.max_fee_per_gas()
157    }
158
159    fn gas_price(&self) -> u128 {
160        self.base.gas_price()
161    }
162
163    fn blob_versioned_hashes(&self) -> &[B256] {
164        self.base.blob_versioned_hashes()
165    }
166
167    fn max_fee_per_blob_gas(&self) -> u128 {
168        self.base.max_fee_per_blob_gas()
169    }
170
171    fn effective_gas_price(&self, base_fee: u128) -> u128 {
172        // Deposit transactions use gas_price directly
173        if self.tx_type() == DEPOSIT_TRANSACTION_TYPE {
174            return self.gas_price();
175        }
176        self.base.effective_gas_price(base_fee)
177    }
178
179    fn authorization_list_len(&self) -> usize {
180        self.base.authorization_list_len()
181    }
182
183    fn authorization_list(&self) -> impl Iterator<Item = Self::Authorization<'_>> {
184        self.base.authorization_list()
185    }
186}
187
188impl<T: Transaction> OpTxTr for OpTransaction<T> {
189    fn enveloped_tx(&self) -> Option<&Bytes> {
190        self.enveloped_tx.as_ref()
191    }
192
193    fn source_hash(&self) -> Option<B256> {
194        if self.tx_type() != DEPOSIT_TRANSACTION_TYPE {
195            return None;
196        }
197        Some(self.deposit.source_hash)
198    }
199
200    fn mint(&self) -> Option<u128> {
201        self.deposit.mint
202    }
203
204    fn is_system_transaction(&self) -> bool {
205        self.deposit.is_system_transaction
206    }
207}
208
209/// Builder for constructing [`OpTransaction`] instances
210#[derive(Default, Debug)]
211pub struct OpTransactionBuilder {
212    base: TxEnvBuilder,
213    enveloped_tx: Option<Bytes>,
214    deposit: DepositTransactionParts,
215}
216
217impl OpTransactionBuilder {
218    /// Create a new builder with default values
219    pub fn new() -> Self {
220        Self {
221            base: TxEnvBuilder::new(),
222            enveloped_tx: None,
223            deposit: DepositTransactionParts::default(),
224        }
225    }
226
227    /// Set the base transaction builder based for TxEnvBuilder.
228    pub fn base(mut self, base: TxEnvBuilder) -> Self {
229        self.base = base;
230        self
231    }
232
233    /// Set the enveloped transaction bytes.
234    pub fn enveloped_tx(mut self, enveloped_tx: Option<Bytes>) -> Self {
235        self.enveloped_tx = enveloped_tx;
236        self
237    }
238
239    /// Set the source hash of the deposit transaction.
240    pub fn source_hash(mut self, source_hash: B256) -> Self {
241        self.deposit.source_hash = source_hash;
242        self
243    }
244
245    /// Set the mint of the deposit transaction.
246    pub fn mint(mut self, mint: u128) -> Self {
247        self.deposit.mint = Some(mint);
248        self
249    }
250
251    /// Set the deposit transaction to be a system transaction.
252    pub fn is_system_transaction(mut self) -> Self {
253        self.deposit.is_system_transaction = true;
254        self
255    }
256
257    /// Set the deposit transaction to not be a system transaction.
258    pub fn not_system_transaction(mut self) -> Self {
259        self.deposit.is_system_transaction = false;
260        self
261    }
262
263    /// Set the deposit transaction to be a deposit transaction.
264    pub fn is_deposit_tx(mut self) -> Self {
265        self.base = self.base.tx_type(Some(DEPOSIT_TRANSACTION_TYPE));
266        self
267    }
268
269    /// Build the [`OpTransaction`] with default values for missing fields.
270    ///
271    /// This is useful for testing and debugging where it is not necessary to
272    /// have full [`OpTransaction`] instance.
273    ///
274    /// If the source hash is not [`B256::ZERO`], set the transaction type to deposit and remove the enveloped transaction.
275    pub fn build_fill(mut self) -> OpTransaction<TxEnv> {
276        let tx_type = self.base.get_tx_type();
277        if tx_type.is_some() {
278            if tx_type == Some(DEPOSIT_TRANSACTION_TYPE) {
279                // source hash is required for deposit transactions
280                if self.deposit.source_hash == B256::ZERO {
281                    self.deposit.source_hash = B256::from([1u8; 32]);
282                }
283            } else {
284                // enveloped is required for non-deposit transactions
285                self.enveloped_tx = Some(vec![0x00].into());
286            }
287        } else if self.deposit.source_hash != B256::ZERO {
288            // if type is not set and source hash is set, set the transaction type to deposit
289            self.base = self.base.tx_type(Some(DEPOSIT_TRANSACTION_TYPE));
290        } else if self.enveloped_tx.is_none() {
291            // if type is not set and source hash is not set, set the enveloped transaction to something.
292            self.enveloped_tx = Some(vec![0x00].into());
293        }
294
295        let base = self.base.build_fill();
296
297        OpTransaction {
298            base,
299            enveloped_tx: self.enveloped_tx,
300            deposit: self.deposit,
301        }
302    }
303
304    /// Build the [`OpTransaction`] instance, return error if the transaction is not valid.
305    ///
306    pub fn build(mut self) -> Result<OpTransaction<TxEnv>, OpBuildError> {
307        let tx_type = self.base.get_tx_type();
308        if tx_type.is_some() {
309            if Some(DEPOSIT_TRANSACTION_TYPE) == tx_type {
310                // if tx type is deposit, check if source hash is set
311                if self.deposit.source_hash == B256::ZERO {
312                    return Err(OpBuildError::MissingSourceHashForDeposit);
313                }
314            } else if self.enveloped_tx.is_none() {
315                // enveloped is required for non-deposit transactions
316                return Err(OpBuildError::MissingEnvelopedTxBytes);
317            }
318        } else if self.deposit.source_hash != B256::ZERO {
319            // if type is not set and source hash is set, set the transaction type to deposit
320            self.base = self.base.tx_type(Some(DEPOSIT_TRANSACTION_TYPE));
321        } else if self.enveloped_tx.is_none() {
322            // tx is not deposit and enveloped is required
323            return Err(OpBuildError::MissingEnvelopedTxBytes);
324        }
325
326        let base = self.base.build()?;
327
328        Ok(OpTransaction {
329            base,
330            enveloped_tx: self.enveloped_tx,
331            deposit: self.deposit,
332        })
333    }
334}
335
336/// Error type for building [`TxEnv`]
337#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
338#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
339pub enum OpBuildError {
340    /// Base transaction build error
341    Base(TxEnvBuildError),
342    /// Missing enveloped transaction bytes
343    MissingEnvelopedTxBytes,
344    /// Missing source hash for deposit transaction
345    MissingSourceHashForDeposit,
346}
347
348impl From<TxEnvBuildError> for OpBuildError {
349    fn from(error: TxEnvBuildError) -> Self {
350        OpBuildError::Base(error)
351    }
352}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357    use revm::{
358        context_interface::Transaction,
359        primitives::{Address, B256},
360    };
361
362    #[test]
363    fn test_deposit_transaction_fields() {
364        let base_tx = TxEnv::builder()
365            .gas_limit(10)
366            .gas_price(100)
367            .gas_priority_fee(Some(5));
368
369        let op_tx = OpTransaction::builder()
370            .base(base_tx)
371            .enveloped_tx(None)
372            .not_system_transaction()
373            .mint(0u128)
374            .source_hash(B256::from([1u8; 32]))
375            .build()
376            .unwrap();
377        // Verify transaction type (deposit transactions should have tx_type based on OpSpecId)
378        // The tx_type is derived from the transaction structure, not set manually
379        // Verify common fields access
380        assert_eq!(op_tx.gas_limit(), 10);
381        assert_eq!(op_tx.kind(), revm::primitives::TxKind::Call(Address::ZERO));
382        // Verify gas related calculations - deposit transactions use gas_price for effective gas price
383        assert_eq!(op_tx.effective_gas_price(90), 100);
384        assert_eq!(op_tx.max_fee_per_gas(), 100);
385    }
386}