alloy_primitives/
common.rs

1use crate::Address;
2
3#[cfg(feature = "rlp")]
4use alloy_rlp::{Buf, BufMut, Decodable, Encodable, EMPTY_STRING_CODE};
5
6/// The `to` field of a transaction. Either a target address, or empty for a
7/// contract creation.
8#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
9#[cfg_attr(feature = "arbitrary", derive(derive_arbitrary::Arbitrary, proptest_derive::Arbitrary))]
10#[doc(alias = "TransactionKind")]
11pub enum TxKind {
12    /// A transaction that creates a contract.
13    #[default]
14    Create,
15    /// A transaction that calls a contract or transfer.
16    Call(Address),
17}
18
19impl From<Option<Address>> for TxKind {
20    /// Creates a `TxKind::Call` with the `Some` address, `None` otherwise.
21    #[inline]
22    fn from(value: Option<Address>) -> Self {
23        match value {
24            None => Self::Create,
25            Some(addr) => Self::Call(addr),
26        }
27    }
28}
29
30impl From<Address> for TxKind {
31    /// Creates a `TxKind::Call` with the given address.
32    #[inline]
33    fn from(value: Address) -> Self {
34        Self::Call(value)
35    }
36}
37
38impl TxKind {
39    /// Returns the address of the contract that will be called or will receive the transfer.
40    pub const fn to(&self) -> Option<&Address> {
41        match self {
42            Self::Create => None,
43            Self::Call(to) => Some(to),
44        }
45    }
46
47    /// Returns true if the transaction is a contract creation.
48    #[inline]
49    pub const fn is_create(&self) -> bool {
50        matches!(self, Self::Create)
51    }
52
53    /// Returns true if the transaction is a contract call.
54    #[inline]
55    pub const fn is_call(&self) -> bool {
56        matches!(self, Self::Call(_))
57    }
58
59    /// Calculates a heuristic for the in-memory size of this object.
60    #[inline]
61    pub const fn size(&self) -> usize {
62        core::mem::size_of::<Self>()
63    }
64}
65
66#[cfg(feature = "rlp")]
67impl Encodable for TxKind {
68    fn encode(&self, out: &mut dyn BufMut) {
69        match self {
70            Self::Call(to) => to.encode(out),
71            Self::Create => out.put_u8(EMPTY_STRING_CODE),
72        }
73    }
74
75    fn length(&self) -> usize {
76        match self {
77            Self::Call(to) => to.length(),
78            Self::Create => 1, // EMPTY_STRING_CODE is a single byte
79        }
80    }
81}
82
83#[cfg(feature = "rlp")]
84impl Decodable for TxKind {
85    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
86        if let Some(&first) = buf.first() {
87            if first == EMPTY_STRING_CODE {
88                buf.advance(1);
89                Ok(Self::Create)
90            } else {
91                let addr = <Address as Decodable>::decode(buf)?;
92                Ok(Self::Call(addr))
93            }
94        } else {
95            Err(alloy_rlp::Error::InputTooShort)
96        }
97    }
98}
99
100#[cfg(feature = "serde")]
101impl serde::Serialize for TxKind {
102    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
103        self.to().serialize(serializer)
104    }
105}
106
107#[cfg(feature = "serde")]
108impl<'de> serde::Deserialize<'de> for TxKind {
109    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
110        Ok(Option::<Address>::deserialize(deserializer)?.into())
111    }
112}