alloy_consensus/transaction/
eip7702.rs

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