alloy_consensus/transaction/
eip7702.rs

1use crate::{SignableTransaction, Transaction, TxType};
2use alloc::vec::Vec;
3use alloy_eips::{
4    eip2718::IsTyped2718,
5    eip2930::AccessList,
6    eip7702::{constants::EIP7702_TX_TYPE_ID, SignedAuthorization},
7    Typed2718,
8};
9use alloy_primitives::{Address, Bytes, ChainId, Signature, TxKind, B256, U256};
10use alloy_rlp::{BufMut, Decodable, Encodable};
11use core::mem;
12
13use super::{RlpEcdsaDecodableTx, RlpEcdsaEncodableTx};
14
15/// A transaction with a priority fee ([EIP-7702](https://eips.ethereum.org/EIPS/eip-7702)).
16#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
17#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
18#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
19#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
20#[doc(alias = "Eip7702Transaction", alias = "TransactionEip7702", alias = "Eip7702Tx")]
21pub struct TxEip7702 {
22    /// EIP-155: Simple replay attack protection
23    #[cfg_attr(feature = "serde", serde(with = "alloy_serde::quantity"))]
24    pub chain_id: ChainId,
25    /// A scalar value equal to the number of transactions sent by the sender; formally Tn.
26    #[cfg_attr(feature = "serde", serde(with = "alloy_serde::quantity"))]
27    pub nonce: u64,
28    /// A scalar value equal to the maximum
29    /// amount of gas that should be used in executing
30    /// this transaction. This is paid up-front, before any
31    /// computation is done and may not be increased
32    /// later; formally Tg.
33    #[cfg_attr(
34        feature = "serde",
35        serde(with = "alloy_serde::quantity", rename = "gas", alias = "gasLimit")
36    )]
37    pub gas_limit: u64,
38    /// A scalar value equal to the maximum
39    /// amount of gas that should be used in executing
40    /// this transaction. This is paid up-front, before any
41    /// computation is done and may not be increased
42    /// later; formally Tg.
43    ///
44    /// As ethereum circulation is around 120mil eth as of 2022 that is around
45    /// 120000000000000000000000000 wei we are safe to use u128 as its max number is:
46    /// 340282366920938463463374607431768211455
47    ///
48    /// This is also known as `GasFeeCap`
49    #[cfg_attr(feature = "serde", serde(with = "alloy_serde::quantity"))]
50    pub max_fee_per_gas: u128,
51    /// Max Priority fee that transaction is paying
52    ///
53    /// As ethereum circulation is around 120mil eth as of 2022 that is around
54    /// 120000000000000000000000000 wei we are safe to use u128 as its max number is:
55    /// 340282366920938463463374607431768211455
56    ///
57    /// This is also known as `GasTipCap`
58    #[cfg_attr(feature = "serde", serde(with = "alloy_serde::quantity"))]
59    pub max_priority_fee_per_gas: u128,
60    /// The 160-bit address of the message call’s recipient.
61    pub to: Address,
62    /// A scalar value equal to the number of Wei to
63    /// be transferred to the message call’s recipient or,
64    /// in the case of contract creation, as an endowment
65    /// to the newly created account; formally Tv.
66    pub value: U256,
67    /// The accessList specifies a list of addresses and storage keys;
68    /// these addresses and storage keys are added into the `accessed_addresses`
69    /// and `accessed_storage_keys` global sets (introduced in EIP-2929).
70    /// A gas cost is charged, though at a discount relative to the cost of
71    /// accessing outside the list.
72    pub access_list: AccessList,
73    /// Authorizations are used to temporarily set the code of its signer to
74    /// the code referenced by `address`. These also include a `chain_id` (which
75    /// can be set to zero and not evaluated) as well as an optional `nonce`.
76    pub authorization_list: Vec<SignedAuthorization>,
77    /// An unlimited size byte array specifying the
78    /// input data of the message call, formally Td.
79    pub input: Bytes,
80}
81
82impl TxEip7702 {
83    /// Get the transaction type.
84    #[doc(alias = "transaction_type")]
85    pub const fn tx_type() -> TxType {
86        TxType::Eip7702
87    }
88
89    /// Calculates a heuristic for the in-memory size of the [TxEip7702] transaction.
90    #[inline]
91    pub fn size(&self) -> usize {
92        mem::size_of::<ChainId>() + // chain_id
93        mem::size_of::<u64>() + // nonce
94        mem::size_of::<u64>() + // gas_limit
95        mem::size_of::<u128>() + // max_fee_per_gas
96        mem::size_of::<u128>() + // max_priority_fee_per_gas
97        mem::size_of::<Address>() + // to
98        mem::size_of::<U256>() + // value
99        self.access_list.size() + // access_list
100        self.input.len() + // input
101        self.authorization_list.capacity() * mem::size_of::<SignedAuthorization>()
102        // authorization_list
103    }
104}
105
106impl RlpEcdsaEncodableTx for TxEip7702 {
107    /// Outputs the length of the transaction's fields, without a RLP header.
108    #[doc(hidden)]
109    fn rlp_encoded_fields_length(&self) -> usize {
110        self.chain_id.length()
111            + self.nonce.length()
112            + self.max_priority_fee_per_gas.length()
113            + self.max_fee_per_gas.length()
114            + self.gas_limit.length()
115            + self.to.length()
116            + self.value.length()
117            + self.input.0.length()
118            + self.access_list.length()
119            + self.authorization_list.length()
120    }
121
122    fn rlp_encode_fields(&self, out: &mut dyn alloy_rlp::BufMut) {
123        self.chain_id.encode(out);
124        self.nonce.encode(out);
125        self.max_priority_fee_per_gas.encode(out);
126        self.max_fee_per_gas.encode(out);
127        self.gas_limit.encode(out);
128        self.to.encode(out);
129        self.value.encode(out);
130        self.input.0.encode(out);
131        self.access_list.encode(out);
132        self.authorization_list.encode(out);
133    }
134}
135
136impl RlpEcdsaDecodableTx for TxEip7702 {
137    const DEFAULT_TX_TYPE: u8 = { Self::tx_type() as u8 };
138
139    fn rlp_decode_fields(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
140        Ok(Self {
141            chain_id: Decodable::decode(buf)?,
142            nonce: Decodable::decode(buf)?,
143            max_priority_fee_per_gas: Decodable::decode(buf)?,
144            max_fee_per_gas: Decodable::decode(buf)?,
145            gas_limit: Decodable::decode(buf)?,
146            to: Decodable::decode(buf)?,
147            value: Decodable::decode(buf)?,
148            input: Decodable::decode(buf)?,
149            access_list: Decodable::decode(buf)?,
150            authorization_list: Decodable::decode(buf)?,
151        })
152    }
153}
154
155impl Transaction for TxEip7702 {
156    #[inline]
157    fn chain_id(&self) -> Option<ChainId> {
158        Some(self.chain_id)
159    }
160
161    #[inline]
162    fn nonce(&self) -> u64 {
163        self.nonce
164    }
165
166    #[inline]
167    fn gas_limit(&self) -> u64 {
168        self.gas_limit
169    }
170
171    #[inline]
172    fn gas_price(&self) -> Option<u128> {
173        None
174    }
175
176    #[inline]
177    fn max_fee_per_gas(&self) -> u128 {
178        self.max_fee_per_gas
179    }
180
181    #[inline]
182    fn max_priority_fee_per_gas(&self) -> Option<u128> {
183        Some(self.max_priority_fee_per_gas)
184    }
185
186    #[inline]
187    fn max_fee_per_blob_gas(&self) -> Option<u128> {
188        None
189    }
190
191    #[inline]
192    fn priority_fee_or_price(&self) -> u128 {
193        self.max_priority_fee_per_gas
194    }
195
196    fn effective_gas_price(&self, base_fee: Option<u64>) -> u128 {
197        alloy_eips::eip1559::calc_effective_gas_price(
198            self.max_fee_per_gas,
199            self.max_priority_fee_per_gas,
200            base_fee,
201        )
202    }
203
204    #[inline]
205    fn is_dynamic_fee(&self) -> bool {
206        true
207    }
208
209    #[inline]
210    fn kind(&self) -> TxKind {
211        self.to.into()
212    }
213
214    #[inline]
215    fn is_create(&self) -> bool {
216        false
217    }
218
219    #[inline]
220    fn value(&self) -> U256 {
221        self.value
222    }
223
224    #[inline]
225    fn input(&self) -> &Bytes {
226        &self.input
227    }
228
229    #[inline]
230    fn access_list(&self) -> Option<&AccessList> {
231        Some(&self.access_list)
232    }
233
234    #[inline]
235    fn blob_versioned_hashes(&self) -> Option<&[B256]> {
236        None
237    }
238
239    #[inline]
240    fn authorization_list(&self) -> Option<&[SignedAuthorization]> {
241        Some(&self.authorization_list)
242    }
243}
244
245impl SignableTransaction<Signature> for TxEip7702 {
246    fn set_chain_id(&mut self, chain_id: ChainId) {
247        self.chain_id = chain_id;
248    }
249
250    fn encode_for_signing(&self, out: &mut dyn alloy_rlp::BufMut) {
251        out.put_u8(EIP7702_TX_TYPE_ID);
252        self.encode(out)
253    }
254
255    fn payload_len_for_signature(&self) -> usize {
256        self.length() + 1
257    }
258}
259
260impl Typed2718 for TxEip7702 {
261    fn ty(&self) -> u8 {
262        TxType::Eip7702 as u8
263    }
264}
265
266impl IsTyped2718 for TxEip7702 {
267    fn is_type(type_id: u8) -> bool {
268        matches!(type_id, 0x04)
269    }
270}
271
272impl Encodable for TxEip7702 {
273    fn encode(&self, out: &mut dyn BufMut) {
274        self.rlp_encode(out);
275    }
276
277    fn length(&self) -> usize {
278        self.rlp_encoded_length()
279    }
280}
281
282impl Decodable for TxEip7702 {
283    fn decode(data: &mut &[u8]) -> alloy_rlp::Result<Self> {
284        Self::rlp_decode(data)
285    }
286}
287
288/// Bincode-compatible [`TxEip7702`] serde implementation.
289#[cfg(all(feature = "serde", feature = "serde-bincode-compat"))]
290pub(super) mod serde_bincode_compat {
291    use alloc::{borrow::Cow, vec::Vec};
292    use alloy_eips::{eip2930::AccessList, eip7702::serde_bincode_compat::SignedAuthorization};
293    use alloy_primitives::{Address, Bytes, ChainId, U256};
294    use serde::{Deserialize, Deserializer, Serialize, Serializer};
295    use serde_with::{DeserializeAs, SerializeAs};
296
297    /// Bincode-compatible [`super::TxEip7702`] serde implementation.
298    ///
299    /// Intended to use with the [`serde_with::serde_as`] macro in the following way:
300    /// ```rust
301    /// use alloy_consensus::{serde_bincode_compat, TxEip7702};
302    /// use serde::{Deserialize, Serialize};
303    /// use serde_with::serde_as;
304    ///
305    /// #[serde_as]
306    /// #[derive(Serialize, Deserialize)]
307    /// struct Data {
308    ///     #[serde_as(as = "serde_bincode_compat::transaction::TxEip7702")]
309    ///     transaction: TxEip7702,
310    /// }
311    /// ```
312    #[derive(Debug, Serialize, Deserialize)]
313    pub struct TxEip7702<'a> {
314        chain_id: ChainId,
315        nonce: u64,
316        gas_limit: u64,
317        max_fee_per_gas: u128,
318        max_priority_fee_per_gas: u128,
319        to: Address,
320        value: U256,
321        access_list: Cow<'a, AccessList>,
322        authorization_list: Vec<SignedAuthorization<'a>>,
323        input: Cow<'a, Bytes>,
324    }
325
326    impl<'a> From<&'a super::TxEip7702> for TxEip7702<'a> {
327        fn from(value: &'a super::TxEip7702) -> Self {
328            Self {
329                chain_id: value.chain_id,
330                nonce: value.nonce,
331                gas_limit: value.gas_limit,
332                max_fee_per_gas: value.max_fee_per_gas,
333                max_priority_fee_per_gas: value.max_priority_fee_per_gas,
334                to: value.to,
335                value: value.value,
336                access_list: Cow::Borrowed(&value.access_list),
337                authorization_list: value.authorization_list.iter().map(Into::into).collect(),
338                input: Cow::Borrowed(&value.input),
339            }
340        }
341    }
342
343    impl<'a> From<TxEip7702<'a>> for super::TxEip7702 {
344        fn from(value: TxEip7702<'a>) -> Self {
345            Self {
346                chain_id: value.chain_id,
347                nonce: value.nonce,
348                gas_limit: value.gas_limit,
349                max_fee_per_gas: value.max_fee_per_gas,
350                max_priority_fee_per_gas: value.max_priority_fee_per_gas,
351                to: value.to,
352                value: value.value,
353                access_list: value.access_list.into_owned(),
354                authorization_list: value.authorization_list.into_iter().map(Into::into).collect(),
355                input: value.input.into_owned(),
356            }
357        }
358    }
359
360    impl SerializeAs<super::TxEip7702> for TxEip7702<'_> {
361        fn serialize_as<S>(source: &super::TxEip7702, serializer: S) -> Result<S::Ok, S::Error>
362        where
363            S: Serializer,
364        {
365            TxEip7702::from(source).serialize(serializer)
366        }
367    }
368
369    impl<'de> DeserializeAs<'de, super::TxEip7702> for TxEip7702<'de> {
370        fn deserialize_as<D>(deserializer: D) -> Result<super::TxEip7702, D::Error>
371        where
372            D: Deserializer<'de>,
373        {
374            TxEip7702::deserialize(deserializer).map(Into::into)
375        }
376    }
377
378    #[cfg(test)]
379    mod tests {
380        use arbitrary::Arbitrary;
381        use bincode::config;
382        use rand::Rng;
383        use serde::{Deserialize, Serialize};
384        use serde_with::serde_as;
385
386        use super::super::{serde_bincode_compat, TxEip7702};
387
388        #[test]
389        fn test_tx_eip7702_bincode_roundtrip() {
390            #[serde_as]
391            #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
392            struct Data {
393                #[serde_as(as = "serde_bincode_compat::TxEip7702")]
394                transaction: TxEip7702,
395            }
396
397            let mut bytes = [0u8; 1024];
398            rand::thread_rng().fill(bytes.as_mut_slice());
399            let data = Data {
400                transaction: TxEip7702::arbitrary(&mut arbitrary::Unstructured::new(&bytes))
401                    .unwrap(),
402            };
403
404            let encoded = bincode::serde::encode_to_vec(&data, config::legacy()).unwrap();
405            let (decoded, _) =
406                bincode::serde::decode_from_slice::<Data, _>(&encoded, config::legacy()).unwrap();
407            assert_eq!(decoded, data);
408        }
409    }
410}
411
412#[cfg(all(test, feature = "k256"))]
413mod tests {
414    use super::*;
415    use crate::SignableTransaction;
416    use alloy_eips::eip2930::AccessList;
417    use alloy_primitives::{address, b256, hex, Address, Signature, U256};
418
419    #[test]
420    fn encode_decode_eip7702() {
421        let tx =  TxEip7702 {
422            chain_id: 1,
423            nonce: 0x42,
424            gas_limit: 44386,
425            to: address!("6069a6c32cf691f5982febae4faf8a6f3ab2f0f6"),
426            value: U256::from(0_u64),
427            input:  hex!("a22cb4650000000000000000000000005eee75727d804a2b13038928d36f8b188945a57a0000000000000000000000000000000000000000000000000000000000000000").into(),
428            max_fee_per_gas: 0x4a817c800,
429            max_priority_fee_per_gas: 0x3b9aca00,
430            access_list: AccessList::default(),
431            authorization_list: vec![],
432        };
433
434        let sig = Signature::from_scalars_and_parity(
435            b256!("840cfc572845f5786e702984c2a582528cad4b49b2a10b9db1be7fca90058565"),
436            b256!("25e7109ceb98168d95b09b18bbf6b685130e0562f233877d492b94eee0c5b6d1"),
437            false,
438        );
439
440        let mut buf = vec![];
441        tx.rlp_encode_signed(&sig, &mut buf);
442        let decoded = TxEip7702::rlp_decode_signed(&mut &buf[..]).unwrap();
443        assert_eq!(decoded, tx.into_signed(sig));
444    }
445
446    #[test]
447    fn test_decode_create() {
448        // tests that a contract creation tx encodes and decodes properly
449        let tx = TxEip7702 {
450            chain_id: 1u64,
451            nonce: 0,
452            max_fee_per_gas: 0x4a817c800,
453            max_priority_fee_per_gas: 0x3b9aca00,
454            gas_limit: 2,
455            to: Address::default(),
456            value: U256::ZERO,
457            input: vec![1, 2].into(),
458            access_list: Default::default(),
459            authorization_list: Default::default(),
460        };
461        let sig = Signature::from_scalars_and_parity(
462            b256!("840cfc572845f5786e702984c2a582528cad4b49b2a10b9db1be7fca90058565"),
463            b256!("25e7109ceb98168d95b09b18bbf6b685130e0562f233877d492b94eee0c5b6d1"),
464            false,
465        );
466        let mut buf = vec![];
467        tx.rlp_encode_signed(&sig, &mut buf);
468        let decoded = TxEip7702::rlp_decode_signed(&mut &buf[..]).unwrap();
469        assert_eq!(decoded, tx.into_signed(sig));
470    }
471
472    #[test]
473    fn test_decode_call() {
474        let tx = TxEip7702 {
475            chain_id: 1u64,
476            nonce: 0,
477            max_fee_per_gas: 0x4a817c800,
478            max_priority_fee_per_gas: 0x3b9aca00,
479            gas_limit: 2,
480            to: Address::default(),
481            value: U256::ZERO,
482            input: vec![1, 2].into(),
483            access_list: Default::default(),
484            authorization_list: Default::default(),
485        };
486
487        let sig = Signature::from_scalars_and_parity(
488            b256!("840cfc572845f5786e702984c2a582528cad4b49b2a10b9db1be7fca90058565"),
489            b256!("25e7109ceb98168d95b09b18bbf6b685130e0562f233877d492b94eee0c5b6d1"),
490            false,
491        );
492
493        let mut buf = vec![];
494        tx.rlp_encode_signed(&sig, &mut buf);
495        let decoded = TxEip7702::rlp_decode_signed(&mut &buf[..]).unwrap();
496        assert_eq!(decoded, tx.into_signed(sig));
497    }
498}