Skip to main content

df_hyperliquid_core/client/evm/
tx.rs

1//! EIP-1559 transactions, type 2, for HyperEVM and for Arbitrum: a call, or
2//! a contract creation when there is no `to`.
3//!
4//! ```text
5//! unsigned = 0x02 || rlp([chainId, nonce, maxPriorityFeePerGas, maxFeePerGas,
6//!                         gas, to, value, data, accessList])
7//! signed   = 0x02 || rlp([... the same nine, yParity, r, s])
8//! ```
9//!
10//! Without the `sign` feature the unsigned transaction, its signing hash and
11//! the raw bytes from a signature made elsewhere still build.
12
13#[cfg(feature = "sign")]
14use crate::account::{LocalKey, recover};
15use crate::account::{SignError, Signature};
16use crate::client::evm::rlp;
17use crate::client::evm::u256::{B256, U256};
18use crate::utils::Address;
19use crate::utils::sign::keccak256;
20use serde::Deserialize;
21
22/// The type byte that leads an EIP-1559 transaction, before and after signing.
23pub const EIP1559: u8 = 0x02;
24
25/// Gas asked for over the node's estimate, in percent, so a busier block does
26/// not run the transaction out.
27pub const GAS_HEADROOM: u64 = 130;
28
29/// The fee cap over the current base fee: room for two blocks of the largest rise.
30const BASE_FEE_TIMES: u64 = 2;
31
32/// A contract and the storage slots the transaction declares it will touch.
33#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize)]
34#[serde(rename_all = "camelCase")]
35pub struct AccessItem {
36    /// The contract.
37    pub address: Address,
38    /// The storage slots in it (`storageKeys`).
39    pub storage_keys: Vec<B256>,
40}
41
42/// The fields of a type 2 transaction, in the order they are encoded. Every
43/// amount is in wei of the chain's coin; `data` is the calldata, or the init
44/// code of a creation.
45#[derive(Debug, Clone, PartialEq, Eq, Default)]
46pub struct Eip1559 {
47    /// The chain the signature is for, such as 999 for HyperEVM mainnet (`chainId`).
48    pub chain_id: u64,
49    /// The sender's next nonce.
50    pub nonce: u64,
51    /// The tip cap in wei per unit of gas (`maxPriorityFeePerGas`).
52    pub max_priority_fee: U256,
53    /// The fee cap in wei per unit of gas, tip included (`maxFeePerGas`).
54    pub max_fee: U256,
55    /// The gas limit.
56    pub gas: u64,
57    /// `None` creates a contract from `data`.
58    pub to: Option<Address>,
59    /// Wei of the chain's coin sent with it.
60    pub value: U256,
61    /// The calldata, or the init code of a creation.
62    pub data: Vec<u8>,
63    /// Contracts and storage slots declared up front; usually empty.
64    pub access_list: Vec<AccessItem>,
65}
66
67impl Eip1559 {
68    fn fields(&self) -> Vec<Vec<u8>> {
69        let to = match &self.to {
70            Some(to) => rlp::bytes(to.bytes()),
71            None => rlp::bytes(&[]),
72        };
73        let access: Vec<Vec<u8>> = self
74            .access_list
75            .iter()
76            .map(|item| {
77                let keys: Vec<Vec<u8>> = item.storage_keys.iter().map(|key| rlp::bytes(&key.0)).collect();
78                rlp::list(&[rlp::bytes(item.address.bytes()), rlp::list(&keys)])
79            })
80            .collect();
81        vec![
82            rlp::uint(u128::from(self.chain_id)),
83            rlp::uint(u128::from(self.nonce)),
84            rlp::u256(self.max_priority_fee),
85            rlp::u256(self.max_fee),
86            rlp::uint(u128::from(self.gas)),
87            to,
88            rlp::u256(self.value),
89            rlp::bytes(&self.data),
90            rlp::list(&access),
91        ]
92    }
93
94    /// `0x02 || rlp(fields)`: what the signature commits to.
95    #[must_use]
96    pub fn unsigned(&self) -> Vec<u8> {
97        typed(&self.fields())
98    }
99
100    /// `keccak256` of [`Eip1559::unsigned`]: the digest the sender signs.
101    #[must_use]
102    pub fn signing_hash(&self) -> B256 {
103        B256(keccak256(&self.unsigned()))
104    }
105
106    /// `0x02 || rlp(fields, yParity, r, s)`: the bytes a node is sent. The
107    /// signature is over [`Eip1559::signing_hash`], from a key here or a
108    /// signer elsewhere; its `v` must be 27 or 28.
109    pub fn signed(&self, signature: &Signature) -> Result<Vec<u8>, SignError> {
110        let parity = match signature.recovery_id() {
111            Some(parity @ (0 | 1)) => parity,
112            _ => return Err(SignError::BadV(signature.v())),
113        };
114        let mut fields = self.fields();
115        fields.push(rlp::uint(u128::from(parity)));
116        fields.push(rlp::word(signature.r()));
117        fields.push(rlp::word(signature.s()));
118        Ok(typed(&fields))
119    }
120
121    /// Signed with a key held in memory: RFC 6979, low-s.
122    #[cfg(feature = "sign")]
123    pub fn sign(&self, key: &LocalKey) -> Result<Vec<u8>, SignError> {
124        self.signed(&key.sign_digest(&self.signing_hash().0)?)
125    }
126
127    /// The address that signed it, to check a wallet's signature before sending.
128    #[cfg(feature = "sign")]
129    pub fn signer(&self, signature: &Signature) -> Result<Address, SignError> {
130        recover(&self.signing_hash().0, signature)
131    }
132
133    /// The contract a creation makes when `from` sends it; `None` for a call.
134    #[must_use]
135    pub fn created(&self, from: Address) -> Option<Address> {
136        self.to.is_none().then(|| create_address(from, self.nonce))
137    }
138
139    /// The most the gas can cost: every unit at the fee cap.
140    #[must_use]
141    pub fn gas_ceiling(&self) -> U256 {
142        self.max_fee.saturating_mul(U256::from_u64(self.gas))
143    }
144
145    /// The most the sender can spend: the gas ceiling and the value.
146    #[must_use]
147    pub fn most_spent(&self) -> Option<U256> {
148        self.max_fee.checked_mul(U256::from_u64(self.gas))?.checked_add(self.value)
149    }
150}
151
152fn typed(fields: &[Vec<u8>]) -> Vec<u8> {
153    let mut out = vec![EIP1559];
154    out.extend(rlp::list(fields));
155    out
156}
157
158/// The hash a node gives a signed transaction: `keccak256` of its raw bytes.
159#[must_use]
160pub fn tx_hash(raw: &[u8]) -> B256 {
161    B256(keccak256(raw))
162}
163
164/// Where a creation sent by `from` at `nonce` puts its contract:
165/// `keccak256(rlp([from, nonce]))`, last twenty bytes.
166#[must_use]
167pub fn create_address(from: Address, nonce: u64) -> Address {
168    let hash = keccak256(&rlp::list(&[rlp::bytes(from.bytes()), rlp::uint(u128::from(nonce))]));
169    let mut bytes = [0u8; 20];
170    bytes.copy_from_slice(&hash[12..]);
171    Address::from_bytes(bytes)
172}
173
174/// What a transaction does: where it goes, the value it carries, its calldata.
175#[derive(Debug, Clone, PartialEq, Eq, Default)]
176pub struct Call {
177    /// `None` creates a contract from `data`.
178    pub to: Option<Address>,
179    /// Wei of the chain's coin sent with it.
180    pub value: U256,
181    /// The calldata, or the init code of a creation.
182    pub data: Vec<u8>,
183}
184
185impl Call {
186    /// The transaction that makes this call on `chain_id`.
187    #[must_use]
188    pub fn transaction(self, chain_id: u64, nonce: u64, gas: u64, fees: Fees) -> Eip1559 {
189        Eip1559 {
190            chain_id,
191            nonce,
192            max_priority_fee: fees.max_priority_fee,
193            max_fee: fees.max_fee,
194            gas,
195            to: self.to,
196            value: self.value,
197            data: self.data,
198            access_list: Vec::new(),
199        }
200    }
201}
202
203/// The two fees a type 2 transaction names, in wei per unit of gas.
204#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
205pub struct Fees {
206    /// The tip cap in wei per unit of gas (`maxPriorityFeePerGas`).
207    pub max_priority_fee: U256,
208    /// The fee cap in wei per unit of gas, tip included (`maxFeePerGas`).
209    pub max_fee: U256,
210}
211
212impl Fees {
213    /// The tip, and a cap of twice the base fee plus the tip: what a block or
214    /// two of rising fees can take. Saturates rather than wraps.
215    #[must_use]
216    pub fn over_base(base: U256, tip: U256) -> Fees {
217        let max_fee = base.saturating_mul(U256::from_u64(BASE_FEE_TIMES)).saturating_add(tip);
218        Fees { max_priority_fee: tip, max_fee }
219    }
220}
221
222/// The node's gas estimate with [`GAS_HEADROOM`].
223#[must_use]
224pub fn with_headroom(gas: u64) -> u64 {
225    let wide = u128::from(gas) * u128::from(GAS_HEADROOM) / 100;
226    u64::try_from(wide).unwrap_or(u64::MAX)
227}
228
229#[cfg(test)]
230#[path = "tests/tx.rs"]
231mod tests;