Skip to main content

foundry_cheatcodes/evm/
mock.rs

1use crate::{Cheatcode, CheatcodesCore, CheatsCtxt, Result, Vm::*};
2use alloy_primitives::{Address, Bytes, U256, map::HashMap};
3use evm2::bytecode::Bytecode;
4use foundry_evm_core::evm::FoundryEvmNetwork;
5use std::{
6    cmp::Ordering,
7    collections::{BTreeMap, VecDeque},
8};
9
10/// Mocked call data.
11#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
12pub struct MockCallDataContext {
13    /// The partial calldata to match for mock
14    pub calldata: Bytes,
15    /// The value to match for mock
16    pub value: Option<U256>,
17}
18
19/// Mocked return data.
20#[derive(Clone, Debug)]
21pub struct MockCallReturnData {
22    /// Whether the mocked call reverts.
23    pub reverts: bool,
24    /// Return data or error
25    pub data: Bytes,
26}
27
28impl PartialOrd for MockCallDataContext {
29    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
30        Some(self.cmp(other))
31    }
32}
33
34impl Ord for MockCallDataContext {
35    fn cmp(&self, other: &Self) -> Ordering {
36        // Calldata matching is reversed to ensure that a tighter match is
37        // returned if an exact match is not found. In case, there is
38        // a partial match to calldata that is more specific than
39        // a match to a msg.value, then the more specific calldata takes
40        // precedence.
41        self.calldata.cmp(&other.calldata).reverse().then(self.value.cmp(&other.value).reverse())
42    }
43}
44
45impl Cheatcode for clearMockedCallsCall {
46    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
47        let Self {} = self;
48        state.mocked_calls = Default::default();
49        Ok(Default::default())
50    }
51}
52
53impl Cheatcode for mockCall_0Call {
54    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
55        let Self { callee, data, returnData } = self;
56        let _ = make_acc_non_empty(callee, ccx)?;
57
58        mock_call(&mut ccx.state.core.mocked_calls, callee, data, None, returnData, false);
59        Ok(Default::default())
60    }
61}
62
63impl Cheatcode for mockCall_1Call {
64    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
65        let Self { callee, msgValue, data, returnData } = self;
66        let _ = make_acc_non_empty(callee, ccx)?;
67
68        mock_call(
69            &mut ccx.state.core.mocked_calls,
70            callee,
71            data,
72            Some(msgValue),
73            returnData,
74            false,
75        );
76        Ok(Default::default())
77    }
78}
79
80impl Cheatcode for mockCall_2Call {
81    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
82        let Self { callee, data, returnData } = self;
83        let _ = make_acc_non_empty(callee, ccx)?;
84
85        mock_call(
86            &mut ccx.state.core.mocked_calls,
87            callee,
88            &Bytes::from(*data),
89            None,
90            returnData,
91            false,
92        );
93        Ok(Default::default())
94    }
95}
96
97impl Cheatcode for mockCall_3Call {
98    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
99        let Self { callee, msgValue, data, returnData } = self;
100        let _ = make_acc_non_empty(callee, ccx)?;
101
102        mock_call(
103            &mut ccx.state.core.mocked_calls,
104            callee,
105            &Bytes::from(*data),
106            Some(msgValue),
107            returnData,
108            false,
109        );
110        Ok(Default::default())
111    }
112}
113
114impl Cheatcode for mockCall_4Call {
115    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
116        let Self { callee, data, returnData, injectCode } = self;
117        if *injectCode {
118            let _ = make_acc_non_empty(callee, ccx)?;
119        }
120
121        mock_call(&mut ccx.state.core.mocked_calls, callee, data, None, returnData, false);
122        Ok(Default::default())
123    }
124}
125
126impl Cheatcode for mockCalls_0Call {
127    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
128        let Self { callee, data, returnData } = self;
129        let _ = make_acc_non_empty(callee, ccx)?;
130
131        mock_calls(&mut ccx.state.core.mocked_calls, callee, data, None, returnData, false);
132        Ok(Default::default())
133    }
134}
135
136impl Cheatcode for mockCalls_1Call {
137    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
138        let Self { callee, msgValue, data, returnData } = self;
139        let _ = make_acc_non_empty(callee, ccx)?;
140
141        mock_calls(
142            &mut ccx.state.core.mocked_calls,
143            callee,
144            data,
145            Some(msgValue),
146            returnData,
147            false,
148        );
149        Ok(Default::default())
150    }
151}
152
153impl Cheatcode for mockCallRevert_0Call {
154    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
155        let Self { callee, data, revertData } = self;
156        let _ = make_acc_non_empty(callee, ccx)?;
157
158        mock_call(&mut ccx.state.core.mocked_calls, callee, data, None, revertData, true);
159        Ok(Default::default())
160    }
161}
162
163impl Cheatcode for mockCallRevert_1Call {
164    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
165        let Self { callee, msgValue, data, revertData } = self;
166        let _ = make_acc_non_empty(callee, ccx)?;
167
168        mock_call(&mut ccx.state.core.mocked_calls, callee, data, Some(msgValue), revertData, true);
169        Ok(Default::default())
170    }
171}
172
173impl Cheatcode for mockCallRevert_2Call {
174    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
175        let Self { callee, data, revertData } = self;
176        let _ = make_acc_non_empty(callee, ccx)?;
177
178        mock_call(
179            &mut ccx.state.core.mocked_calls,
180            callee,
181            &Bytes::from(*data),
182            None,
183            revertData,
184            true,
185        );
186        Ok(Default::default())
187    }
188}
189
190impl Cheatcode for mockCallRevert_3Call {
191    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
192        let Self { callee, msgValue, data, revertData } = self;
193        let _ = make_acc_non_empty(callee, ccx)?;
194
195        mock_call(
196            &mut ccx.state.core.mocked_calls,
197            callee,
198            &Bytes::from(*data),
199            Some(msgValue),
200            revertData,
201            true,
202        );
203        Ok(Default::default())
204    }
205}
206
207impl Cheatcode for mockFunctionCall {
208    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
209        let Self { callee, target, data } = self;
210        state.mocked_functions.entry(*callee).or_default().insert(data.clone(), *target);
211
212        Ok(Default::default())
213    }
214}
215
216fn mock_call(
217    mocks: &mut HashMap<Address, BTreeMap<MockCallDataContext, VecDeque<MockCallReturnData>>>,
218    callee: &Address,
219    cdata: &Bytes,
220    value: Option<&U256>,
221    rdata: &Bytes,
222    reverts: bool,
223) {
224    mock_calls(mocks, callee, cdata, value, std::slice::from_ref(rdata), reverts)
225}
226
227fn mock_calls(
228    mocks: &mut HashMap<Address, BTreeMap<MockCallDataContext, VecDeque<MockCallReturnData>>>,
229    callee: &Address,
230    cdata: &Bytes,
231    value: Option<&U256>,
232    rdata_vec: &[Bytes],
233    reverts: bool,
234) {
235    mocks.entry(*callee).or_default().insert(
236        MockCallDataContext { calldata: cdata.clone(), value: value.copied() },
237        rdata_vec.iter().map(|rdata| MockCallReturnData { reverts, data: rdata.clone() }).collect(),
238    );
239}
240
241// Etches a single byte onto the account if it is empty to circumvent the `extcodesize`
242// check Solidity might perform.
243fn make_acc_non_empty<FEN: FoundryEvmNetwork>(
244    callee: &Address,
245    ccx: &mut CheatsCtxt<'_, '_, FEN>,
246) -> Result {
247    let mut account = ccx.evm.state_mut().account(callee)?;
248    account.warm();
249    if account.load_code()?.is_empty() {
250        account.set_code_slow(Bytecode::new_raw(Bytes::from_static(&[0u8])));
251    }
252
253    Ok(Default::default())
254}
255
256/// Finds the return data queue of the mock matching a call.
257///
258/// An exact calldata and value match wins. Otherwise, the first mock in map order whose calldata
259/// prefixes `input` and whose value, if set, equals `value` is used.
260pub(crate) fn find_mock_returns<'a, T>(
261    mocks: &'a mut BTreeMap<MockCallDataContext, VecDeque<T>>,
262    input: &Bytes,
263    value: Option<U256>,
264) -> Option<&'a mut VecDeque<T>> {
265    let ctx = MockCallDataContext { calldata: input.clone(), value };
266    // Reversed `Ord` puts all matches at or after `ctx`, with the exact key first.
267    mocks
268        .range_mut(ctx..)
269        .find(|(mock, _)| {
270            input.get(..mock.calldata.len()) == Some(&mock.calldata[..])
271                && mock.value.is_none_or(|mock_value| Some(mock_value) == value)
272        })
273        .map(|(_, v)| v)
274}
275
276/// Consumes the front return data of a mock, keeping the last one for every later call.
277pub(crate) fn advance_mock_returns<T>(queue: &mut VecDeque<T>) {
278    if queue.len() > 1 {
279        queue.pop_front();
280    }
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286
287    fn mock(
288        calldata: &'static [u8],
289        value: Option<u64>,
290        result: u8,
291    ) -> (MockCallDataContext, VecDeque<u8>) {
292        (
293            MockCallDataContext {
294                calldata: Bytes::from_static(calldata),
295                value: value.map(U256::from),
296            },
297            VecDeque::from([result]),
298        )
299    }
300
301    #[test]
302    fn mock_matching_precedence() {
303        let mut mocks = BTreeMap::from([
304            mock(b"call", Some(1), 1),
305            mock(b"call", Some(4), 9),
306            mock(b"call", None, 2),
307            mock(b"cal", Some(1), 3),
308            mock(b"cal", Some(0), 4),
309            mock(b"cal", Some(2), 5),
310            mock(b"cal", None, 6),
311            mock(b"ca", Some(3), 7),
312            mock(b"call-longer", Some(1), 8),
313        ]);
314
315        for (input, value, expected) in [
316            (b"call", Some(1), 1),
317            (b"call", Some(3), 2),
318            (b"call", None, 2),
319            (b"calx", Some(1), 3),
320            (b"calx", Some(3), 6),
321        ] {
322            let queue =
323                find_mock_returns(&mut mocks, &Bytes::from_static(input), value.map(U256::from))
324                    .unwrap();
325            assert_eq!(queue.front(), Some(&expected), "input: {input:?}, value: {value:?}");
326        }
327    }
328
329    #[test]
330    fn absent_transfer_value_does_not_match_zero() {
331        let mut mocks = BTreeMap::from([mock(b"call", Some(0), 1)]);
332        let input = Bytes::from_static(b"call");
333        assert!(find_mock_returns(&mut mocks, &input, None).is_none());
334        assert_eq!(
335            find_mock_returns(&mut mocks, &input, Some(U256::ZERO)).unwrap().front(),
336            Some(&1)
337        );
338
339        mocks.extend([mock(b"cal", None, 2)]);
340        assert_eq!(find_mock_returns(&mut mocks, &input, None).unwrap().front(), Some(&2));
341    }
342
343    #[test]
344    fn empty_matched_queue_is_distinct_from_no_match() {
345        let mut mocks = BTreeMap::from([mock(b"cal", None, 1)]);
346        mocks.insert(
347            MockCallDataContext { calldata: Bytes::from_static(b"call"), value: None },
348            VecDeque::new(),
349        );
350
351        let queue = find_mock_returns(&mut mocks, &Bytes::from_static(b"call"), None).unwrap();
352        assert!(queue.is_empty());
353        assert!(find_mock_returns(&mut mocks, &Bytes::from_static(b"other"), None).is_none());
354    }
355
356    #[test]
357    fn advancing_returns_keeps_last_result() {
358        let mut queue = VecDeque::from([1, 2, 3]);
359        advance_mock_returns(&mut queue);
360        assert_eq!(queue, VecDeque::from([2, 3]));
361        advance_mock_returns(&mut queue);
362        assert_eq!(queue, VecDeque::from([3]));
363        advance_mock_returns(&mut queue);
364        assert_eq!(queue, VecDeque::from([3]));
365
366        queue.clear();
367        advance_mock_returns(&mut queue);
368        assert!(queue.is_empty());
369    }
370}