Skip to main content

foundry_cli/opts/
transaction.rs

1use std::str::FromStr;
2
3use super::TempoOpts;
4use crate::utils::{parse_ether_value, parse_json};
5use alloy_eips::{eip2930::AccessList, eip7702::SignedAuthorization};
6use alloy_network::{Network, TransactionBuilder};
7use alloy_primitives::{Address, U64, U256, hex};
8use alloy_rlp::Decodable;
9use clap::Parser;
10use foundry_common::FoundryTransactionBuilder;
11
12/// CLI helper to parse an EIP-7702 authorization list.
13/// Can be either a hex-encoded signed authorization or an address.
14#[derive(Clone, Debug)]
15pub enum CliAuthorizationList {
16    /// If an address is provided, we sign the authorization delegating to provided address.
17    Address(Address),
18    /// If RLP-encoded authorization is provided, we decode it and attach to transaction.
19    Signed(SignedAuthorization),
20}
21
22impl FromStr for CliAuthorizationList {
23    type Err = eyre::Error;
24
25    fn from_str(s: &str) -> Result<Self, Self::Err> {
26        if let Ok(addr) = Address::from_str(s) {
27            Ok(Self::Address(addr))
28        } else if let Ok(auth) = SignedAuthorization::decode(&mut hex::decode(s)?.as_ref()) {
29            auth.signature()
30                .map_err(|err| eyre::eyre!("Invalid authorization signature: {err}"))?;
31            Ok(Self::Signed(auth))
32        } else {
33            eyre::bail!("Failed to decode authorization");
34        }
35    }
36}
37
38#[derive(Clone, Debug, Parser)]
39#[command(next_help_heading = "Transaction options")]
40pub struct TransactionOpts {
41    /// Gas limit for the transaction.
42    #[arg(long, env = "ETH_GAS_LIMIT")]
43    pub gas_limit: Option<U256>,
44
45    /// Gas price for legacy transactions, or max fee per gas for EIP1559 transactions, either
46    /// specified in wei, or as a string with a unit type.
47    ///
48    /// Examples: 1ether, 10gwei, 0.01ether
49    #[arg(
50        long,
51        env = "ETH_GAS_PRICE",
52        value_parser = parse_ether_value,
53        value_name = "PRICE"
54    )]
55    pub gas_price: Option<U256>,
56
57    /// Max priority fee per gas for EIP1559 transactions.
58    #[arg(
59        long,
60        env = "ETH_PRIORITY_GAS_PRICE",
61        value_parser = parse_ether_value,
62        value_name = "PRICE"
63    )]
64    pub priority_gas_price: Option<U256>,
65
66    /// Ether to send in the transaction, either specified in wei, or as a string with a unit type.
67    ///
68    ///
69    ///
70    /// Examples: 1ether, 10gwei, 0.01ether
71    #[arg(long, value_parser = parse_ether_value)]
72    pub value: Option<U256>,
73
74    /// Nonce for the transaction.
75    #[arg(long)]
76    pub nonce: Option<U64>,
77
78    /// Send a legacy transaction instead of an EIP1559 transaction.
79    ///
80    /// This is automatically enabled for common networks without EIP1559.
81    #[arg(long)]
82    pub legacy: bool,
83
84    /// Send a blob transaction using EIP-7594 (PeerDAS) format.
85    ///
86    /// Note: Use with `--eip4844` for the legacy EIP-4844 format.
87    #[arg(long, conflicts_with = "legacy")]
88    pub blob: bool,
89
90    /// Send a blob transaction using EIP-4844 (legacy) format instead of EIP-7594. Must be used
91    /// with `--blob`.
92    #[arg(long, conflicts_with = "legacy", requires = "blob")]
93    pub eip4844: bool,
94
95    /// Gas price for EIP-7594/EIP-4844 blob transaction.
96    #[arg(long, conflicts_with = "legacy", value_parser = parse_ether_value, env = "ETH_BLOB_GAS_PRICE", value_name = "BLOB_PRICE")]
97    pub blob_gas_price: Option<U256>,
98
99    /// EIP-7702 authorization list.
100    ///
101    /// Can be either a hex-encoded signed authorization or an address.
102    #[arg(long, conflicts_with_all = &["legacy", "blob"])]
103    pub auth: Vec<CliAuthorizationList>,
104
105    /// EIP-2930 access list.
106    ///
107    /// Accepts either a JSON-encoded access list or an empty value to create the access list
108    /// via an RPC call to `eth_createAccessList`. To retrieve only the access list portion, use
109    /// the `cast access-list` command.
110    #[arg(long, value_parser = parse_json::<AccessList>)]
111    pub access_list: Option<Option<AccessList>>,
112
113    #[command(flatten)]
114    pub tempo: TempoOpts,
115}
116
117impl TransactionOpts {
118    /// Applies gas, value, fee, and network-specific options to a transaction request.
119    pub fn apply<N: Network>(&self, tx: &mut N::TransactionRequest, legacy: bool)
120    where
121        N::TransactionRequest: FoundryTransactionBuilder<N>,
122    {
123        if let Some(gas_limit) = self.gas_limit {
124            tx.set_gas_limit(gas_limit.to());
125        }
126
127        if let Some(value) = self.value {
128            tx.set_value(value);
129        }
130
131        if let Some(gas_price) = self.gas_price {
132            if legacy {
133                tx.set_gas_price(gas_price.to());
134            } else {
135                tx.set_max_fee_per_gas(gas_price.to());
136            }
137        }
138
139        if !legacy && let Some(priority_fee) = self.priority_gas_price {
140            tx.set_max_priority_fee_per_gas(priority_fee.to());
141        }
142
143        if let Some(max_blob_fee) = self.blob_gas_price {
144            tx.set_max_fee_per_blob_gas(max_blob_fee.to())
145        }
146
147        // set network-specific options
148        self.tempo.apply::<N>(tx, self.nonce.map(|n| n.to()));
149    }
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155    use alloy_eips::eip7702::Authorization;
156
157    #[test]
158    fn parse_priority_gas_tx_opts() {
159        let args: TransactionOpts =
160            TransactionOpts::parse_from(["foundry-cli", "--priority-gas-price", "100"]);
161        assert!(args.priority_gas_price.is_some());
162    }
163
164    #[test]
165    fn parse_signed_authorization_rejects_invalid_parity() {
166        let auth = |y_parity| {
167            let auth = Authorization { chain_id: U256::from(1), address: Address::ZERO, nonce: 0 };
168            hex::encode(alloy_rlp::encode(SignedAuthorization::new_unchecked(
169                auth,
170                y_parity,
171                U256::from(1),
172                U256::from(1),
173            )))
174        };
175
176        assert!(matches!(auth(1).parse(), Ok(CliAuthorizationList::Signed(_))));
177        assert_eq!(
178            auth(27).parse::<CliAuthorizationList>().unwrap_err().to_string(),
179            "Invalid authorization signature: invalid parity: 27"
180        );
181    }
182}