Skip to main content

forge_script/
transaction.rs

1use super::ScriptResult;
2use crate::build::LinkedBuildData;
3use alloy_dyn_abi::JsonAbiExt;
4use alloy_network::{Network, TransactionBuilder};
5use alloy_primitives::{Address, B256, Selector, hex};
6use eyre::Result;
7use forge_script_sequence::TransactionWithMetadata;
8use foundry_cli::utils::apply_gas_estimate_multiplier;
9use foundry_common::{
10    ContractData, ContractsByArtifact, SELECTOR_LEN, TransactionMaybeSigned, fmt::format_token_raw,
11};
12use foundry_evm::traces::{CallKind, CallTraceDecoder};
13use itertools::Itertools;
14use std::collections::BTreeMap;
15
16#[derive(Debug)]
17pub struct ScriptTransactionBuilder<N: Network> {
18    transaction: TransactionWithMetadata<N>,
19}
20
21impl<N: Network> ScriptTransactionBuilder<N> {
22    pub fn new(transaction: TransactionMaybeSigned<N>, rpc: String) -> Self {
23        let mut transaction = TransactionWithMetadata::from_tx_request(transaction);
24        transaction.rpc = rpc;
25        // If tx.gas is already set that means it was specified in script
26        transaction.is_fixed_gas_limit = transaction.tx().gas().is_some();
27
28        Self { transaction }
29    }
30
31    /// Populate the transaction as CALL tx
32    pub fn set_call(
33        &mut self,
34        local_contracts: &BTreeMap<Address, &ContractData>,
35        known_contracts: &ContractsByArtifact,
36        decoder: &CallTraceDecoder,
37        create2_deployer: Address,
38    ) -> Result<()> {
39        if let Some(to) = self.transaction.transaction.to() {
40            self.transaction.call_kind = CallKind::Call;
41            self.transaction.contract_address = Some(to);
42
43            if to == create2_deployer {
44                if let Some(input) = self.transaction.transaction.input()
45                    && input.len() >= 32
46                {
47                    let (salt, init_code) = input.split_at(32);
48
49                    self.set_create(
50                        true,
51                        create2_deployer.create2_from_code(B256::from_slice(salt), init_code),
52                        known_contracts,
53                    )?;
54                } else {
55                    let input_len =
56                        self.transaction.transaction.input().map_or(0, |input| input.len());
57                    sh_warn!(
58                        "Skipping CREATE2 decoding for call to deployer {create2_deployer}: input length {input_len} is shorter than the 32-byte salt prefix"
59                    )?;
60                }
61            } else {
62                let Some(data) = self.transaction.transaction.input() else { return Ok(()) };
63
64                if data.len() < SELECTOR_LEN {
65                    return Ok(());
66                }
67
68                let (selector, data) = data.split_at(SELECTOR_LEN);
69                let selector = Selector::from_slice(selector);
70
71                let function = if let Some(info) = local_contracts.get(&to) {
72                    // This CALL is made to a local contract.
73                    self.transaction.contract_name = Some(info.name.clone());
74                    info.abi.functions().find(|function| function.selector() == selector)
75                } else {
76                    // This CALL is made to an external contract; try to decode it from the given
77                    // decoder.
78                    decoder
79                        .functions_for_selector(to, &selector)
80                        .and_then(|functions| functions.first())
81                };
82
83                if let Some(function) = function {
84                    self.transaction.function = Some(function.signature());
85                    self.transaction.function_abi = Some(function.full_signature());
86                    self.transaction.display_function = Some(function.name.clone());
87
88                    let values = function.abi_decode_input(data).inspect_err(|_| {
89                        error!(
90                            contract=?self.transaction.contract_name,
91                            signature=?function,
92                            data=hex::encode(data),
93                            "Failed to decode function arguments",
94                        );
95                    })?;
96                    self.transaction.arguments =
97                        Some(values.iter().map(format_token_raw).collect());
98                }
99            }
100        }
101
102        Ok(())
103    }
104
105    /// Populate the transaction as CREATE tx
106    ///
107    /// If this is a CREATE2 transaction this attempt to decode the arguments from the CREATE2
108    /// deployer's function
109    pub fn set_create(
110        &mut self,
111        is_create2: bool,
112        address: Address,
113        contracts: &ContractsByArtifact,
114    ) -> Result<()> {
115        if is_create2 {
116            self.transaction.call_kind = CallKind::Create2;
117        } else {
118            self.transaction.call_kind = CallKind::Create;
119        }
120
121        self.transaction.contract_address = Some(address);
122
123        let Some(data) = self.transaction.transaction.input() else { return Ok(()) };
124
125        // `create2` transactions are prefixed by a 32 byte salt.
126        let creation_code = if is_create2 {
127            if data.len() < 32 {
128                return Ok(());
129            }
130            &data[32..]
131        } else {
132            data
133        };
134        let artifact = contracts.find_by_creation_code_prefix(creation_code);
135        self.transaction.contract_name = artifact
136            .or_else(|| contracts.find_by_creation_code(creation_code))
137            .map(|(id, _)| id.name.clone());
138        // Script verification skips Vyper, so a Vyper deployment never has to match on resume.
139        self.transaction.exact_artifact_match =
140            artifact.is_some_and(|(id, _)| !id.source.extension().is_some_and(|ext| ext == "vy"));
141
142        let Some((_, info)) = artifact else { return Ok(()) };
143        let Some(bytecode) = info.bytecode() else { return Ok(()) };
144
145        // The constructor args start after bytecode.
146        let contains_constructor_args = creation_code.len() > bytecode.len();
147        if !contains_constructor_args {
148            return Ok(());
149        }
150        let constructor_args = &creation_code[bytecode.len()..];
151
152        let Some(constructor) = info.abi.constructor() else { return Ok(()) };
153        let values = constructor.abi_decode_input(constructor_args).inspect_err(|_| {
154                error!(
155                    contract=?self.transaction.contract_name,
156                    signature=%format!("constructor({})", constructor.inputs.iter().map(|p| &p.ty).format(",")),
157                    is_create2,
158                    constructor_args=%hex::encode(constructor_args),
159                    "Failed to decode constructor arguments",
160                );
161                debug!(full_data=%hex::encode(data), bytecode=%hex::encode(creation_code));
162            })?;
163        self.transaction.arguments = Some(values.iter().map(format_token_raw).collect());
164
165        Ok(())
166    }
167
168    /// Populates additional data from the transaction execution result.
169    pub fn with_execution_result(
170        mut self,
171        result: &ScriptResult<N>,
172        gas_estimate_multiplier: u64,
173        linked_build_data: &LinkedBuildData,
174    ) -> Result<Self> {
175        let mut created_contracts =
176            result.get_created_contracts(&linked_build_data.known_contracts);
177
178        // Add the additional contracts created in this transaction, so we can verify them later.
179        created_contracts.retain(|contract| {
180            // Filter out the contract that was created by the transaction itself.
181            self.transaction.contract_address != Some(contract.address)
182        });
183
184        self.transaction.additional_contracts = created_contracts;
185
186        if !self.transaction.is_fixed_gas_limit
187            && let Some(unsigned) = self.transaction.transaction.as_unsigned_mut()
188        {
189            // We inflate the gas used by the user specified percentage
190            unsigned.set_gas_limit(apply_gas_estimate_multiplier(
191                result.gas_used,
192                Some(gas_estimate_multiplier),
193            )?);
194        }
195
196        Ok(self)
197    }
198
199    pub fn build(self) -> TransactionWithMetadata<N> {
200        self.transaction
201    }
202}
203
204impl<N: Network> From<TransactionWithMetadata<N>> for ScriptTransactionBuilder<N> {
205    fn from(transaction: TransactionWithMetadata<N>) -> Self {
206        Self { transaction }
207    }
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213    use alloy_network::Ethereum;
214    use alloy_primitives::{Bytes, address};
215    use alloy_rpc_types::TransactionRequest;
216
217    fn call_to_create2_deployer(input: Option<Bytes>) -> TransactionWithMetadata<Ethereum> {
218        let create2_deployer = address!("0000000000000000000000000000000000001234");
219        let mut transaction = TransactionRequest::default()
220            .with_from(Address::repeat_byte(0x11))
221            .with_to(create2_deployer)
222            .with_nonce(0);
223        if let Some(input) = input {
224            transaction = transaction.with_input(input);
225        }
226        let mut builder = ScriptTransactionBuilder::<Ethereum>::new(
227            TransactionMaybeSigned::new(transaction),
228            "http://localhost:8545".to_string(),
229        );
230        let decoder = CallTraceDecoder::new();
231        builder
232            .set_call(&BTreeMap::new(), &ContractsByArtifact::default(), decoder, create2_deployer)
233            .unwrap();
234        builder.build()
235    }
236
237    #[test]
238    fn short_create2_input_is_classified_as_call() {
239        let create2_deployer = address!("0000000000000000000000000000000000001234");
240        for input in [None, Some(Bytes::new()), Some(Bytes::from(vec![0xab; 31]))] {
241            let transaction = call_to_create2_deployer(input);
242            assert_eq!(transaction.call_kind, CallKind::Call);
243            assert_eq!(transaction.contract_address, Some(create2_deployer));
244        }
245    }
246
247    #[test]
248    fn valid_create2_input_is_classified_as_create2() {
249        let create2_deployer = address!("0000000000000000000000000000000000001234");
250        for input in [Bytes::from(vec![0xab; 32]), Bytes::from(vec![0xab; 33])] {
251            let expected = create2_deployer
252                .create2_from_code(B256::repeat_byte(0xab), input.get(32..).unwrap());
253            let transaction = call_to_create2_deployer(Some(input));
254            assert_eq!(transaction.call_kind, CallKind::Create2);
255            assert_eq!(transaction.contract_address, Some(expected));
256        }
257    }
258}
259
260#[cfg(all(test, feature = "monad"))]
261mod monad_tests {
262    use super::*;
263    use alloy_network::Ethereum;
264    use alloy_primitives::{Bytes, address, keccak256};
265    use alloy_rpc_types::TransactionRequest;
266    use foundry_evm::{hardforks::MonadHardfork, traces::CallTraceDecoderBuilder};
267    use foundry_evm_networks::NetworkConfigs;
268
269    const STAKING_ADDRESS: Address = address!("0000000000000000000000000000000000001000");
270    const RESERVE_BALANCE_ADDRESS: Address = address!("0000000000000000000000000000000000001001");
271
272    fn monad_decoder(hardfork: MonadHardfork) -> CallTraceDecoder {
273        CallTraceDecoderBuilder::new()
274            .with_networks(NetworkConfigs::with_monad())
275            .with_chain_id(Some(143))
276            .with_hardfork(Some(hardfork.into()))
277            .build()
278    }
279
280    fn call_metadata(
281        address: Address,
282        signature: &str,
283        hardfork: MonadHardfork,
284    ) -> TransactionWithMetadata<Ethereum> {
285        let input = Bytes::copy_from_slice(&keccak256(signature)[..SELECTOR_LEN]);
286        let selector = Selector::from_slice(&input);
287        let decoder = monad_decoder(hardfork);
288
289        assert!(!decoder.functions.contains_key(&selector));
290        assert!(decoder.functions_for_selector(address, &selector).is_some());
291
292        let transaction = TransactionRequest::default()
293            .with_from(Address::repeat_byte(0x11))
294            .with_to(address)
295            .with_nonce(0)
296            .with_input(input);
297        let mut builder = ScriptTransactionBuilder::new(
298            TransactionMaybeSigned::new(transaction),
299            "http://localhost:8545".to_string(),
300        );
301        builder
302            .set_call(&BTreeMap::new(), &ContractsByArtifact::default(), &decoder, Address::ZERO)
303            .unwrap();
304        builder.build()
305    }
306
307    #[test]
308    fn address_scoped_monad_calls_populate_metadata() {
309        let staking = call_metadata(STAKING_ADDRESS, "getEpoch()", MonadHardfork::MonadEight);
310        assert_eq!(staking.function.as_deref(), Some("getEpoch()"));
311        assert_eq!(
312            staking.function_abi.as_deref(),
313            Some("function getEpoch() returns (uint64 epoch, bool inEpochDelayPeriod)")
314        );
315        assert_eq!(staking.display_function.as_deref(), Some("getEpoch"));
316        assert_eq!(staking.arguments, Some(Vec::new()));
317
318        let reserve =
319            call_metadata(RESERVE_BALANCE_ADDRESS, "dippedIntoReserve()", MonadHardfork::MonadNine);
320        assert_eq!(reserve.function.as_deref(), Some("dippedIntoReserve()"));
321        assert_eq!(
322            reserve.function_abi.as_deref(),
323            Some("function dippedIntoReserve() returns (bool dipped)")
324        );
325        assert_eq!(reserve.display_function.as_deref(), Some("dippedIntoReserve"));
326        assert_eq!(reserve.arguments, Some(Vec::new()));
327    }
328}