Skip to main content

foundry_evm_symbolic/executor/
calls.rs

1use super::*;
2use alloy_sol_types::{SolType, sol_data};
3use foundry_cheatcodes_spec::Vm::VmCalls;
4use foundry_common::ErrorExt;
5
6impl SymbolicExecutor {
7    pub(super) fn call(
8        &mut self,
9        executor: &ExecutorView<'_>,
10        state: &mut PathState,
11        worklist: &mut VecDeque<PathState>,
12        completed_paths: &mut usize,
13        kind: CallKind,
14    ) -> Result<StepOutcome, SymbolicError> {
15        let free_write_targets = self.free_address_write_targets(executor, state, kind)?;
16        let pre_call_state = (!state.function_mocks.is_empty()
17            || !free_write_targets.is_empty()
18            || !state.expected_calls.is_empty()
19            || !state.call_mocks.is_empty()
20            || (state.is_static && matches!(kind, CallKind::Call)))
21        .then(|| state.clone());
22        let call_pc = state.pc.saturating_sub(1);
23        // A word the fork decides in place leaves the remaining words to decide.
24        for (write_target, candidates) in &free_write_targets {
25            if self.branch_free_address_write_if_needed(
26                state,
27                worklist,
28                pre_call_state.as_ref().expect("free address writes require pre-call state"),
29                call_pc,
30                write_target,
31                candidates,
32            )? {
33                return Ok(StepOutcome::Forked);
34            }
35        }
36        if state.prank.has_active() {
37            state.resolve_prank_addresses(&mut self.cx);
38        }
39
40        let has_value = matches!(kind, CallKind::Call | CallKind::CallCode);
41        let in_offset_idx = if has_value { 3 } else { 2 };
42        let in_offset = state.stack.peek(in_offset_idx)?.clone();
43        let in_size = state.stack.peek(in_offset_idx + 1)?.clone();
44        let out_offset = state.stack.peek(in_offset_idx + 2)?.clone();
45        let out_size = state.stack.peek(in_offset_idx + 3)?.clone();
46        if let Some(outcome) =
47            self.guard_memory_range(executor, state, worklist, &in_offset, &in_size)?
48        {
49            return Ok(outcome);
50        }
51        if let Some(outcome) =
52            self.guard_memory_range(executor, state, worklist, &out_offset, &out_size)?
53        {
54            return Ok(outcome);
55        }
56
57        let gas = state.stack.pop()?;
58        // The equivalence check does not model the callee's gas, so explicit limits are kept.
59        if !gas.is_raw_gasleft() && !self.symbolic_gas() {
60            return Err(SymbolicError::Unsupported("explicit CALL gas limit not modeled"));
61        }
62        let target = state.stack.pop()?;
63        self.ensure_gas_modeled(&target)?;
64        let target = target.address_operand(&mut self.cx);
65        let target_address = state.world.resolve_address(&target);
66        let value = match (kind, target_address) {
67            (CallKind::Call, Some(to))
68                if to == CHEATCODE_ADDRESS || to == SYMBOLIC_VM_COMPAT_ADDRESS =>
69            {
70                let value = state.stack.pop()?;
71                let value =
72                    state.expect_constrained_word(&mut self.cx, value, "symbolic CALL value")?;
73                SymExpr::constant(&mut self.cx, value)
74            }
75            (CallKind::Call, _) => state.stack.pop()?,
76            (CallKind::CallCode, _) => state.stack.pop()?,
77            (CallKind::StaticCall | CallKind::DelegateCall, _) => SymExpr::zero(&mut self.cx),
78        };
79        self.ensure_gas_modeled(&value)?;
80        let in_offset = state.stack.pop()?;
81        self.ensure_gas_modeled(&in_offset)?;
82        let in_size = state.stack.pop()?;
83        self.ensure_gas_modeled(&in_size)?;
84        let in_size = match state.constrained_usize_checked(&mut self.cx, &in_size) {
85            Some(Ok(size)) => BoundedCopySize::Concrete(size),
86            Some(Err(_)) => {
87                return Ok(StepOutcome::Revert);
88            }
89            None => {
90                let max_limit = self.config.max_calldata_bytes as usize;
91                let max_size = self.solver_upper_bound_usize(
92                    state,
93                    &in_size,
94                    max_limit,
95                    "symbolic CALL input size",
96                )?;
97                BoundedCopySize::Symbolic { size: in_size, max_size }
98            }
99        };
100        let out_offset = state.stack.pop()?;
101        self.ensure_gas_modeled(&out_offset)?;
102        let out_size = state.stack.pop()?;
103        self.ensure_gas_modeled(&out_size)?;
104        let out_size = match state.constrained_usize_checked(&mut self.cx, &out_size) {
105            Some(Ok(size)) => BoundedCopySize::Concrete(size),
106            Some(Err(_)) => {
107                return Ok(StepOutcome::Revert);
108            }
109            None => {
110                let max_limit = self.config.max_calldata_bytes as usize;
111                let max_size = self.solver_upper_bound_usize(
112                    state,
113                    &out_size,
114                    max_limit,
115                    "symbolic CALL output size",
116                )?;
117                BoundedCopySize::Symbolic { size: out_size, max_size }
118            }
119        };
120
121        in_size.expand_memory(&mut self.cx, &mut state.memory, in_offset.clone());
122        out_size.expand_memory(&mut self.cx, &mut state.memory, out_offset.clone());
123
124        if state.is_static && matches!(kind, CallKind::Call) {
125            match state.constrained_word(&mut self.cx, &value) {
126                Some(value) if value.is_zero() => {}
127                Some(_) => {
128                    state.return_data = SymReturnData::empty(&mut self.cx);
129                    return Ok(StepOutcome::ExceptionalHalt);
130                }
131                None => {
132                    let zero = SymBoolExpr::eq_word_const(&mut self.cx, &value, U256::ZERO);
133                    let (zero_constraints, zero_sat) =
134                        self.constraints_with_condition(state, zero.clone())?;
135                    let nonzero = zero.not(&mut self.cx);
136                    let (nonzero_constraints, nonzero_sat) =
137                        self.constraints_with_condition(state, nonzero)?;
138                    match (zero_sat, nonzero_sat) {
139                        (true, true) => {
140                            let mut zero_state = pre_call_state
141                                .as_ref()
142                                .expect("static calls preserve pre-call state")
143                                .clone();
144                            zero_state.pc = call_pc;
145                            zero_state.constraints = zero_constraints;
146                            worklist.push_back(zero_state);
147                            state.constraints = nonzero_constraints;
148                            state.return_data = SymReturnData::empty(&mut self.cx);
149                            return Ok(StepOutcome::ExceptionalHalt);
150                        }
151                        (true, false) => state.constraints = zero_constraints,
152                        (false, true) => {
153                            state.constraints = nonzero_constraints;
154                            state.return_data = SymReturnData::empty(&mut self.cx);
155                            return Ok(StepOutcome::ExceptionalHalt);
156                        }
157                        (false, false) => return Ok(StepOutcome::AssumeRejected),
158                    }
159                }
160            }
161        }
162
163        let call_input = in_size.read_from_memory(&mut self.cx, &state.memory, in_offset.clone());
164        // Gas is not modeled, so calldata derived from `GAS` / `gasleft()` must fail closed instead
165        // of handing the callee a fabricated gas value.
166        if !self.symbolic_gas() && call_input.contains_gasleft(&mut self.cx) {
167            return Err(SymbolicError::Unsupported("GAS/gasleft() not modeled"));
168        }
169
170        if let Some(to) = target_address {
171            let code_address = if self.function_mock_may_match(executor, state, to, &call_input)? {
172                let callee = self.call_code_account(executor, state, to)?;
173                let pre_call_state =
174                    pre_call_state.as_ref().expect("function mocks require pre-call state");
175                if self.branch_symbolic_function_mock_if_needed(
176                    state,
177                    worklist,
178                    pre_call_state,
179                    call_pc,
180                    callee,
181                    &call_input,
182                )? {
183                    return Ok(StepOutcome::Forked);
184                }
185                self.function_mock_target(state, callee, &call_input)?.unwrap_or(to)
186            } else {
187                to
188            };
189            if !state.expected_calls.is_empty() || !state.call_mocks.is_empty() {
190                let pre_call_state =
191                    pre_call_state.as_ref().expect("call mocks require pre-call state");
192                if self.branch_symbolic_call_value_if_needed(
193                    state,
194                    worklist,
195                    pre_call_state,
196                    call_pc,
197                    code_address,
198                    &value,
199                    &gas,
200                    &call_input,
201                )? {
202                    return Ok(StepOutcome::Forked);
203                }
204            }
205            let concrete_value = self.transfer_value(state, kind, &value);
206            if !state.expected_calls.is_empty() || !state.call_mocks.is_empty() {
207                let pre_call_state =
208                    pre_call_state.as_ref().expect("call mocks require pre-call state");
209                if self.branch_symbolic_call_match_if_needed(
210                    state,
211                    worklist,
212                    pre_call_state,
213                    call_pc,
214                    code_address,
215                    concrete_value,
216                    &gas,
217                    &call_input,
218                )? {
219                    return Ok(StepOutcome::Forked);
220                }
221            }
222            return self.call_concrete_target(
223                executor,
224                state,
225                worklist,
226                completed_paths,
227                kind,
228                to,
229                Some(target),
230                value,
231                gas,
232                in_offset,
233                in_size,
234                out_offset,
235                out_size,
236            );
237        }
238
239        self.call_symbolic_target(
240            executor,
241            state,
242            worklist,
243            completed_paths,
244            kind,
245            target,
246            value,
247            gas,
248            in_offset,
249            in_size,
250            out_offset,
251            out_size,
252        )
253    }
254
255    #[expect(clippy::too_many_arguments)]
256    pub(super) fn branch_symbolic_call_value_if_needed(
257        &mut self,
258        state: &mut PathState,
259        worklist: &mut VecDeque<PathState>,
260        pre_call_state: &PathState,
261        call_pc: usize,
262        code_address: Address,
263        value: &SymExpr,
264        gas: &SymExpr,
265        call_input: &SymBytes,
266    ) -> Result<bool, SymbolicError> {
267        if state.constrained_word(&mut self.cx, value).is_some() {
268            return Ok(false);
269        }
270
271        for candidate in self.call_value_candidates(state, code_address, gas, call_input)? {
272            let eq = SymBoolExpr::eq_word_const(&mut self.cx, value, candidate);
273            let (eq_constraints, eq_sat) = self.constraints_with_condition(state, eq.clone())?;
274            let eq_not = eq.not(&mut self.cx);
275            let (neq_constraints, neq_sat) = self.constraints_with_condition(state, eq_not)?;
276
277            match (eq_sat, neq_sat) {
278                (true, true) => {
279                    let mut eq_state = pre_call_state.clone();
280                    eq_state.pc = call_pc;
281                    eq_state.constraints = eq_constraints;
282                    worklist.push_back(eq_state);
283
284                    let mut neq_state = pre_call_state.clone();
285                    neq_state.pc = call_pc;
286                    neq_state.constraints = neq_constraints;
287                    worklist.push_back(neq_state);
288                    return Ok(true);
289                }
290                (true, false) => {
291                    state.constraints = eq_constraints;
292                    return Ok(false);
293                }
294                (false, true) => {
295                    state.constraints = neq_constraints;
296                }
297                (false, false) => return Ok(false),
298            }
299        }
300
301        Ok(false)
302    }
303
304    pub(super) fn branch_symbolic_function_mock_if_needed(
305        &mut self,
306        state: &mut PathState,
307        worklist: &mut VecDeque<PathState>,
308        pre_call_state: &PathState,
309        call_pc: usize,
310        callee: Address,
311        calldata: &SymBytes,
312    ) -> Result<bool, SymbolicError> {
313        for condition in self.function_mock_conditions(state, callee, calldata) {
314            if self.branch_symbolic_match_condition_if_needed(
315                state,
316                worklist,
317                pre_call_state,
318                call_pc,
319                condition,
320            )? {
321                return Ok(true);
322            }
323        }
324
325        Ok(false)
326    }
327
328    pub(super) fn observe_expected_call(
329        &mut self,
330        state: &mut PathState,
331        callee: Address,
332        value: Option<U256>,
333        gas: &SymExpr,
334        calldata: &SymBytes,
335    ) -> Result<bool, SymbolicError> {
336        if state.expected_calls.is_empty() {
337            return Ok(true);
338        }
339        // Like Forge, the call counts for every expectation it matches.
340        let mut observed = true;
341        for idx in 0..state.expected_calls.len() {
342            if let Some(constraints) = self.expected_call_match_constraints(
343                state,
344                &state.expected_calls[idx],
345                callee,
346                value,
347                gas,
348                calldata,
349            )? {
350                state.constraints = constraints;
351                observed &= state.expected_calls[idx].observe();
352            }
353        }
354        Ok(observed)
355    }
356
357    #[expect(clippy::too_many_arguments)]
358    pub(super) fn branch_symbolic_call_match_if_needed(
359        &mut self,
360        state: &mut PathState,
361        worklist: &mut VecDeque<PathState>,
362        pre_call_state: &PathState,
363        call_pc: usize,
364        code_address: Address,
365        value: Option<U256>,
366        gas: &SymExpr,
367        calldata: &SymBytes,
368    ) -> Result<bool, SymbolicError> {
369        for condition in self.call_match_conditions(state, code_address, value, gas, calldata)? {
370            if self.branch_symbolic_match_condition_if_needed(
371                state,
372                worklist,
373                pre_call_state,
374                call_pc,
375                condition,
376            )? {
377                return Ok(true);
378            }
379        }
380
381        Ok(false)
382    }
383
384    pub(super) fn take_call_mock(
385        &mut self,
386        state: &mut PathState,
387        callee: Address,
388        value: Option<U256>,
389        calldata: &SymBytes,
390    ) -> Result<Option<CallMockOutcome>, SymbolicError> {
391        let Some((idx, constraints)) = self.select_call_mock(state, callee, value, calldata)?
392        else {
393            return Ok(None);
394        };
395        state.constraints = constraints;
396        if !state.call_mocks[idx].answers() {
397            return Ok(None);
398        }
399        Ok(Some(state.call_mocks[idx].next_outcome(&mut self.cx)))
400    }
401
402    /// Selects the most specific `vm.mockCall` matching this call, with the constraints of the
403    /// match, before deciding whether it answers the call, as Forge does.
404    fn select_call_mock(
405        &mut self,
406        state: &PathState,
407        callee: Address,
408        value: Option<U256>,
409        calldata: &SymBytes,
410    ) -> Result<Option<(usize, Vec<SymBoolExpr>)>, SymbolicError> {
411        let mut best = None;
412        for idx in 0..state.call_mocks.len() {
413            let Some(constraints) = self.call_mock_match_constraints(
414                state,
415                &state.call_mocks[idx],
416                callee,
417                value,
418                calldata,
419            )?
420            else {
421                continue;
422            };
423            let specificity = state.call_mocks[idx].specificity();
424            if best.as_ref().is_none_or(
425                |(_, best_specificity, _): &(usize, (usize, bool), Vec<SymBoolExpr>)| {
426                    specificity > *best_specificity
427                },
428            ) {
429                best = Some((idx, specificity, constraints));
430            }
431        }
432        Ok(best.map(|(idx, _, constraints)| (idx, constraints)))
433    }
434
435    /// Returns whether a `vm.mockCall` answers this call.
436    fn has_call_mock(
437        &mut self,
438        state: &PathState,
439        callee: Address,
440        value: &SymExpr,
441        calldata: &SymBytes,
442    ) -> Result<bool, SymbolicError> {
443        let value = state.constrained_word(&mut self.cx, value);
444        Ok(self
445            .select_call_mock(state, callee, value, calldata)?
446            .is_some_and(|(idx, _)| state.call_mocks[idx].answers()))
447    }
448
449    /// Returns the value that `vm.mockCall` and `vm.expectCall` value filters match. Like Forge's
450    /// `CallInputs::transfer_value`, a DELEGATECALL has none.
451    fn transfer_value(
452        &mut self,
453        state: &PathState,
454        kind: CallKind,
455        value: &SymExpr,
456    ) -> Option<U256> {
457        if matches!(kind, CallKind::DelegateCall) {
458            return None;
459        }
460        state.constrained_word(&mut self.cx, value)
461    }
462
463    pub(super) fn branch_symbolic_match_condition_if_needed(
464        &mut self,
465        state: &mut PathState,
466        worklist: &mut VecDeque<PathState>,
467        pre_call_state: &PathState,
468        call_pc: usize,
469        condition: SymBoolExpr,
470    ) -> Result<bool, SymbolicError> {
471        let (match_constraints, match_sat) =
472            self.constraints_with_condition(state, condition.clone())?;
473        let mismatch_condition = condition.not(&mut self.cx);
474        let (mismatch_constraints, mismatch_sat) =
475            self.constraints_with_condition(state, mismatch_condition)?;
476
477        match (match_sat, mismatch_sat) {
478            (true, true) => {
479                let mut match_state = pre_call_state.clone();
480                match_state.pc = call_pc;
481                match_state.constraints = match_constraints;
482                worklist.push_back(match_state);
483
484                let mut mismatch_state = pre_call_state.clone();
485                mismatch_state.pc = call_pc;
486                mismatch_state.constraints = mismatch_constraints;
487                worklist.push_back(mismatch_state);
488                Ok(true)
489            }
490            (true, false) => {
491                state.constraints = match_constraints;
492                Ok(false)
493            }
494            (false, true) => {
495                state.constraints = mismatch_constraints;
496                Ok(false)
497            }
498            (false, false) => Ok(false),
499        }
500    }
501
502    pub(super) fn function_mock_target(
503        &mut self,
504        state: &mut PathState,
505        callee: Address,
506        calldata: &SymBytes,
507    ) -> Result<Option<Address>, SymbolicError> {
508        for idx in (0..state.function_mocks.len()).rev() {
509            if state.function_mocks[idx].calldata_len() != calldata.len() {
510                continue;
511            }
512            let Some(condition) =
513                state.function_mocks[idx].match_condition(&mut self.cx, callee, calldata)
514            else {
515                continue;
516            };
517            if let Some(constraints) = self.constraints_for_condition(state, condition)? {
518                state.constraints = constraints;
519                return Ok(Some(state.function_mocks[idx].target()));
520            }
521        }
522        for idx in (0..state.function_mocks.len()).rev() {
523            if state.function_mocks[idx].calldata_len() != 4 {
524                continue;
525            }
526            let Some(condition) =
527                state.function_mocks[idx].match_condition(&mut self.cx, callee, calldata)
528            else {
529                continue;
530            };
531            if let Some(constraints) = self.constraints_for_condition(state, condition)? {
532                state.constraints = constraints;
533                return Ok(Some(state.function_mocks[idx].target()));
534            }
535        }
536        Ok(None)
537    }
538
539    /// Whether a function mock can match a call to `to` with `calldata` on this path, so its key,
540    /// the call's code address, is needed.
541    fn function_mock_may_match(
542        &mut self,
543        executor: &ExecutorView<'_>,
544        state: &mut PathState,
545        to: Address,
546        calldata: &SymBytes,
547    ) -> Result<bool, SymbolicError> {
548        if state.function_mocks.is_empty() {
549            return Ok(false);
550        }
551        let code_address = self.call_code_address(executor, state, to)?;
552        for idx in 0..state.function_mocks.len() {
553            if let Some(condition) = state.function_mocks[idx].code_match_condition(
554                &mut self.cx,
555                &code_address,
556                calldata,
557            ) && self.constraints_with_condition(state, condition)?.1
558            {
559                return Ok(true);
560            }
561        }
562        Ok(false)
563    }
564
565    /// Returns the code address of a call to `to`, which `vm.mockFunction` is keyed by: the
566    /// delegate of an EIP-7702 delegated `to`, as in evm2, which may be symbolic, or `to` itself.
567    fn call_code_address(
568        &mut self,
569        executor: &ExecutorView<'_>,
570        state: &mut PathState,
571        to: Address,
572    ) -> Result<SymExpr, SymbolicError> {
573        if executor.eip7702_delegations
574            && let Some(delegate) =
575                state.world.extcode(&mut self.cx, executor, to)?.eip7702_delegate(&mut self.cx)?
576        {
577            return Ok(delegate.right_aligned_word(&mut self.cx, 0, 20));
578        }
579        Ok(SymExpr::constant(&mut self.cx, address_word(to)))
580    }
581
582    /// Returns the code address of a call to `to`, whose code runs unless a mock redirects it.
583    pub(super) fn call_code_account(
584        &mut self,
585        executor: &ExecutorView<'_>,
586        state: &mut PathState,
587        to: Address,
588    ) -> Result<Address, SymbolicError> {
589        let address = self.call_code_address(executor, state, to)?;
590        let Some(address) = address.as_const() else {
591            return Err(SymbolicError::Unsupported("symbolic EIP-7702 delegation"));
592        };
593        Ok(word_to_address(address))
594    }
595
596    pub(super) fn expected_call_match_constraints(
597        &mut self,
598        state: &PathState,
599        expected: &ExpectedCall,
600        callee: Address,
601        value: Option<U256>,
602        gas: &SymExpr,
603        calldata: &SymBytes,
604    ) -> Result<Option<Vec<SymBoolExpr>>, SymbolicError> {
605        let Some(condition) =
606            expected.match_condition(&mut self.cx, callee, value, gas, calldata)?
607        else {
608            return Ok(None);
609        };
610        self.constraints_for_condition(state, condition)
611    }
612
613    pub(super) fn call_mock_match_constraints(
614        &mut self,
615        state: &PathState,
616        mock: &CallMock,
617        callee: Address,
618        value: Option<U256>,
619        calldata: &SymBytes,
620    ) -> Result<Option<Vec<SymBoolExpr>>, SymbolicError> {
621        let Some(condition) = mock.match_condition(&mut self.cx, callee, value, calldata) else {
622            return Ok(None);
623        };
624        self.constraints_for_condition(state, condition)
625    }
626
627    /// Returns whether `expected_revert_matches` holds.
628    pub(super) fn expected_revert_matches(
629        &mut self,
630        state: &mut PathState,
631        expected: &ExpectedRevert,
632        reverter: Option<Address>,
633        return_data: &SymReturnData,
634    ) -> Result<bool, SymbolicError> {
635        let Some(condition) = expected.match_condition(&mut self.cx, reverter, return_data) else {
636            return Ok(false);
637        };
638
639        let (match_constraints, match_sat) =
640            self.constraints_with_condition(state, condition.clone())?;
641        if !match_sat {
642            return Ok(false);
643        }
644
645        let mismatch_condition = condition.not(&mut self.cx);
646        let (mismatch_constraints, mismatch_sat) =
647            self.constraints_with_condition(state, mismatch_condition)?;
648        if mismatch_sat {
649            state.constraints = mismatch_constraints;
650            return Ok(false);
651        }
652
653        state.constraints = match_constraints;
654        Ok(true)
655    }
656
657    /// Finishes a call that runs no callee code, such as a mock, a precompile, an account without
658    /// code or a failed value transfer, applying a pending `vm.expectRevert` as Forge's
659    /// `call_end` does. Like `join_call_outcome`, a mismatch fails the path.
660    ///
661    /// Like `join_call_outcome`, a revert under `vm.assumeNoRevert` skips `vm.expectRevert`, and
662    /// a matching revert returns `FOUNDRY::ASSUME`.
663    #[expect(clippy::too_many_arguments)]
664    pub(super) fn finish_codeless_call(
665        &mut self,
666        executor: &ExecutorView<'_>,
667        state: &mut PathState,
668        kind: CallKind,
669        status: CallStatus,
670        mut return_data: SymReturnData,
671        reverter: Address,
672        out_offset: SymExpr,
673        out_size: &BoundedCopySize,
674    ) -> Result<StepOutcome, SymbolicError> {
675        let mut success = status == CallStatus::Success;
676        // Like Forge, a call that does not revert checks a pending `vm.expectEmit` unless
677        // `vm.expectRevert` handles it.
678        let unmet_expected_emit = !matches!(status, CallStatus::Revert)
679            && (state.expected_revert.is_none() || (success && executor.internal_expect_revert))
680            && state.check_expected_emit_after_call(kind);
681        let assumption = state.assume_no_revert_next_call.take();
682        let assumed_revert = status == CallStatus::Revert && assumption.is_some();
683        if status == CallStatus::Revert {
684            state.first_reverted_callee.get_or_insert(reverter);
685        }
686        if let Some(assumption) = &assumption
687            && assumed_revert
688            && self.assume_no_revert_matches(
689                state,
690                assumption,
691                assumption.reverted_by.unwrap_or(reverter),
692                &return_data,
693            )?
694        {
695            return_data = SymReturnData::from_concrete_bytes(&mut self.cx, MAGIC_ASSUME.to_vec());
696        }
697        // Like Forge, internal `expectRevert` mode keeps waiting after a successful call.
698        if !assumed_revert
699            && let Some(mut expected) = state.expected_revert.clone()
700            && !(success && executor.internal_expect_revert)
701        {
702            if success {
703                state.expected_revert = None;
704                return_data =
705                    error_string_return_data(&mut self.cx, "next call did not revert as expected");
706            } else {
707                // Like Forge, the reverter is the first call that failed since `vm.expectRevert`,
708                // which is this call unless an earlier one failed.
709                let first_failed_callee = state.first_failed_callee.or(Some(reverter));
710                let reverter = expected.reverted_by(Some(reverter), first_failed_callee);
711                if !self.expected_revert_matches(state, &expected, reverter, &return_data)? {
712                    return Ok(StepOutcome::Failure);
713                }
714                let done = expected.consume_one();
715                state.expected_revert = (!done).then_some(expected);
716                return_data =
717                    SymReturnData::from_concrete_bytes(&mut self.cx, DUMMY_CALL_OUTPUT.to_vec());
718            }
719            success = !success;
720        } else if !success && !assumed_revert {
721            // Like Forge, a failure not consumed here can be the reverter of a pending
722            // `vm.expectRevert`.
723            state.first_failed_callee.get_or_insert(reverter);
724        }
725        // Like Forge, the failure is a bare string; `classify_revert` reads it from the pending
726        // expectation when the revert reaches the top frame.
727        if unmet_expected_emit {
728            success = false;
729            return_data = self.unmet_expected_emit_return_data();
730        }
731        state.return_data = return_data;
732        state.copy_call_output_offset(&mut self.cx, out_offset, out_size)?;
733        let success = SymExpr::constant(&mut self.cx, U256::from(success));
734        state.stack.push(success)?;
735        Ok(StepOutcome::Continue)
736    }
737
738    /// Returns whether a revert matches `vm.assumeNoRevert`, or `Unsupported` when both outcomes
739    /// are feasible.
740    pub(super) fn assume_no_revert_matches(
741        &mut self,
742        state: &PathState,
743        assumption: &AssumeNoRevert,
744        reverter: Address,
745        return_data: &SymReturnData,
746    ) -> Result<bool, SymbolicError> {
747        let Some(filters) = &assumption.filters else {
748            return Ok(true);
749        };
750
751        let conditions = filters
752            .iter()
753            .filter_map(|filter| filter.match_condition(&mut self.cx, Some(reverter), return_data))
754            .collect::<Vec<_>>();
755        if conditions.is_empty() {
756            return Ok(false);
757        }
758
759        let condition = SymBoolExpr::or(&mut self.cx, conditions);
760        let (_, match_sat) = self.constraints_with_condition(state, condition.clone())?;
761        if !match_sat {
762            return Ok(false);
763        }
764
765        let mismatch_condition = condition.not(&mut self.cx);
766        let (_, mismatch_sat) = self.constraints_with_condition(state, mismatch_condition)?;
767        if mismatch_sat {
768            return Err(SymbolicError::Unsupported("ambiguous symbolic vm.assumeNoRevert match"));
769        }
770
771        Ok(true)
772    }
773
774    pub(super) fn constraints_for_condition(
775        &mut self,
776        state: &PathState,
777        condition: SymBoolExpr,
778    ) -> Result<Option<Vec<SymBoolExpr>>, SymbolicError> {
779        let (constraints, sat) = self.constraints_with_condition(state, condition)?;
780        Ok(sat.then_some(constraints))
781    }
782
783    pub(super) fn constraints_with_condition(
784        &mut self,
785        state: &PathState,
786        condition: SymBoolExpr,
787    ) -> Result<(Vec<SymBoolExpr>, bool), SymbolicError> {
788        match condition.as_const() {
789            Some(true) => Ok((state.constraints.clone(), true)),
790            Some(false) => Ok((state.constraints.clone(), false)),
791            None => {
792                let mut constraints = state.constraints.clone();
793                constraints.push(condition);
794                let sat = self.is_sat_with_state(state, &constraints)?;
795                Ok((constraints, sat))
796            }
797        }
798    }
799
800    pub(super) fn take_loop_jump(
801        &self,
802        state: &mut PathState,
803        code: &SymCode,
804        source_pc: usize,
805        dest: usize,
806    ) -> bool {
807        let Some(bound) = self.config.loop_bound else {
808            return true;
809        };
810        if dest >= source_pc {
811            return true;
812        }
813        // Key the back-edge by the return addresses on the stack, so an internal function called
814        // from different sites does not count as one loop. Each address counts once, so the return
815        // address a recursive call pushes again keeps the key and recursion stays bounded.
816        let mut return_pcs = Vec::new();
817        for pc in state
818            .stack
819            .iter()
820            .filter_map(|word| word.as_const().and_then(|word| usize::try_from(word).ok()))
821            .filter(|pc| code.is_valid_jumpdest(*pc).is_ok_and(|valid| valid))
822        {
823            if !return_pcs.contains(&pc) {
824                return_pcs.push(pc);
825            }
826        }
827        let count = state.loop_jumps.entry((dest, return_pcs)).or_default();
828        if *count >= bound {
829            return false;
830        }
831        *count += 1;
832        true
833    }
834
835    pub(super) fn handle_log(
836        &mut self,
837        state: &mut PathState,
838        worklist: &mut VecDeque<PathState>,
839        log: SymbolicLog,
840    ) -> Result<StepOutcome, SymbolicError> {
841        let Some(mut expected) = state.expected_emit.take() else {
842            state.record_log(log);
843            return Ok(StepOutcome::Continue);
844        };
845
846        if let Some(template) = expected.template().cloned() {
847            // Like Forge, a log that does not match keeps the expectation pending for a later
848            // log, so a feasible mismatch continues on its own path.
849            let condition = match expected.match_condition(&mut self.cx, &template, &log) {
850                Some(condition) => condition,
851                None if expected.is_forbidden() => {
852                    return Err(SymbolicError::Unsupported(
853                        "symbolic vm.expectEmit count 0 with symbolic log size",
854                    ));
855                }
856                None => {
857                    // The log may still match, so its mismatch path alone cannot prove the test.
858                    self.defer_incomplete("symbolic vm.expectEmit with symbolic log size");
859                    SymBoolExpr::constant(&mut self.cx, false)
860                }
861            };
862            let (match_constraints, match_sat) =
863                self.constraints_with_condition(state, condition.clone())?;
864            if !match_sat {
865                state.expected_emit = Some(expected);
866                state.record_log(log);
867                return Ok(StepOutcome::Continue);
868            }
869            let mismatch = condition.not(&mut self.cx);
870            if let Some(constraints) = self.constraints_for_condition(state, mismatch)? {
871                let mut mismatch_state = state.clone();
872                mismatch_state.constraints = constraints;
873                mismatch_state.expected_emit = Some(expected.clone());
874                mismatch_state.record_log(log.clone());
875                worklist.push_back(mismatch_state);
876            }
877            state.constraints = match_constraints;
878            if expected.is_forbidden() {
879                // Like Forge, a log matching a `count = 0` expectation reverts the emitting frame.
880                state.expected_emit = Some(expected);
881                return self.revert_expect_emit(state, "log emitted but expected 0 times");
882            }
883            if !expected.consume_one() {
884                state.expected_emit = Some(expected);
885            }
886        } else {
887            // Like Forge, a log without topics cannot fill the template of a non-anonymous
888            // expectation and reverts the emitting frame.
889            if !expected.is_anonymous() && !log.has_topics() {
890                return self.revert_expect_emit(
891                    state,
892                    "use vm.expectEmitAnonymous to match anonymous events",
893                );
894            }
895            expected.set_template(log.clone());
896            state.expected_emit = Some(expected);
897        }
898
899        state.record_log(log);
900        Ok(StepOutcome::Continue)
901    }
902
903    /// Return data of a call that failed the pending `vm.expectEmit`: an ABI-encoded string
904    /// without an error selector, like Forge's `UnmetEmit`. Forge's message depends on the logs,
905    /// so a placeholder stands in and defers incomplete: a caller that inspects it cannot prove a
906    /// path, while an uncaught failure still gives a counterexample.
907    fn unmet_expected_emit_return_data(&mut self) -> SymReturnData {
908        self.defer_incomplete("symbolic vm.expectEmit failure message");
909        let message = sol_data::String::abi_encode("log != expected log");
910        SymReturnData::from_concrete_bytes(&mut self.cx, message)
911    }
912
913    /// Reverts the current frame with a `vm.expectEmit` failure, as Forge does for the emitting
914    /// frame.
915    fn revert_expect_emit(
916        &mut self,
917        state: &mut PathState,
918        reason: &str,
919    ) -> Result<StepOutcome, SymbolicError> {
920        state.return_data = error_string_return_data(&mut self.cx, reason);
921        self.classify_revert(state)
922    }
923
924    #[expect(clippy::too_many_arguments)]
925    pub(super) fn call_concrete_target(
926        &mut self,
927        executor: &ExecutorView<'_>,
928        state: &mut PathState,
929        worklist: &mut VecDeque<PathState>,
930        completed_paths: &mut usize,
931        kind: CallKind,
932        to: Address,
933        target_word: Option<SymExpr>,
934        value: SymExpr,
935        gas: SymExpr,
936        in_offset: SymExpr,
937        in_size: BoundedCopySize,
938        out_offset: SymExpr,
939        out_size: BoundedCopySize,
940    ) -> Result<StepOutcome, SymbolicError> {
941        // Like Forge, only a CALL or STATICCALL reaches a cheatcode. A DELEGATECALL or CALLCODE
942        // runs the cheatcode account's one-byte code instead.
943        let compatibility_cheatcode = if matches!(kind, CallKind::Call | CallKind::StaticCall)
944            && to == SYMBOLIC_VM_COMPAT_ADDRESS
945        {
946            let (_, max_input_size, _) = in_size.parts(&mut self.cx);
947            if max_input_size < 4 {
948                false
949            } else if let Some(offset) = in_offset.as_const() {
950                let offset = usize::try_from(offset).map_err(|_| {
951                    SymbolicError::Unsupported("symbolic compatibility CALL input offset")
952                })?;
953                let selector = state.memory.read_concrete(&mut self.cx, offset, 4)?;
954                let selector: [u8; 4] = selector
955                    .try_into()
956                    .map_err(|_| SymbolicError::Unsupported("symbolic compatibility selector"))?;
957                SymbolicVmCheatcode::from_selector(selector).is_some()
958            } else {
959                // The existing symbolic-offset path checks whether the selector is pinned.
960                true
961            }
962        } else {
963            false
964        };
965        if (matches!(kind, CallKind::Call | CallKind::StaticCall) && to == CHEATCODE_ADDRESS)
966            || compatibility_cheatcode
967        {
968            if !state.constrained_word(&mut self.cx, &value).is_some_and(|value| value.is_zero()) {
969                return Err(SymbolicError::Unsupported("value-bearing cheatcode CALL"));
970            }
971            let (in_size_word, in_size, has_symbolic_in_size) = in_size.parts(&mut self.cx);
972            let has_symbolic_input_offset = in_offset.as_const().is_none();
973            let concrete_in_offset = if has_symbolic_input_offset {
974                None
975            } else {
976                Some(in_offset.as_usize_or("symbolic cheatcode CALL input offset")?)
977            };
978            // Forge fails a cheatcode call whose calldata its ABI decoder rejects.
979            let concrete_input = concrete_in_offset
980                .filter(|_| to == CHEATCODE_ADDRESS && !has_symbolic_in_size)
981                .and_then(|offset| state.memory.read_concrete(&mut self.cx, offset, in_size).ok());
982            if let Some(input) = &concrete_input
983                && let Err(error) = decode_cheatcode_call(input)
984            {
985                let return_data = error_string_return_data(&mut self.cx, &error.to_string());
986                revert_cheatcode_call(&mut self.cx, state, out_offset, &out_size, return_data)?;
987                return Ok(StepOutcome::Continue);
988            }
989            if in_size < 4 {
990                return Err(SymbolicError::Unsupported("short cheatcode CALL"));
991            }
992            // After an allocation of symbolic size the input offset is symbolic, but the input
993            // is still the `in_size` bytes there: read them with the offset bounds.
994            let symbolic_offset_input = has_symbolic_input_offset.then(|| {
995                let minimum_offset = state.lower_bound_usize(&in_offset);
996                let maximum_offset = state.upper_bound_usize(&mut self.cx, &in_offset);
997                state.memory.read_bytes_offset_with_bounds(
998                    &mut self.cx,
999                    in_offset.clone(),
1000                    in_size,
1001                    minimum_offset,
1002                    maximum_offset,
1003                )
1004            });
1005            let selector = if let Some(input) = &symbolic_offset_input {
1006                let selector = input.right_aligned_word(&mut self.cx, 0, 4);
1007                self.constrained_word_with_solver(state, &selector)?
1008                    .map(|selector| selector.to_be_bytes::<32>()[28..].try_into().unwrap())
1009                    .ok_or(SymbolicError::Unsupported("symbolic cheatcode selector"))?
1010            } else {
1011                state
1012                    .memory
1013                    .read_concrete(
1014                        &mut self.cx,
1015                        concrete_in_offset.expect("ordinary cheatcode input offset is concrete"),
1016                        4,
1017                    )?
1018                    .try_into()
1019                    .map_err(|_| SymbolicError::Unsupported("symbolic cheatcode selector"))?
1020            };
1021            let full_word_array_assertion =
1022                to == CHEATCODE_ADDRESS && is_full_word_array_assertion(selector);
1023            let min_size = if to == CHEATCODE_ADDRESS {
1024                foundry_cheatcode_min_input_size(selector)
1025            } else {
1026                symbolic_vm_cheatcode_min_input_size(selector)
1027            };
1028            if has_symbolic_in_size {
1029                let min_size = min_size
1030                    .ok_or(SymbolicError::Unsupported("symbolic cheatcode CALL input size"))?;
1031                if min_size > in_size {
1032                    return Err(SymbolicError::Unsupported("symbolic cheatcode CALL input size"));
1033                }
1034                if !full_word_array_assertion
1035                    && state.lower_bound_usize(&in_size_word) < min_size
1036                    && !self.assume_expr_at_least(state, &in_size_word, min_size)?
1037                {
1038                    return Ok(StepOutcome::AssumeRejected);
1039                }
1040            } else if concrete_input.is_none() && !full_word_array_assertion {
1041                // The decoder needs concrete bytes at a concrete offset. Without it, never read
1042                // arguments past the input, which Forge rejects as too short to decode, and at a
1043                // symbolic offset only accept an input known to hold every argument.
1044                if min_size.is_some_and(|min_size| in_size < min_size) {
1045                    return Err(SymbolicError::Unsupported("short cheatcode CALL"));
1046                }
1047                if has_symbolic_input_offset && min_size.is_none() {
1048                    return Err(SymbolicError::Unsupported("symbolic cheatcode CALL input offset"));
1049                }
1050            }
1051
1052            // The handlers decode the input from memory at a concrete offset. The callee cannot
1053            // see the caller's memory, so an input read at a symbolic offset is decoded from a
1054            // scratch memory that holds it at offset 0; the array assertions read the offset.
1055            let scratch_input =
1056                symbolic_offset_input.filter(|_| !full_word_array_assertion).map(|input| {
1057                    let mut scratch = SymMemory::default();
1058                    scratch.store_bytes(&mut self.cx, 0, input);
1059                    scratch
1060                });
1061            let input_offset = if scratch_input.is_some() { Some(0) } else { concrete_in_offset };
1062
1063            if to == CHEATCODE_ADDRESS
1064                && let Some(input_offset) = input_offset
1065                && let Some(outcome) = self.branch_assume_cheatcode_if_needed(
1066                    state,
1067                    worklist,
1068                    selector,
1069                    scratch_input.as_ref(),
1070                    input_offset,
1071                    out_offset.clone(),
1072                    &out_size,
1073                )?
1074            {
1075                return Ok(outcome);
1076            }
1077
1078            if to == CHEATCODE_ADDRESS
1079                && let Some(concrete_in_offset) = concrete_in_offset
1080                && let Some(outcome) = self.branch_accesses_cheatcode_if_needed(
1081                    state,
1082                    worklist,
1083                    selector,
1084                    concrete_in_offset,
1085                    out_offset.clone(),
1086                    &out_size,
1087                )?
1088            {
1089                return Ok(outcome);
1090            }
1091
1092            if to == CHEATCODE_ADDRESS
1093                && let Some(concrete_in_offset) = concrete_in_offset
1094                && let Some(outcome) = self.deploy_code_cheatcode_if_needed(
1095                    executor,
1096                    state,
1097                    worklist,
1098                    completed_paths,
1099                    selector,
1100                    concrete_in_offset,
1101                    out_offset.clone(),
1102                    &out_size,
1103                )?
1104            {
1105                return Ok(outcome);
1106            }
1107
1108            if to == CHEATCODE_ADDRESS
1109                && let Some(concrete_in_offset) = concrete_in_offset
1110                && let Some(outcome) = self.bound_cheatcode_if_needed(
1111                    state,
1112                    worklist,
1113                    selector,
1114                    concrete_in_offset,
1115                    out_offset.clone(),
1116                    &out_size,
1117                )?
1118            {
1119                return Ok(outcome);
1120            }
1121
1122            if to == CHEATCODE_ADDRESS
1123                && let Some(input_offset) = input_offset
1124                && let Some(outcome) = self.branch_cheatcode_argument_check_if_needed(
1125                    executor,
1126                    state,
1127                    worklist,
1128                    selector,
1129                    scratch_input.as_ref(),
1130                    input_offset,
1131                    &out_offset,
1132                    &out_size,
1133                )?
1134            {
1135                return Ok(outcome);
1136            }
1137
1138            let caller_memory =
1139                scratch_input.map(|scratch| std::mem::replace(&mut state.memory, scratch));
1140            let (in_offset, concrete_in_offset) = if caller_memory.is_some() {
1141                (SymExpr::zero(&mut self.cx), Some(0))
1142            } else {
1143                (in_offset, concrete_in_offset)
1144            };
1145            let outcome = if to == CHEATCODE_ADDRESS {
1146                self.handle_foundry_cheatcode(
1147                    executor,
1148                    state,
1149                    selector,
1150                    &in_offset,
1151                    &in_size_word,
1152                    in_size,
1153                )
1154            } else if to == SYMBOLIC_VM_COMPAT_ADDRESS {
1155                self.handle_symbolic_vm_cheatcode(
1156                    executor,
1157                    state,
1158                    selector,
1159                    concrete_in_offset.expect("symbolic vm input offset is concrete"),
1160                )
1161                .inspect(|outcome| {
1162                    if let CheatcodeOutcome::ContinueData(ret) = outcome {
1163                        state.svm_returns.push(ret.clone());
1164                    }
1165                })
1166            } else {
1167                Err(SymbolicError::Unsupported("symbolic cheatcode address"))
1168            };
1169            if let Some(memory) = caller_memory {
1170                state.memory = memory;
1171            }
1172            let return_data = match outcome? {
1173                CheatcodeOutcome::Continue(ret) => SymReturnData::from_words(&mut self.cx, ret),
1174                CheatcodeOutcome::ContinueData(ret) => ret,
1175                CheatcodeOutcome::Revert(ret) => {
1176                    revert_cheatcode_call(&mut self.cx, state, out_offset, &out_size, ret)?;
1177                    return Ok(StepOutcome::Continue);
1178                }
1179                CheatcodeOutcome::Failure => return Ok(StepOutcome::Failure),
1180                CheatcodeOutcome::Fork { mut passing, revert } => {
1181                    // The cheatcode only read memory, so the passing branch gets the caller's.
1182                    passing.memory = state.memory.clone();
1183                    let empty = SymReturnData::empty(&mut self.cx);
1184                    complete_cheatcode_call(
1185                        &mut self.cx,
1186                        &mut passing,
1187                        out_offset.clone(),
1188                        &out_size,
1189                        empty,
1190                    )?;
1191                    worklist.push_back(*passing);
1192                    match revert {
1193                        Some(ret) => {
1194                            revert_cheatcode_call(&mut self.cx, state, out_offset, &out_size, ret)?;
1195                            return Ok(StepOutcome::Continue);
1196                        }
1197                        None => SymReturnData::from_words(&mut self.cx, Vec::new()),
1198                    }
1199                }
1200                CheatcodeOutcome::Choices(choices) => {
1201                    let mut choices = choices.into_iter();
1202                    let (constraints, return_data) = choices.next().expect("nonempty choices");
1203                    // Only `svm.createCalldata` returns choices, and replay answers it on each
1204                    // path with that path's own return data.
1205                    for (choice_constraints, choice_return_data) in choices {
1206                        let mut choice = state.clone();
1207                        choice.constraints.extend(choice_constraints);
1208                        choice.svm_returns.push(choice_return_data.clone());
1209                        complete_cheatcode_call(
1210                            &mut self.cx,
1211                            &mut choice,
1212                            out_offset.clone(),
1213                            &out_size,
1214                            choice_return_data,
1215                        )?;
1216                        worklist.push_back(choice);
1217                    }
1218                    state.constraints.extend(constraints);
1219                    state.svm_returns.push(return_data.clone());
1220                    return_data
1221                }
1222            };
1223
1224            state.return_data = return_data;
1225            state.copy_call_output_offset(&mut self.cx, out_offset, &out_size)?;
1226            state.stack.push(SymExpr::one(&mut self.cx))?;
1227            return Ok(StepOutcome::Continue);
1228        }
1229
1230        if to == HARDHAT_CONSOLE_ADDRESS {
1231            // Forge's console inspector reverts a call it cannot decode. It only sees calls whose
1232            // destination is the console address, so DELEGATECALL and CALLCODE run the console's
1233            // empty code instead.
1234            let error = if matches!(kind, CallKind::Call | CallKind::StaticCall) {
1235                in_size
1236                    .read_from_memory(&mut self.cx, &state.memory, in_offset)
1237                    .concrete_bytes(&mut self.cx, "symbolic console input")
1238                    .ok()
1239                    .and_then(|input| console::hh::ConsoleCalls::abi_decode(&input).err())
1240            } else {
1241                None
1242            };
1243            state.return_data = match &error {
1244                Some(error) => {
1245                    state.first_failed_callee.get_or_insert(HARDHAT_CONSOLE_ADDRESS);
1246                    SymReturnData::from_concrete_bytes(
1247                        &mut self.cx,
1248                        error.abi_encode_revert().into(),
1249                    )
1250                }
1251                None => SymReturnData::empty(&mut self.cx),
1252            };
1253            state.copy_call_output_offset(&mut self.cx, out_offset, &out_size)?;
1254            state.stack.push(SymExpr::constant(&mut self.cx, U256::from(error.is_none())))?;
1255            return Ok(StepOutcome::Continue);
1256        }
1257
1258        let call_input = in_size.read_from_memory(&mut self.cx, &state.memory, in_offset.clone());
1259        // `vm.mockFunction` swaps the code that runs, and the concrete inspector matches
1260        // `vm.expectCall` against that address, so resolve the redirect before observing.
1261        let function_mock = if self.function_mock_may_match(executor, state, to, &call_input)? {
1262            let callee = self.call_code_account(executor, state, to)?;
1263            self.function_mock_target(state, callee, &call_input)?
1264        } else {
1265            None
1266        };
1267        let code_address = function_mock.unwrap_or(to);
1268        if !state.expected_calls.is_empty() {
1269            let concrete_value = self.transfer_value(state, kind, &value);
1270            if !self.observe_expected_call(
1271                state,
1272                code_address,
1273                concrete_value,
1274                &gas,
1275                &call_input,
1276            )? {
1277                return Ok(StepOutcome::Failure);
1278            }
1279        }
1280        let inherited_prank = state.callers();
1281        let call_context =
1282            (!matches!(kind, CallKind::DelegateCall)).then(|| state.prank_for_next_call());
1283        // An isolated CALL is its own transaction, so it bumps the caller's nonce even when the
1284        // call fails. Concrete Forge answers a mocked call before isolating it.
1285        let isolated =
1286            matches!(kind, CallKind::Call) && state.starts_isolated_transaction(executor);
1287        // Like Forge's `CallInputs::transfer_to`, also the account a codeless call reverts as.
1288        let transfer_to = if matches!(kind, CallKind::DelegateCall | CallKind::CallCode) {
1289            state.address
1290        } else {
1291            to
1292        };
1293        if matches!(kind, CallKind::Call | CallKind::CallCode) {
1294            let call_caller = call_context.as_ref().expect("value calls have a call context").0;
1295            if isolated && !self.has_call_mock(state, code_address, &value, &call_input)? {
1296                state.world.increment_nonce(executor, call_caller)?;
1297            }
1298            if let Some(outcome) = self.prepare_value_transfer(
1299                executor,
1300                state,
1301                worklist,
1302                kind,
1303                call_caller,
1304                transfer_to,
1305                value.clone(),
1306                out_offset.clone(),
1307                &out_size,
1308            )? {
1309                return Ok(outcome);
1310            }
1311        }
1312        if !state.call_mocks.is_empty() {
1313            let concrete_value = self.transfer_value(state, kind, &value);
1314            if let Some(mock) =
1315                self.take_call_mock(state, code_address, concrete_value, &call_input)?
1316            {
1317                let (return_data, reverts) = mock.into_parts();
1318                if !reverts && let Some((call_caller, _, _)) = call_context {
1319                    self.apply_call_value_transfer(executor, state, kind, to, call_caller, value)?;
1320                }
1321                return self.finish_codeless_call(
1322                    executor,
1323                    state,
1324                    kind,
1325                    if reverts { CallStatus::Revert } else { CallStatus::Success },
1326                    return_data,
1327                    transfer_to,
1328                    out_offset,
1329                    &out_size,
1330                );
1331            }
1332        }
1333        if matches!(kind, CallKind::DelegateCall) && state.prank.has_active() {
1334            return Err(SymbolicError::Unsupported("symbolic prank delegatecall"));
1335        }
1336        let (call_caller, call_caller_word, pranked_origin) =
1337            call_context.unwrap_or_else(|| state.prank_for_next_call());
1338
1339        // A call beyond the call depth limit fails before it transfers value or runs
1340        // any code, including a precompile.
1341        if state.at_call_depth_limit() {
1342            let return_data = SymReturnData::empty(&mut self.cx);
1343            return self.finish_codeless_call(
1344                executor,
1345                state,
1346                kind,
1347                CallStatus::Revert,
1348                return_data,
1349                transfer_to,
1350                out_offset,
1351                &out_size,
1352            );
1353        }
1354
1355        let spec_id = executor.spec_id;
1356        if is_precompile_for_spec(code_address, spec_id) {
1357            let input_len = in_size.size_word(&mut self.cx);
1358            let input = in_size.read_from_memory(&mut self.cx, &state.memory, in_offset);
1359            if precompile_number_for_spec(code_address, spec_id) == Some(10) {
1360                let input_bytes = input.materialize(&mut self.cx);
1361                return self.execute_kzg_precompile_call(
1362                    executor,
1363                    state,
1364                    worklist,
1365                    kind,
1366                    to,
1367                    call_caller,
1368                    value,
1369                    out_offset,
1370                    &out_size,
1371                    input_bytes,
1372                    input_len,
1373                );
1374            }
1375            let gas = self.precompile_gas(executor, state, kind, &value);
1376            // A path can pin a symbolic input to one value, as `if (a == 1)` does before
1377            // `sha256(abi.encode(a))`: run the precompile on that value so the result is exact
1378            // and a counterexample replays, instead of an opaque term over the pinned bytes.
1379            let pinned_input = input_len
1380                .as_const()
1381                .and_then(|len| usize::try_from(len).ok())
1382                .filter(|len| *len <= input.len())
1383                .and_then(|len| {
1384                    let bytes = input.materialize(&mut self.cx);
1385                    let symbolic = bytes[..len].iter().any(|byte| byte.as_const().is_none());
1386                    constrained_bytes_at(&mut self.cx, state, &bytes, 0, len)
1387                        .map(|pinned| (pinned, symbolic))
1388                });
1389            let outcome = match &pinned_input {
1390                Some((pinned, _)) => {
1391                    execute_precompile(&mut self.cx, code_address, pinned, spec_id, gas)?
1392                }
1393                None => execute_symbolic_precompile(
1394                    &mut self.cx,
1395                    code_address,
1396                    input.clone(),
1397                    input_len.clone(),
1398                    spec_id,
1399                    gas,
1400                )?,
1401            };
1402            // A malformed signature returns no data, which replay reproduces exactly, while a
1403            // well-formed one keeps the opaque recovery model. Prefer a malformed witness.
1404            if pinned_input.is_none()
1405                && precompile_number_for_spec(code_address, spec_id) == Some(1)
1406            {
1407                let sized = SymBytes::sized(&mut self.cx, input.clone(), input_len.clone(), 128);
1408                let malformed =
1409                    ecrecover_signature_well_formed(&mut self.cx, &sized).not(&mut self.cx);
1410                if malformed.as_const().is_none() {
1411                    state.witness_preferences.push(malformed);
1412                }
1413            }
1414            // An earlier call over the same symbolic input keeps its opaque term, so tie that term
1415            // to the result: repeated-call equality must survive the guard that pinned the input.
1416            // A constant input has no such term.
1417            if let Some((_, true)) = &pinned_input
1418                && let Some(concrete) = &outcome
1419                && let Ok(Some(symbolic)) = execute_symbolic_precompile(
1420                    &mut self.cx,
1421                    code_address,
1422                    input,
1423                    input_len,
1424                    spec_id,
1425                    gas,
1426                )
1427            {
1428                let len_eq = SymBoolExpr::eq(
1429                    &mut self.cx,
1430                    symbolic.len_word.clone(),
1431                    concrete.len_word.clone(),
1432                );
1433                let mut ties = vec![len_eq];
1434                for offset in (0..concrete.len()).step_by(32) {
1435                    let modeled = symbolic.bytes.word_at(&mut self.cx, offset);
1436                    let actual = concrete.bytes.word_at(&mut self.cx, offset);
1437                    ties.push(SymBoolExpr::eq(&mut self.cx, modeled, actual));
1438                }
1439                state
1440                    .constraints
1441                    .extend(ties.into_iter().filter(|equal| equal.as_const() != Some(true)));
1442            }
1443            return self.apply_precompile_outcome(
1444                executor,
1445                state,
1446                kind,
1447                to,
1448                call_caller,
1449                value,
1450                out_offset,
1451                &out_size,
1452                outcome,
1453            );
1454        }
1455
1456        // Like the concrete inspector, a mock target's own delegation is not resolved.
1457        let code_address = match function_mock {
1458            Some(mock) => mock,
1459            None => self.call_code_account(executor, state, to)?,
1460        };
1461        if self.equivalence.is_some()
1462            && state.world.is_unknown_account(&mut self.cx, executor, code_address)?
1463        {
1464            let target =
1465                target_word.unwrap_or_else(|| SymExpr::constant(&mut self.cx, address_word(to)));
1466            let input_len = in_size.size_word(&mut self.cx);
1467            return self.call_unknown_code(
1468                executor,
1469                state,
1470                kind,
1471                to,
1472                call_caller,
1473                target,
1474                value,
1475                call_input,
1476                input_len,
1477                out_offset,
1478                &out_size,
1479            );
1480        }
1481
1482        let child_code = state.world.extcode(&mut self.cx, executor, code_address)?;
1483        if child_code.is_empty() {
1484            self.apply_call_value_transfer(executor, state, kind, to, call_caller, value)?;
1485            let return_data = SymReturnData::empty(&mut self.cx);
1486            return self.finish_codeless_call(
1487                executor,
1488                state,
1489                kind,
1490                CallStatus::Success,
1491                return_data,
1492                transfer_to,
1493                out_offset,
1494                &out_size,
1495            );
1496        }
1497
1498        let calldata = in_size.calldata(&mut self.cx, call_input);
1499        let callee_address_word = state
1500            .world
1501            .symbolic_word_for_address(to)
1502            .or_else(|| {
1503                target_word
1504                    .as_ref()
1505                    .filter(|expr| state.world.resolve_address(expr) == Some(to))
1506                    .cloned()
1507            })
1508            .unwrap_or_else(|| SymExpr::constant(&mut self.cx, address_word(to)));
1509        let frame = match kind {
1510            CallKind::Call => {
1511                let mut frame = CallFrame::new(
1512                    &mut self.cx,
1513                    to,
1514                    to,
1515                    call_caller,
1516                    value.clone(),
1517                    state.is_static,
1518                    calldata,
1519                );
1520                frame.address_word = callee_address_word;
1521                frame.caller_word = call_caller_word;
1522                frame
1523            }
1524            CallKind::StaticCall => {
1525                let value = SymExpr::zero(&mut self.cx);
1526                let mut frame =
1527                    CallFrame::new(&mut self.cx, to, to, call_caller, value, true, calldata);
1528                frame.address_word = callee_address_word;
1529                frame.caller_word = call_caller_word;
1530                frame
1531            }
1532            CallKind::DelegateCall => {
1533                let mut frame = CallFrame::new(
1534                    &mut self.cx,
1535                    state.address,
1536                    state.storage_address,
1537                    state.caller,
1538                    state.callvalue.clone(),
1539                    state.is_static,
1540                    calldata,
1541                );
1542                frame.address_word = state.address_word.clone();
1543                frame.caller_word = state.caller_word.clone();
1544                frame
1545            }
1546            CallKind::CallCode => {
1547                let mut frame = CallFrame::new(
1548                    &mut self.cx,
1549                    state.address,
1550                    state.storage_address,
1551                    call_caller,
1552                    value.clone(),
1553                    state.is_static,
1554                    calldata,
1555                );
1556                frame.address_word = state.address_word.clone();
1557                frame.caller_word = call_caller_word;
1558                frame
1559            }
1560        };
1561
1562        let original_world = state.world.clone();
1563        let mut child = state.child(frame);
1564        child.prank.inherited = inherited_prank;
1565        if isolated {
1566            child.world.clear_transient_storage();
1567            child.call_depth_base = child.call_depth;
1568        }
1569        if let Some((origin, origin_word)) = pranked_origin {
1570            child.origin = origin;
1571            child.origin_word = origin_word;
1572        }
1573        self.apply_call_value_transfer(executor, &mut child, kind, to, call_caller, value)?;
1574        let outcomes = self.execute_external_call(executor, child, &child_code, completed_paths)?;
1575        if outcomes.is_empty() {
1576            return Ok(StepOutcome::AssumeRejected);
1577        }
1578
1579        let assume_no_revert = state.assume_no_revert_next_call.take();
1580        let mut parents = VecDeque::with_capacity(outcomes.len());
1581        for mut outcome in outcomes {
1582            let failed_callee =
1583                (!matches!(outcome.status, CallStatus::Success)).then_some(outcome.state.address);
1584            if matches!(outcome.status, CallStatus::Revert) {
1585                outcome.state.first_reverted_callee.get_or_insert(outcome.state.address);
1586            }
1587            match self.join_call_outcome(
1588                executor,
1589                state,
1590                &original_world,
1591                outcome,
1592                failed_callee,
1593                assume_no_revert.as_ref(),
1594            )? {
1595                JoinedCallOutcome::Failure(parent) => {
1596                    *state = parent;
1597                    return Ok(StepOutcome::Failure);
1598                }
1599                JoinedCallOutcome::ExceptionalHalt(mut parent) => {
1600                    parent.return_data = if parent.check_expected_emit_after_call(kind) {
1601                        self.unmet_expected_emit_return_data()
1602                    } else {
1603                        SymReturnData::empty(&mut self.cx)
1604                    };
1605                    parent.copy_call_output_offset(&mut self.cx, out_offset.clone(), &out_size)?;
1606                    parent.stack.push(SymExpr::zero(&mut self.cx))?;
1607                    parents.push_back(parent);
1608                }
1609                JoinedCallOutcome::ExpectedRevert(mut parent) => {
1610                    parent.return_data = SymReturnData::from_concrete_bytes(
1611                        &mut self.cx,
1612                        DUMMY_CALL_OUTPUT.to_vec(),
1613                    );
1614                    parent.copy_call_output_offset(&mut self.cx, out_offset.clone(), &out_size)?;
1615                    parent.stack.push(SymExpr::one(&mut self.cx))?;
1616                    parents.push_back(parent);
1617                }
1618                JoinedCallOutcome::Success { mut parent, child, unmet_expected_revert } => {
1619                    parent.world = child.world;
1620                    if isolated {
1621                        parent.world.restore_transient_storage(&original_world);
1622                    }
1623                    let unmet_expected_emit = unmet_expected_revert.is_none()
1624                        && parent.check_expected_emit_after_call(kind);
1625                    parent.return_data = match unmet_expected_revert {
1626                        Some(reason) => error_string_return_data(&mut self.cx, reason),
1627                        None if unmet_expected_emit => self.unmet_expected_emit_return_data(),
1628                        None => child.frame.return_data,
1629                    };
1630                    parent.copy_call_output_offset(&mut self.cx, out_offset.clone(), &out_size)?;
1631                    let success = SymExpr::constant(
1632                        &mut self.cx,
1633                        U256::from(unmet_expected_revert.is_none() && !unmet_expected_emit),
1634                    );
1635                    parent.stack.push(success)?;
1636                    parents.push_back(parent);
1637                }
1638                JoinedCallOutcome::Revert { mut parent, child } => {
1639                    parent.return_data = child.frame.return_data;
1640                    parent.copy_call_output_offset(&mut self.cx, out_offset.clone(), &out_size)?;
1641                    parent.stack.push(SymExpr::zero(&mut self.cx))?;
1642                    parents.push_back(parent);
1643                }
1644            }
1645        }
1646
1647        Ok(self.resume_parent_paths(state, worklist, parents))
1648    }
1649
1650    #[expect(clippy::too_many_arguments)]
1651    fn execute_kzg_precompile_call(
1652        &mut self,
1653        executor: &ExecutorView<'_>,
1654        state: &mut PathState,
1655        worklist: &mut VecDeque<PathState>,
1656        kind: CallKind,
1657        to: Address,
1658        call_caller: Address,
1659        value: SymExpr,
1660        out_offset: SymExpr,
1661        out_size: &BoundedCopySize,
1662        input: Vec<SymExpr>,
1663        input_len: SymExpr,
1664    ) -> Result<StepOutcome, SymbolicError> {
1665        let gas = self.precompile_gas(executor, state, kind, &value);
1666        if let Some(outcome) =
1667            kzg_constrained_outcome(&mut self.cx, state, &input, &input_len, gas)?
1668        {
1669            return self.apply_precompile_outcome(
1670                executor,
1671                state,
1672                kind,
1673                to,
1674                call_caller,
1675                value,
1676                out_offset,
1677                out_size,
1678                outcome,
1679            );
1680        }
1681
1682        let success_condition = kzg_success_witness_condition(&mut self.cx, &input, &input_len);
1683        let failure_condition =
1684            kzg_failure_witness_condition(&mut self.cx, state, &input, &input_len);
1685        let modeled_condition = SymBoolExpr::or(
1686            &mut self.cx,
1687            vec![success_condition.clone(), failure_condition.clone()],
1688        );
1689        let modeled_condition = modeled_condition.not(&mut self.cx);
1690        let (_, residual_sat) = self.constraints_with_condition(state, modeled_condition)?;
1691        if residual_sat {
1692            self.defer_incomplete(KZG_RESIDUAL_REASON);
1693        }
1694
1695        let (success_constraints, success_sat) =
1696            self.constraints_with_condition(state, success_condition)?;
1697
1698        let (failure_constraints, failure_sat) =
1699            self.constraints_with_condition(state, failure_condition)?;
1700
1701        match (success_sat, failure_sat) {
1702            (true, true) => {
1703                let mut failure = state.clone();
1704                failure.constraints = failure_constraints;
1705                match self.apply_precompile_outcome(
1706                    executor,
1707                    &mut failure,
1708                    kind,
1709                    to,
1710                    call_caller,
1711                    value.clone(),
1712                    out_offset.clone(),
1713                    out_size,
1714                    None,
1715                )? {
1716                    StepOutcome::Continue => worklist.push_back(failure),
1717                    outcome => {
1718                        *state = failure;
1719                        return Ok(outcome);
1720                    }
1721                }
1722
1723                state.constraints = success_constraints;
1724                let return_data = kzg_success_return_data(&mut self.cx);
1725                self.apply_precompile_outcome(
1726                    executor,
1727                    state,
1728                    kind,
1729                    to,
1730                    call_caller,
1731                    value,
1732                    out_offset,
1733                    out_size,
1734                    Some(return_data),
1735                )
1736            }
1737            (true, false) => {
1738                state.constraints = success_constraints;
1739                let return_data = kzg_success_return_data(&mut self.cx);
1740                self.apply_precompile_outcome(
1741                    executor,
1742                    state,
1743                    kind,
1744                    to,
1745                    call_caller,
1746                    value,
1747                    out_offset,
1748                    out_size,
1749                    Some(return_data),
1750                )
1751            }
1752            (false, true) => {
1753                state.constraints = failure_constraints;
1754                self.apply_precompile_outcome(
1755                    executor,
1756                    state,
1757                    kind,
1758                    to,
1759                    call_caller,
1760                    value,
1761                    out_offset,
1762                    out_size,
1763                    None,
1764                )
1765            }
1766            (false, false) => Err(SymbolicError::Unsupported(KZG_RESIDUAL_REASON)),
1767        }
1768    }
1769
1770    /// Returns the gas a `gasleft()` call gives a precompile, with the value transfer stipend when
1771    /// the call may send value.
1772    fn precompile_gas(
1773        &mut self,
1774        executor: &ExecutorView<'_>,
1775        state: &PathState,
1776        kind: CallKind,
1777        value: &SymExpr,
1778    ) -> u64 {
1779        let sends_value = matches!(kind, CallKind::Call | CallKind::CallCode)
1780            && state.constrained_word(&mut self.cx, value).is_none_or(|value| !value.is_zero());
1781        precompile_call_gas(executor.gas_limit, sends_value)
1782    }
1783
1784    #[expect(clippy::too_many_arguments)]
1785    /// Applies a precompile call result to the current symbolic state.
1786    fn apply_precompile_outcome(
1787        &mut self,
1788        executor: &ExecutorView<'_>,
1789        state: &mut PathState,
1790        kind: CallKind,
1791        to: Address,
1792        call_caller: Address,
1793        value: SymExpr,
1794        out_offset: SymExpr,
1795        out_size: &BoundedCopySize,
1796        outcome: Option<SymReturnData>,
1797    ) -> Result<StepOutcome, SymbolicError> {
1798        let reverter = if matches!(kind, CallKind::DelegateCall | CallKind::CallCode) {
1799            state.address
1800        } else {
1801            to
1802        };
1803        let (status, return_data) = match outcome {
1804            Some(return_data) => {
1805                self.apply_call_value_transfer(executor, state, kind, to, call_caller, value)?;
1806                (CallStatus::Success, return_data)
1807            }
1808            None => (CallStatus::ExceptionalHalt, SymReturnData::empty(&mut self.cx)),
1809        };
1810        self.finish_codeless_call(
1811            executor,
1812            state,
1813            kind,
1814            status,
1815            return_data,
1816            reverter,
1817            out_offset,
1818            out_size,
1819        )
1820    }
1821
1822    fn apply_call_value_transfer(
1823        &mut self,
1824        executor: &ExecutorView<'_>,
1825        state: &mut PathState,
1826        kind: CallKind,
1827        to: Address,
1828        from: Address,
1829        value: SymExpr,
1830    ) -> Result<(), SymbolicError> {
1831        let to = match kind {
1832            CallKind::Call => to,
1833            CallKind::CallCode => state.address,
1834            CallKind::DelegateCall | CallKind::StaticCall => return Ok(()),
1835        };
1836        state.world.transfer(&mut self.cx, executor, from, to, value, true)
1837    }
1838
1839    #[expect(clippy::too_many_arguments)]
1840    pub(super) fn prepare_value_transfer(
1841        &mut self,
1842        executor: &ExecutorView<'_>,
1843        state: &mut PathState,
1844        worklist: &mut VecDeque<PathState>,
1845        kind: CallKind,
1846        from: Address,
1847        to: Address,
1848        value: SymExpr,
1849        out_offset: SymExpr,
1850        out_size: &BoundedCopySize,
1851    ) -> Result<Option<StepOutcome>, SymbolicError> {
1852        if state.constrained_word(&mut self.cx, &value).is_some_and(|value| value.is_zero()) {
1853            return Ok(None);
1854        }
1855
1856        // A sender balance below `value` fails the call with an `OutOfFunds` revert.
1857        let balance = state.balance(&mut self.cx, executor, from)?;
1858        let can_transfer = SymBoolExpr::cmp(&mut self.cx, SymCmpOp::Uge, balance, value);
1859        if can_transfer.as_const() == Some(true) {
1860            return Ok(None);
1861        }
1862
1863        let cannot_transfer = can_transfer.clone().not(&mut self.cx);
1864        let success_constraints = self.constraints_for_condition(state, can_transfer)?;
1865        let Some(failure_constraints) = self.constraints_for_condition(state, cannot_transfer)?
1866        else {
1867            let Some(constraints) = success_constraints else {
1868                return Ok(Some(StepOutcome::AssumeRejected));
1869            };
1870            state.constraints = constraints;
1871            return Ok(None);
1872        };
1873        let mut failure = state.clone();
1874        failure.constraints = failure_constraints;
1875        let return_data = SymReturnData::empty(&mut self.cx);
1876        let outcome = self.finish_codeless_call(
1877            executor,
1878            &mut failure,
1879            kind,
1880            CallStatus::Revert,
1881            return_data,
1882            to,
1883            out_offset,
1884            out_size,
1885        )?;
1886        match success_constraints {
1887            Some(constraints) if matches!(outcome, StepOutcome::Continue) => {
1888                worklist.push_back(failure);
1889                state.constraints = constraints;
1890                Ok(None)
1891            }
1892            // Without a feasible transfer, or when the failure ends execution, the failure
1893            // continues on this path.
1894            _ => {
1895                *state = failure;
1896                Ok(Some(outcome))
1897            }
1898        }
1899    }
1900
1901    pub(super) fn prepare_create_value_transfer(
1902        &mut self,
1903        executor: &ExecutorView<'_>,
1904        state: &mut PathState,
1905        worklist: &mut VecDeque<PathState>,
1906        from: Address,
1907        value: SymExpr,
1908    ) -> Result<bool, SymbolicError> {
1909        if state.constrained_word(&mut self.cx, &value).is_some_and(|value| value.is_zero()) {
1910            return Ok(true);
1911        }
1912
1913        let balance = state.balance(&mut self.cx, executor, from)?;
1914        let can_pay = SymBoolExpr::cmp(&mut self.cx, SymCmpOp::Uge, balance, value);
1915        match can_pay.as_const() {
1916            Some(true) => Ok(true),
1917            Some(false) => {
1918                self.fail_create_before_frame(executor, state)?;
1919                Ok(false)
1920            }
1921            None => {
1922                let mut success_constraints = state.constraints.clone();
1923                success_constraints.push(can_pay.clone());
1924                let success_sat = self.is_sat_with_state(state, &success_constraints)?;
1925
1926                let mut failure_constraints = state.constraints.clone();
1927                failure_constraints.push(can_pay.not(&mut self.cx));
1928                let failure_sat = self.is_sat_with_state(state, &failure_constraints)?;
1929
1930                match (success_sat, failure_sat) {
1931                    (true, true) => {
1932                        let mut failure = state.clone();
1933                        failure.constraints = failure_constraints;
1934                        self.fail_create_before_frame(executor, &mut failure)?;
1935                        worklist.push_back(failure);
1936
1937                        state.constraints = success_constraints;
1938                        Ok(true)
1939                    }
1940                    (true, false) => {
1941                        state.constraints = success_constraints;
1942                        Ok(true)
1943                    }
1944                    (false, true) => {
1945                        state.constraints = failure_constraints;
1946                        self.fail_create_before_frame(executor, state)?;
1947                        Ok(false)
1948                    }
1949                    (false, false) => Ok(false),
1950                }
1951            }
1952        }
1953    }
1954
1955    #[expect(clippy::too_many_arguments)]
1956    pub(super) fn call_symbolic_target(
1957        &mut self,
1958        executor: &ExecutorView<'_>,
1959        state: &mut PathState,
1960        worklist: &mut VecDeque<PathState>,
1961        completed_paths: &mut usize,
1962        kind: CallKind,
1963        target: SymExpr,
1964        value: SymExpr,
1965        gas: SymExpr,
1966        in_offset: SymExpr,
1967        in_size: BoundedCopySize,
1968        out_offset: SymExpr,
1969        out_size: BoundedCopySize,
1970    ) -> Result<StepOutcome, SymbolicError> {
1971        let mut candidates = state.world.symbolic_call_targets(&mut self.cx, executor)?;
1972        candidates.push(SYMBOLIC_VM_COMPAT_ADDRESS);
1973        if matches!(kind, CallKind::DelegateCall | CallKind::CallCode) {
1974            candidates.push(CHEATCODE_ADDRESS);
1975        }
1976        // An equivalence check abstracts a target that is no known contract as one unknown
1977        // function of the call's inputs, which also covers every precompile.
1978        if self.equivalence.is_none() {
1979            candidates.extend(active_precompiles(executor.spec_id).as_map().addresses());
1980        }
1981        candidates.sort();
1982        candidates.dedup();
1983
1984        let candidate_constraints = candidates
1985            .iter()
1986            .map(|address| state.world.symbolic_address_condition(&mut self.cx, &target, *address))
1987            .collect::<Vec<_>>();
1988        // Only the real cheatcode address uses Forge's decoder. The compatibility address is an
1989        // ordinary call target unless its selector names a symbolic-VM operation.
1990        let cheatcode_condition =
1991            matches!(kind, CallKind::Call | CallKind::StaticCall).then(|| {
1992                let address = SymExpr::constant(&mut self.cx, address_word(CHEATCODE_ADDRESS));
1993                SymBoolExpr::eq(&mut self.cx, target.clone(), address)
1994            });
1995        let mut outside_constraints = state.constraints.clone();
1996        outside_constraints.extend(
1997            candidate_constraints
1998                .iter()
1999                .chain(cheatcode_condition.iter())
2000                .cloned()
2001                .map(|condition| condition.not(&mut self.cx)),
2002        );
2003        let outside_sat = self.is_sat_with_state(state, &outside_constraints)?;
2004
2005        if !self.config.symbolic_call_targets && self.equivalence.is_none() && outside_sat {
2006            return Err(SymbolicError::Unsupported("symbolic CALL target"));
2007        }
2008
2009        let mut parents = VecDeque::new();
2010        if outside_sat {
2011            let mut branch = state.clone();
2012            branch.constraints = outside_constraints;
2013
2014            if matches!(kind, CallKind::DelegateCall) && branch.prank.has_active() {
2015                return Err(SymbolicError::Unsupported("symbolic prank delegatecall"));
2016            }
2017            let (call_caller, _, _) = branch.prank_for_next_call();
2018            if matches!(kind, CallKind::Call) && branch.starts_isolated_transaction(executor) {
2019                branch.world.increment_nonce(executor, call_caller)?;
2020            }
2021            let mut outcome = None;
2022            if branch.at_call_depth_limit() {
2023                // Beyond the call depth limit the call fails before it transfers value. A
2024                // pending revert cheatcode would match against a symbolic reverter.
2025                if branch.expected_revert.is_some() || branch.assume_no_revert_next_call.is_some() {
2026                    return Err(SymbolicError::Unsupported(
2027                        "revert cheatcode on a symbolic CALL target beyond the call depth limit",
2028                    ));
2029                }
2030                branch.return_data = SymReturnData::empty(&mut self.cx);
2031                branch.copy_call_output_offset(&mut self.cx, out_offset.clone(), &out_size)?;
2032                branch.stack.push(SymExpr::zero(&mut self.cx))?;
2033                outcome = Some(StepOutcome::Continue);
2034            } else if self.equivalence.is_some() {
2035                // A target that is none of the known contracts is unknown code.
2036                let to = branch.world.symbolic_address_slot(target.clone());
2037                if matches!(kind, CallKind::Call) {
2038                    outcome = self.prepare_value_transfer(
2039                        executor,
2040                        &mut branch,
2041                        &mut parents,
2042                        kind,
2043                        call_caller,
2044                        to,
2045                        value.clone(),
2046                        out_offset.clone(),
2047                        &out_size,
2048                    )?;
2049                }
2050                if outcome.is_none() {
2051                    let input =
2052                        in_size.read_from_memory(&mut self.cx, &branch.memory, in_offset.clone());
2053                    let input_len = in_size.size_word(&mut self.cx);
2054                    outcome = Some(self.call_unknown_code(
2055                        executor,
2056                        &mut branch,
2057                        kind,
2058                        to,
2059                        call_caller,
2060                        target,
2061                        value.clone(),
2062                        input,
2063                        input_len,
2064                        out_offset.clone(),
2065                        &out_size,
2066                    )?);
2067                }
2068            } else if matches!(kind, CallKind::Call | CallKind::CallCode) {
2069                let transfer_to = if matches!(kind, CallKind::Call) {
2070                    // A failed transfer would report this placeholder, not the symbolic target, as
2071                    // the reverter.
2072                    if branch.expected_revert.as_ref().is_some_and(ExpectedRevert::has_reverter) {
2073                        return Err(SymbolicError::Unsupported(
2074                            "symbolic vm.expectRevert reverter on symbolic CALL target",
2075                        ));
2076                    }
2077                    branch.world.symbolic_address_slot(target)
2078                } else {
2079                    branch.address
2080                };
2081                outcome = self.prepare_value_transfer(
2082                    executor,
2083                    &mut branch,
2084                    &mut parents,
2085                    kind,
2086                    call_caller,
2087                    transfer_to,
2088                    value.clone(),
2089                    out_offset.clone(),
2090                    &out_size,
2091                )?;
2092                if outcome.is_none() {
2093                    branch.world.transfer(
2094                        &mut self.cx,
2095                        executor,
2096                        call_caller,
2097                        transfer_to,
2098                        value.clone(),
2099                        true,
2100                    )?;
2101                }
2102            }
2103            let outcome = match outcome {
2104                Some(outcome) => outcome,
2105                None => {
2106                    // A successful call has no reverter to match.
2107                    let return_data = SymReturnData::empty(&mut self.cx);
2108                    let reverter = branch.address;
2109                    self.finish_codeless_call(
2110                        executor,
2111                        &mut branch,
2112                        kind,
2113                        CallStatus::Success,
2114                        return_data,
2115                        reverter,
2116                        out_offset.clone(),
2117                        &out_size,
2118                    )?
2119                }
2120            };
2121            match outcome {
2122                StepOutcome::Continue => parents.push_back(branch),
2123                StepOutcome::AssumeRejected => {}
2124                outcome => {
2125                    *state = branch;
2126                    return Ok(outcome);
2127                }
2128            }
2129        }
2130
2131        let call_input = in_size.read_from_memory(&mut self.cx, &state.memory, in_offset.clone());
2132        if let Some(cheatcode_condition) = cheatcode_condition {
2133            let mut cheatcode_branch = state.clone();
2134            cheatcode_branch.constraints.push(cheatcode_condition);
2135            if self.is_sat_with_state(&cheatcode_branch, &cheatcode_branch.constraints)? {
2136                // The decoder error only depends on the selector, except for shorter calldata.
2137                let input = if call_input.len() < 4 {
2138                    call_input.clone()
2139                } else {
2140                    call_input.slice_concrete(&mut self.cx, 0, 4)
2141                };
2142                let input = input.concrete_bytes(&mut self.cx, "symbolic cheatcode selector")?;
2143                if let Ok(selector) = <[u8; 4]>::try_from(input.as_slice())
2144                    && VmCalls::signature_by_selector(selector).is_some()
2145                {
2146                    return Err(SymbolicError::Unsupported("symbolic cheatcode CALL target"));
2147                }
2148                let Err(error) = decode_cheatcode_call(&input) else {
2149                    return Err(SymbolicError::Unsupported("symbolic cheatcode CALL target"));
2150                };
2151                // Like Forge, a cheatcode call leaves `vm.expectRevert` and `vm.assumeNoRevert`
2152                // pending.
2153                let return_data = error_string_return_data(&mut self.cx, &error.to_string());
2154                revert_cheatcode_call(
2155                    &mut self.cx,
2156                    &mut cheatcode_branch,
2157                    out_offset.clone(),
2158                    &out_size,
2159                    return_data,
2160                )?;
2161                parents.push_back(cheatcode_branch);
2162            }
2163        }
2164
2165        for (to, constraint) in candidates.into_iter().zip(candidate_constraints) {
2166            let mut branch = state.clone();
2167            branch.constraints.push(constraint);
2168            if !self.is_sat_with_state(&branch, &branch.constraints)? {
2169                continue;
2170            }
2171            // Forge treats the compatibility address as an ordinary account, so only a call that
2172            // names it concretely reaches the symbolic-VM operations.
2173            if to == SYMBOLIC_VM_COMPAT_ADDRESS
2174                && matches!(kind, CallKind::Call | CallKind::StaticCall)
2175                && call_input.len() >= 4
2176            {
2177                let selector = call_input
2178                    .slice_concrete(&mut self.cx, 0, 4)
2179                    .concrete_bytes(&mut self.cx, "symbolic compatibility selector")?;
2180                if let Ok(selector) = <[u8; 4]>::try_from(selector.as_slice())
2181                    && SymbolicVmCheatcode::from_selector(selector).is_some()
2182                {
2183                    return Err(SymbolicError::Unsupported("symbolic cheatcode CALL target"));
2184                }
2185            }
2186
2187            // Decide mock matches before executing either the mocked or real call.
2188            for mut branch in self.split_symbolic_target_candidate(
2189                executor,
2190                branch,
2191                kind,
2192                to,
2193                &value,
2194                &gas,
2195                &call_input,
2196            )? {
2197                let mut branch_worklist = VecDeque::new();
2198                match self.call_concrete_target(
2199                    executor,
2200                    &mut branch,
2201                    &mut branch_worklist,
2202                    completed_paths,
2203                    kind,
2204                    to,
2205                    None,
2206                    value.clone(),
2207                    gas.clone(),
2208                    in_offset.clone(),
2209                    in_size.clone(),
2210                    out_offset.clone(),
2211                    out_size.clone(),
2212                )? {
2213                    StepOutcome::Continue => {
2214                        parents.push_back(branch);
2215                        parents.extend(branch_worklist);
2216                    }
2217                    StepOutcome::AssumeRejected => {}
2218                    outcome => {
2219                        *state = branch;
2220                        return Ok(outcome);
2221                    }
2222                }
2223            }
2224        }
2225
2226        let Some(first) = self.pop_next_path(&mut parents) else {
2227            return Ok(StepOutcome::AssumeRejected);
2228        };
2229        *state = first;
2230        worklist.extend(parents);
2231        Ok(StepOutcome::Continue)
2232    }
2233
2234    /// Decides mock and expectation matches before executing a symbolic-target candidate.
2235    #[expect(clippy::too_many_arguments)]
2236    fn split_symbolic_target_candidate(
2237        &mut self,
2238        executor: &ExecutorView<'_>,
2239        mut branch: PathState,
2240        kind: CallKind,
2241        to: Address,
2242        value: &SymExpr,
2243        gas: &SymExpr,
2244        call_input: &SymBytes,
2245    ) -> Result<Vec<PathState>, SymbolicError> {
2246        let callee = if self.function_mock_may_match(executor, &mut branch, to, call_input)? {
2247            Some(self.call_code_account(executor, &mut branch, to)?)
2248        } else {
2249            None
2250        };
2251        let mut branches = vec![branch];
2252        if let Some(callee) = callee {
2253            for condition in self.function_mock_conditions(&branches[0], callee, call_input) {
2254                branches = self.split_branches_on(branches, condition)?;
2255            }
2256        }
2257
2258        let mut out = Vec::new();
2259        for mut branch in branches {
2260            let code_address = match callee {
2261                Some(callee) => {
2262                    self.function_mock_target(&mut branch, callee, call_input)?.unwrap_or(to)
2263                }
2264                None => to,
2265            };
2266
2267            let mut value_branches = vec![branch];
2268            if value_branches[0].constrained_word(&mut self.cx, value).is_none() {
2269                let candidates =
2270                    self.call_value_candidates(&value_branches[0], code_address, gas, call_input)?;
2271                for candidate in candidates {
2272                    let eq = SymBoolExpr::eq_word_const(&mut self.cx, value, candidate);
2273                    value_branches = self.split_branches_on(value_branches, eq)?;
2274                }
2275            }
2276
2277            for branch in value_branches {
2278                let concrete_value = self.transfer_value(&branch, kind, value);
2279                let mut match_branches = vec![branch];
2280                let conditions = self.call_match_conditions(
2281                    &match_branches[0],
2282                    code_address,
2283                    concrete_value,
2284                    gas,
2285                    call_input,
2286                )?;
2287                for condition in conditions {
2288                    match_branches = self.split_branches_on(match_branches, condition)?;
2289                }
2290                if out.len() + match_branches.len() > self.config.path_width() as usize {
2291                    return Err(SymbolicError::Unsupported("symbolic path limit exceeded"));
2292                }
2293                out.extend(match_branches);
2294            }
2295        }
2296        Ok(out)
2297    }
2298
2299    /// Splits branches on a match condition, retaining feasible outcomes.
2300    fn split_branches_on(
2301        &mut self,
2302        branches: Vec<PathState>,
2303        condition: SymBoolExpr,
2304    ) -> Result<Vec<PathState>, SymbolicError> {
2305        let mismatch_condition = condition.clone().not(&mut self.cx);
2306        let mut next = Vec::with_capacity(branches.len());
2307        for branch in branches {
2308            let (match_constraints, match_sat) =
2309                self.constraints_with_condition(&branch, condition.clone())?;
2310            let (mismatch_constraints, mismatch_sat) =
2311                self.constraints_with_condition(&branch, mismatch_condition.clone())?;
2312            match (match_sat, mismatch_sat) {
2313                (true, true) => {
2314                    let mut match_branch = branch.clone();
2315                    match_branch.constraints = match_constraints;
2316                    next.push(match_branch);
2317                    let mut mismatch_branch = branch;
2318                    mismatch_branch.constraints = mismatch_constraints;
2319                    next.push(mismatch_branch);
2320                }
2321                (true, false) => {
2322                    let mut branch = branch;
2323                    branch.constraints = match_constraints;
2324                    next.push(branch);
2325                }
2326                (false, true) => {
2327                    let mut branch = branch;
2328                    branch.constraints = mismatch_constraints;
2329                    next.push(branch);
2330                }
2331                (false, false) => {}
2332            }
2333            if next.len() > self.config.path_width() as usize {
2334                return Err(SymbolicError::Unsupported("symbolic path limit exceeded"));
2335            }
2336        }
2337        Ok(next)
2338    }
2339
2340    /// Function mock conditions in match-precedence order.
2341    fn function_mock_conditions(
2342        &mut self,
2343        state: &PathState,
2344        callee: Address,
2345        calldata: &SymBytes,
2346    ) -> Vec<SymBoolExpr> {
2347        let mut conditions = Vec::new();
2348        for calldata_len in [calldata.len(), 4] {
2349            for idx in (0..state.function_mocks.len()).rev() {
2350                if state.function_mocks[idx].calldata_len() != calldata_len {
2351                    continue;
2352                }
2353                if let Some(condition) =
2354                    state.function_mocks[idx].match_condition(&mut self.cx, callee, calldata)
2355                {
2356                    conditions.push(condition);
2357                }
2358            }
2359        }
2360        conditions
2361    }
2362
2363    /// Values that can satisfy a call expectation or mock.
2364    fn call_value_candidates(
2365        &mut self,
2366        state: &PathState,
2367        code_address: Address,
2368        gas: &SymExpr,
2369        call_input: &SymBytes,
2370    ) -> Result<Vec<U256>, SymbolicError> {
2371        let mut candidates = HashSet::<U256>::default();
2372        for expected in &state.expected_calls {
2373            let Some(expected_value) = expected.value() else { continue };
2374            if self
2375                .expected_call_match_constraints(
2376                    state,
2377                    expected,
2378                    code_address,
2379                    Some(expected_value),
2380                    gas,
2381                    call_input,
2382                )?
2383                .is_some()
2384            {
2385                candidates.insert(expected_value);
2386            }
2387        }
2388        for mock in &state.call_mocks {
2389            let Some(mock_value) = mock.value() else { continue };
2390            if self
2391                .call_mock_match_constraints(
2392                    state,
2393                    mock,
2394                    code_address,
2395                    Some(mock_value),
2396                    call_input,
2397                )?
2398                .is_some()
2399            {
2400                candidates.insert(mock_value);
2401            }
2402        }
2403        let mut candidates = candidates.into_iter().collect::<Vec<_>>();
2404        candidates.sort_unstable();
2405        Ok(candidates)
2406    }
2407
2408    /// Expected call and call mock conditions in match-precedence order.
2409    fn call_match_conditions(
2410        &mut self,
2411        state: &PathState,
2412        code_address: Address,
2413        value: Option<U256>,
2414        gas: &SymExpr,
2415        calldata: &SymBytes,
2416    ) -> Result<Vec<SymBoolExpr>, SymbolicError> {
2417        let mut conditions = Vec::new();
2418        for expected in &state.expected_calls {
2419            if let Some(condition) =
2420                expected.match_condition(&mut self.cx, code_address, value, gas, calldata)?
2421            {
2422                conditions.push(condition);
2423            }
2424        }
2425        let mut mocks = (0..state.call_mocks.len()).collect::<Vec<_>>();
2426        mocks.sort_by_key(|idx| {
2427            let (len, has_value) = state.call_mocks[*idx].specificity();
2428            (std::cmp::Reverse(len), std::cmp::Reverse(has_value), *idx)
2429        });
2430        for idx in mocks {
2431            if let Some(condition) =
2432                state.call_mocks[idx].match_condition(&mut self.cx, code_address, value, calldata)
2433            {
2434                conditions.push(condition);
2435            }
2436        }
2437        Ok(conditions)
2438    }
2439}
2440
2441const KZG_POINT_EVALUATION_INPUT_LEN: usize = 192;
2442const KZG_VERSIONED_HASH_OFFSET: usize = 0;
2443const KZG_Z_OFFSET: usize = 32;
2444const KZG_Y_OFFSET: usize = 64;
2445const KZG_COMMITMENT_OFFSET: usize = 96;
2446const KZG_PROOF_OFFSET: usize = 144;
2447
2448const KZG_BLS_MODULUS: [u8; 32] =
2449    hex!("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001");
2450
2451/// Versioned hash version for KZG commitments.
2452const KZG_VERSIONED_HASH_VERSION: u8 = 0x01;
2453
2454/// `U256(FIELD_ELEMENTS_PER_BLOB).to_be_bytes() ++ BLS_MODULUS.to_bytes32()`.
2455const KZG_RETURN_VALUE: [u8; 64] = hex!(
2456    "0000000000000000000000000000000000000000000000000000000000001000"
2457    "73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001"
2458);
2459
2460const KZG_SUCCESS_INPUT: [u8; KZG_POINT_EVALUATION_INPUT_LEN] = hex!(
2461    "01e798154708fe7789429634053cbf9f99b619f9f084048927333fce637f549b"
2462    "73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000"
2463    "1522a4a7f34e1ea350ae07c29c96c7e79655aa926122e95fe69fcbd932ca49e9"
2464    "8f59a8d2a1a625a17f3fea0fe5eb8c896db3764f3185481bc22f91b4aaffcca25f26936857bc3a7c2539ea8ec3a952b7"
2465    "a62ad71d14c5719385c0686f1871430475bf3a00f0aa3f7b8dd99a9abc2160744faf0070725e00b60ad9a026a15b1a8c"
2466);
2467
2468const KZG_INVALID_PROOF: [u8; 48] = [0xff; 48];
2469const KZG_ZERO_COMMITMENT: [u8; 48] = [0x00; 48];
2470const KZG_ONE_COMMITMENT: [u8; 48] = [0x01; 48];
2471const KZG_RESIDUAL_REASON: &str = "symbolic KZG point-evaluation precompile residual not modeled";
2472
2473fn kzg_success_return_data(cx: &mut SymCx) -> SymReturnData {
2474    SymReturnData::from_concrete_bytes(cx, KZG_RETURN_VALUE.to_vec())
2475}
2476
2477fn kzg_constrained_outcome(
2478    cx: &mut SymCx,
2479    state: &PathState,
2480    input: &[SymExpr],
2481    input_len: &SymExpr,
2482    gas: u64,
2483) -> Result<Option<Option<SymReturnData>>, SymbolicError> {
2484    let Some(input_len) = state.constrained_usize(cx, input_len) else {
2485        return Ok(None);
2486    };
2487    if input_len != KZG_POINT_EVALUATION_INPUT_LEN {
2488        return Ok(Some(None));
2489    }
2490    if input_len > input.len() {
2491        return Err(SymbolicError::Unsupported("out-of-bounds symbolic precompile input"));
2492    }
2493
2494    if let Some(input) = constrained_bytes_at(cx, state, input, 0, input_len) {
2495        return execute_precompile(cx, Address::with_last_byte(10), &input, SpecId::CANCUN, gas)
2496            .map(Some);
2497    }
2498
2499    if constrained_byte(cx, state, &input[0])
2500        .is_some_and(|version| version != KZG_VERSIONED_HASH_VERSION)
2501    {
2502        return Ok(Some(None));
2503    }
2504
2505    if constrained_bytes_at(cx, state, input, KZG_Z_OFFSET, KZG_BLS_MODULUS.len())
2506        .is_some_and(|z| z == KZG_BLS_MODULUS)
2507        || constrained_bytes_at(cx, state, input, KZG_Y_OFFSET, KZG_BLS_MODULUS.len())
2508            .is_some_and(|y| y == KZG_BLS_MODULUS)
2509        || constrained_bytes_at(cx, state, input, KZG_PROOF_OFFSET, KZG_INVALID_PROOF.len())
2510            .is_some_and(|proof| proof == KZG_INVALID_PROOF)
2511    {
2512        return Ok(Some(None));
2513    }
2514
2515    if let Some(commitment) = constrained_bytes_at(cx, state, input, KZG_COMMITMENT_OFFSET, 48) {
2516        let expected_hash = kzg_to_versioned_hash(&commitment);
2517        for (idx, expected) in expected_hash.into_iter().enumerate() {
2518            if constrained_byte(cx, state, &input[idx]).is_some_and(|actual| actual != expected) {
2519                return Ok(Some(None));
2520            }
2521        }
2522    }
2523
2524    Ok(None)
2525}
2526
2527fn kzg_success_witness_condition(
2528    cx: &mut SymCx,
2529    input: &[SymExpr],
2530    input_len: &SymExpr,
2531) -> SymBoolExpr {
2532    let len = expr_eq_condition(cx, input_len, KZG_POINT_EVALUATION_INPUT_LEN);
2533    let bytes = bytes_eq_condition(cx, input, KZG_VERSIONED_HASH_OFFSET, &KZG_SUCCESS_INPUT);
2534    SymBoolExpr::and(cx, vec![len, bytes])
2535}
2536
2537fn kzg_failure_witness_condition(
2538    cx: &mut SymCx,
2539    state: &PathState,
2540    input: &[SymExpr],
2541    input_len: &SymExpr,
2542) -> SymBoolExpr {
2543    let len_192 = expr_eq_condition(cx, input_len, KZG_POINT_EVALUATION_INPUT_LEN);
2544    let len_ne_192 = expr_ne_condition(cx, input_len, KZG_POINT_EVALUATION_INPUT_LEN);
2545    let bad_version = byte_ne_condition(cx, input, 0, KZG_VERSIONED_HASH_VERSION);
2546    let bad_z = bytes_eq_condition(cx, input, KZG_Z_OFFSET, &KZG_BLS_MODULUS);
2547    let bad_y = bytes_eq_condition(cx, input, KZG_Y_OFFSET, &KZG_BLS_MODULUS);
2548    let bad_proof = bytes_eq_condition(cx, input, KZG_PROOF_OFFSET, &KZG_INVALID_PROOF);
2549    let mut conditions = vec![
2550        len_ne_192,
2551        SymBoolExpr::and(cx, vec![len_192.clone(), bad_version]),
2552        SymBoolExpr::and(cx, vec![len_192.clone(), bad_z]),
2553        SymBoolExpr::and(cx, vec![len_192.clone(), bad_y]),
2554        SymBoolExpr::and(cx, vec![len_192.clone(), bad_proof]),
2555    ];
2556
2557    if let Some(commitment) = constrained_bytes_at(cx, state, input, KZG_COMMITMENT_OFFSET, 48) {
2558        let expected_hash = kzg_to_versioned_hash(&commitment);
2559        let mismatch = kzg_versioned_hash_mismatch_condition(cx, input, &expected_hash);
2560        conditions.push(SymBoolExpr::and(cx, vec![len_192.clone(), mismatch]));
2561    }
2562
2563    let expected_hash = &KZG_SUCCESS_INPUT[KZG_VERSIONED_HASH_OFFSET..KZG_Z_OFFSET];
2564    let commitment = &KZG_SUCCESS_INPUT[KZG_COMMITMENT_OFFSET..KZG_PROOF_OFFSET];
2565    let commitment_eq = bytes_eq_condition(cx, input, KZG_COMMITMENT_OFFSET, commitment);
2566    let hash_byte_mismatch = byte_eq_condition(cx, input, 1, expected_hash[1] ^ 1);
2567    conditions.push(SymBoolExpr::and(cx, vec![len_192.clone(), commitment_eq, hash_byte_mismatch]));
2568
2569    for commitment in [&KZG_ZERO_COMMITMENT, &KZG_ONE_COMMITMENT] {
2570        let expected_hash = kzg_to_versioned_hash(commitment);
2571        let commitment_eq = bytes_eq_condition(cx, input, KZG_COMMITMENT_OFFSET, commitment);
2572        let mismatch = kzg_versioned_hash_mismatch_condition(cx, input, &expected_hash);
2573        conditions.push(SymBoolExpr::and(cx, vec![len_192.clone(), commitment_eq, mismatch]));
2574    }
2575
2576    SymBoolExpr::or(cx, conditions)
2577}
2578
2579fn kzg_versioned_hash_mismatch_condition(
2580    cx: &mut SymCx,
2581    input: &[SymExpr],
2582    expected_hash: &[u8; 32],
2583) -> SymBoolExpr {
2584    bytes_ne_condition(cx, input, KZG_VERSIONED_HASH_OFFSET, expected_hash)
2585}
2586
2587fn expr_eq_condition(cx: &mut SymCx, expr: &SymExpr, value: usize) -> SymBoolExpr {
2588    SymBoolExpr::eq_word_const(cx, expr, U256::from(value))
2589}
2590
2591fn expr_ne_condition(cx: &mut SymCx, expr: &SymExpr, value: usize) -> SymBoolExpr {
2592    let condition = expr_eq_condition(cx, expr, value);
2593    condition.not(cx)
2594}
2595
2596fn byte_eq_condition(cx: &mut SymCx, input: &[SymExpr], offset: usize, value: u8) -> SymBoolExpr {
2597    match input.get(offset) {
2598        Some(expr) => expr_eq_condition(cx, expr, value as usize),
2599        None => SymBoolExpr::constant(cx, false),
2600    }
2601}
2602
2603fn byte_ne_condition(cx: &mut SymCx, input: &[SymExpr], offset: usize, value: u8) -> SymBoolExpr {
2604    match input.get(offset) {
2605        Some(expr) => expr_ne_condition(cx, expr, value as usize),
2606        None => SymBoolExpr::constant(cx, false),
2607    }
2608}
2609
2610fn bytes_eq_condition(
2611    cx: &mut SymCx,
2612    input: &[SymExpr],
2613    offset: usize,
2614    bytes: &[u8],
2615) -> SymBoolExpr {
2616    let Some(end) = offset.checked_add(bytes.len()) else {
2617        return SymBoolExpr::constant(cx, false);
2618    };
2619    if end > input.len() {
2620        return SymBoolExpr::constant(cx, false);
2621    }
2622    let conditions = input[offset..end]
2623        .iter()
2624        .zip(bytes)
2625        .map(|(expr, byte)| expr_eq_condition(cx, expr, *byte as usize))
2626        .collect();
2627    SymBoolExpr::and(cx, conditions)
2628}
2629
2630fn bytes_ne_condition(
2631    cx: &mut SymCx,
2632    input: &[SymExpr],
2633    offset: usize,
2634    bytes: &[u8],
2635) -> SymBoolExpr {
2636    let Some(end) = offset.checked_add(bytes.len()) else {
2637        return SymBoolExpr::constant(cx, false);
2638    };
2639    if end > input.len() {
2640        return SymBoolExpr::constant(cx, false);
2641    }
2642    let conditions = input[offset..end]
2643        .iter()
2644        .zip(bytes)
2645        .map(|(expr, byte)| expr_ne_condition(cx, expr, *byte as usize))
2646        .collect();
2647    SymBoolExpr::or(cx, conditions)
2648}
2649
2650fn constrained_bytes_at(
2651    cx: &mut SymCx,
2652    state: &PathState,
2653    input: &[SymExpr],
2654    offset: usize,
2655    len: usize,
2656) -> Option<Vec<u8>> {
2657    let end = offset.checked_add(len)?;
2658    let bytes = input.get(offset..end)?;
2659    bytes.iter().map(|byte| constrained_byte(cx, state, byte)).collect()
2660}
2661
2662fn constrained_byte(cx: &mut SymCx, state: &PathState, byte: &SymExpr) -> Option<u8> {
2663    state.constrained_word(cx, byte).and_then(|byte| u8::try_from(byte).ok())
2664}
2665
2666impl SymbolicExecutor {
2667    fn ensure_gas_modeled(&self, expr: &SymExpr) -> Result<(), SymbolicError> {
2668        if !self.symbolic_gas() && expr.contains_gasleft() {
2669            Err(SymbolicError::Unsupported("GAS/gasleft() not modeled"))
2670        } else {
2671            Ok(())
2672        }
2673    }
2674}
2675
2676/// Returns `KZG_VERSIONED_HASH_VERSION ++ sha256(commitment)[1..]`.
2677fn kzg_to_versioned_hash(commitment: &[u8]) -> [u8; 32] {
2678    let mut hash = evm2::precompiles::crypto().sha256(commitment);
2679    hash[0] = KZG_VERSIONED_HASH_VERSION;
2680    hash
2681}