1use std::fmt::{self, Display};
2
3use crate::{
4 Cheatcode, Cheatcodes, CheatcodesCore, CheatsCtxt, Result, Vm::*, expected_emit::ExpectedEmit,
5};
6use alloy_primitives::{
7 Address, Bytes, LogData as RawLog, U256, hex, keccak256,
8 map::{HashMap, hash_map::Entry},
9};
10use alloy_sol_types::{SolCall, SolValue};
11use evm2::interpreter::MessageKind;
12use foundry_evm_core::evm::FoundryEvmNetwork;
13use itertools::Itertools;
14use tempo_contracts::precompiles::ISignatureVerifier;
15use tempo_precompiles::SIGNATURE_VERIFIER_ADDRESS;
16
17use super::revert_handlers::RevertParameters;
18pub type ExpectedCallTracker = HashMap<Address, ExpectedCallsForTarget>;
29
30pub type ExpectedCallsForTarget =
32 HashMap<(Bytes, Option<ExpectedCallScheme>), (ExpectedCallData, u64)>;
33
34#[derive(Clone, Debug)]
35pub struct ExpectedCallData {
36 pub value: Option<U256>,
38 pub gas: Option<u64>,
40 pub min_gas: Option<u64>,
42 pub count: u64,
47 pub call_type: ExpectedCallType,
49}
50
51impl Default for ExpectedCallData {
52 fn default() -> Self {
53 Self {
54 value: None,
55 gas: None,
56 min_gas: None,
57 count: 1,
58 call_type: ExpectedCallType::NonCount,
59 }
60 }
61}
62
63#[derive(Clone, Debug, PartialEq, Eq)]
65pub enum ExpectedCallType {
66 NonCount,
68 Count,
70}
71
72#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
74pub enum ExpectedCallScheme {
75 Call,
77 CallCode,
79 DelegateCall,
81 StaticCall,
83}
84
85impl From<MessageKind> for ExpectedCallScheme {
86 fn from(kind: MessageKind) -> Self {
87 match kind {
88 MessageKind::Call => Self::Call,
89 MessageKind::CallCode => Self::CallCode,
90 MessageKind::DelegateCall => Self::DelegateCall,
91 MessageKind::StaticCall => Self::StaticCall,
92 _ => Self::Call,
94 }
95 }
96}
97
98#[derive(Clone, Debug)]
100pub enum ExpectedRevertKind {
101 Default,
103 Cheatcode { pending_processing: bool },
109}
110
111#[derive(Clone, Debug)]
112pub struct ExpectedRevert {
113 pub reason: Option<Bytes>,
115 pub depth: usize,
117 pub kind: ExpectedRevertKind,
119 pub partial_match: bool,
121 pub reverter: Option<Address>,
123 pub reverted_by: Option<Address>,
125 pub max_depth: usize,
127 pub count: u64,
129 pub actual_count: u64,
131}
132
133#[derive(Clone, Debug)]
134pub struct ExpectedCreate {
135 pub deployer: Address,
137 pub bytecode: Bytes,
139 pub create_scheme: CreateScheme,
141}
142
143#[derive(Clone, Debug)]
144pub enum CreateScheme {
145 Create,
146 Create2,
147}
148
149impl Display for CreateScheme {
150 fn fmt(&self, f: &mut fmt::Formatter) -> std::fmt::Result {
151 match self {
152 Self::Create => write!(f, "CREATE"),
153 Self::Create2 => write!(f, "CREATE2"),
154 }
155 }
156}
157
158impl From<MessageKind> for CreateScheme {
159 fn from(kind: MessageKind) -> Self {
160 match kind {
161 MessageKind::Create => Self::Create,
162 MessageKind::Create2 => Self::Create2,
163 _ => Self::Create,
165 }
166 }
167}
168
169impl CreateScheme {
170 pub const fn eq(&self, create_scheme: Self) -> bool {
171 matches!(
172 (self, create_scheme),
173 (Self::Create, Self::Create) | (Self::Create2, Self::Create2 { .. })
174 )
175 }
176}
177
178impl Cheatcode for expectCall_0Call {
179 fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
180 let Self { callee, data } = self;
181 expect_call(state, callee, data, None, ExpectedCallData::default())
182 }
183}
184
185impl Cheatcode for expectCall_1Call {
186 fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
187 let Self { callee, data, count } = self;
188 expect_call(
189 state,
190 callee,
191 data,
192 None,
193 ExpectedCallData {
194 count: *count,
195 call_type: ExpectedCallType::Count,
196 ..Default::default()
197 },
198 )
199 }
200}
201
202impl Cheatcode for expectCall_2Call {
203 fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
204 let Self { callee, msgValue, data } = self;
205 expect_call(
206 state,
207 callee,
208 data,
209 None,
210 ExpectedCallData { value: Some(*msgValue), ..Default::default() },
211 )
212 }
213}
214
215impl Cheatcode for expectCall_3Call {
216 fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
217 let Self { callee, msgValue, data, count } = self;
218 expect_call(
219 state,
220 callee,
221 data,
222 None,
223 ExpectedCallData {
224 value: Some(*msgValue),
225 count: *count,
226 call_type: ExpectedCallType::Count,
227 ..Default::default()
228 },
229 )
230 }
231}
232
233impl Cheatcode for expectCall_4Call {
234 fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
235 let Self { callee, msgValue, gas, data } = self;
236 expect_call(
237 state,
238 callee,
239 data,
240 None,
241 ExpectedCallData { value: Some(*msgValue), gas: Some(*gas), ..Default::default() },
242 )
243 }
244}
245
246impl Cheatcode for expectCall_5Call {
247 fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
248 let Self { callee, msgValue, gas, data, count } = self;
249 expect_call(
250 state,
251 callee,
252 data,
253 None,
254 ExpectedCallData {
255 value: Some(*msgValue),
256 gas: Some(*gas),
257 count: *count,
258 call_type: ExpectedCallType::Count,
259 ..Default::default()
260 },
261 )
262 }
263}
264
265impl Cheatcode for expectDelegateCallCall {
266 fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
267 let Self { callee, data } = self;
268 expect_call(
269 state,
270 callee,
271 data,
272 Some(ExpectedCallScheme::DelegateCall),
273 ExpectedCallData::default(),
274 )
275 }
276}
277
278impl Cheatcode for expectCallMinGas_0Call {
279 fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
280 let Self { callee, msgValue, minGas, data } = self;
281 expect_call(
282 state,
283 callee,
284 data,
285 None,
286 ExpectedCallData {
287 value: Some(*msgValue),
288 min_gas: Some(*minGas),
289 ..Default::default()
290 },
291 )
292 }
293}
294
295impl Cheatcode for expectCallMinGas_1Call {
296 fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
297 let Self { callee, msgValue, minGas, data, count } = self;
298 expect_call(
299 state,
300 callee,
301 data,
302 None,
303 ExpectedCallData {
304 value: Some(*msgValue),
305 min_gas: Some(*minGas),
306 count: *count,
307 call_type: ExpectedCallType::Count,
308 ..Default::default()
309 },
310 )
311 }
312}
313
314impl Cheatcode for expectEmit_0Call {
315 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
316 let Self { checkTopic1, checkTopic2, checkTopic3, checkData } = *self;
317 expect_emit(
318 ccx.state,
319 ccx.depth(),
320 [true, checkTopic1, checkTopic2, checkTopic3, checkData],
321 None,
322 false,
323 1,
324 )
325 }
326}
327
328impl Cheatcode for expectEmit_1Call {
329 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
330 let Self { checkTopic1, checkTopic2, checkTopic3, checkData, emitter } = *self;
331 expect_emit(
332 ccx.state,
333 ccx.depth(),
334 [true, checkTopic1, checkTopic2, checkTopic3, checkData],
335 Some(emitter),
336 false,
337 1,
338 )
339 }
340}
341
342impl Cheatcode for expectEmit_2Call {
343 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
344 let Self {} = self;
345 expect_emit(ccx.state, ccx.depth(), [true; 5], None, false, 1)
346 }
347}
348
349impl Cheatcode for expectEmit_3Call {
350 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
351 let Self { emitter } = *self;
352 expect_emit(ccx.state, ccx.depth(), [true; 5], Some(emitter), false, 1)
353 }
354}
355
356impl Cheatcode for expectEmit_4Call {
357 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
358 let Self { checkTopic1, checkTopic2, checkTopic3, checkData, count } = *self;
359 expect_emit(
360 ccx.state,
361 ccx.depth(),
362 [true, checkTopic1, checkTopic2, checkTopic3, checkData],
363 None,
364 false,
365 count,
366 )
367 }
368}
369
370impl Cheatcode for expectEmit_5Call {
371 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
372 let Self { checkTopic1, checkTopic2, checkTopic3, checkData, emitter, count } = *self;
373 expect_emit(
374 ccx.state,
375 ccx.depth(),
376 [true, checkTopic1, checkTopic2, checkTopic3, checkData],
377 Some(emitter),
378 false,
379 count,
380 )
381 }
382}
383
384impl Cheatcode for expectEmit_6Call {
385 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
386 let Self { count } = *self;
387 expect_emit(ccx.state, ccx.depth(), [true; 5], None, false, count)
388 }
389}
390
391impl Cheatcode for expectEmit_7Call {
392 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
393 let Self { emitter, count } = *self;
394 expect_emit(ccx.state, ccx.depth(), [true; 5], Some(emitter), false, count)
395 }
396}
397
398impl Cheatcode for expectEmitAnonymous_0Call {
399 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
400 let Self { checkTopic0, checkTopic1, checkTopic2, checkTopic3, checkData } = *self;
401 expect_emit(
402 ccx.state,
403 ccx.depth(),
404 [checkTopic0, checkTopic1, checkTopic2, checkTopic3, checkData],
405 None,
406 true,
407 1,
408 )
409 }
410}
411
412impl Cheatcode for expectEmitAnonymous_1Call {
413 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
414 let Self { checkTopic0, checkTopic1, checkTopic2, checkTopic3, checkData, emitter } = *self;
415 expect_emit(
416 ccx.state,
417 ccx.depth(),
418 [checkTopic0, checkTopic1, checkTopic2, checkTopic3, checkData],
419 Some(emitter),
420 true,
421 1,
422 )
423 }
424}
425
426impl Cheatcode for expectEmitAnonymous_2Call {
427 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
428 let Self {} = self;
429 expect_emit(ccx.state, ccx.depth(), [true; 5], None, true, 1)
430 }
431}
432
433impl Cheatcode for expectEmitAnonymous_3Call {
434 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
435 let Self { emitter } = *self;
436 expect_emit(ccx.state, ccx.depth(), [true; 5], Some(emitter), true, 1)
437 }
438}
439
440impl Cheatcode for expectCreateCall {
441 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
442 let Self { bytecode, deployer } = self;
443 expect_create(ccx.state, bytecode.clone(), *deployer, CreateScheme::Create)
444 }
445}
446
447impl Cheatcode for expectCreate2Call {
448 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
449 let Self { bytecode, deployer } = self;
450 expect_create(ccx.state, bytecode.clone(), *deployer, CreateScheme::Create2)
451 }
452}
453
454impl Cheatcode for expectTip20LogoURIUpdatedCall {
455 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
456 let Self { token, updater, newLogoURI } = self;
457 expect_logo_uri_updated(ccx, token, updater, newLogoURI)
458 }
459}
460
461impl Cheatcode for expectKeychainVerifiedCall {
462 fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
463 let Self { account, digest, signature } = self;
464 expect_keychain_verified(state, *account, *digest, signature.clone(), false)
465 }
466}
467
468impl Cheatcode for expectKeychainAdminVerifiedCall {
469 fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
470 let Self { account, digest, signature } = self;
471 expect_keychain_verified(state, *account, *digest, signature.clone(), true)
472 }
473}
474
475impl Cheatcode for expectLogoURIUpdatedCall {
476 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
477 let Self { token, updater, newLogoURI } = self;
478 expect_logo_uri_updated(ccx, token, updater, newLogoURI)
479 }
480}
481
482fn expect_keychain_verified(
483 state: &mut CheatcodesCore,
484 account: Address,
485 digest: alloy_primitives::B256,
486 signature: Bytes,
487 admin: bool,
488) -> Result {
489 let calldata = if admin {
490 ISignatureVerifier::verifyKeychainAdminCall { account, hash: digest, signature }
491 .abi_encode()
492 } else {
493 ISignatureVerifier::verifyKeychainCall { account, hash: digest, signature }.abi_encode()
494 };
495 expect_call(
496 state,
497 &SIGNATURE_VERIFIER_ADDRESS,
498 &Bytes::from(calldata),
499 None,
500 ExpectedCallData::default(),
501 )
502}
503
504fn expect_logo_uri_updated<FEN: FoundryEvmNetwork>(
505 ccx: &mut CheatsCtxt<'_, '_, FEN>,
506 token: &Address,
507 updater: &Address,
508 new_logo_uri: &str,
509) -> Result {
510 let expected_emit = ExpectedEmit {
511 depth: ccx.depth(),
512 log: Some(RawLog::new_unchecked(
513 vec![keccak256("LogoURIUpdated(address,string)"), updater.into_word()],
514 new_logo_uri.abi_encode().into(),
515 )),
516 checks: [true, true, false, false, true],
517 address: Some(*token),
518 anonymous: false,
519 found: false,
520 count: 1,
521 mismatch_error: None,
522 };
523 ccx.state.expected_emits.push_back((expected_emit, Default::default()));
524 Ok(Default::default())
525}
526
527impl Cheatcode for expectRevert_0Call {
528 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
529 let Self {} = self;
530 expect_revert(ccx.state, None, ccx.depth(), false, false, None, 1)
531 }
532}
533
534impl Cheatcode for expectRevert_1Call {
535 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
536 let Self { revertData } = self;
537 expect_revert(ccx.state, Some(revertData.as_ref()), ccx.depth(), false, false, None, 1)
538 }
539}
540
541impl Cheatcode for expectRevert_2Call {
542 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
543 let Self { revertData } = self;
544 expect_revert(ccx.state, Some(revertData), ccx.depth(), false, false, None, 1)
545 }
546}
547
548impl Cheatcode for expectRevert_3Call {
549 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
550 let Self { reverter } = self;
551 expect_revert(ccx.state, None, ccx.depth(), false, false, Some(*reverter), 1)
552 }
553}
554
555impl Cheatcode for expectRevert_4Call {
556 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
557 let Self { revertData, reverter } = self;
558 expect_revert(
559 ccx.state,
560 Some(revertData.as_ref()),
561 ccx.depth(),
562 false,
563 false,
564 Some(*reverter),
565 1,
566 )
567 }
568}
569
570impl Cheatcode for expectRevert_5Call {
571 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
572 let Self { revertData, reverter } = self;
573 expect_revert(ccx.state, Some(revertData), ccx.depth(), false, false, Some(*reverter), 1)
574 }
575}
576
577impl Cheatcode for expectRevert_6Call {
578 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
579 let Self { count } = self;
580 expect_revert(ccx.state, None, ccx.depth(), false, false, None, *count)
581 }
582}
583
584impl Cheatcode for expectRevert_7Call {
585 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
586 let Self { revertData, count } = self;
587 expect_revert(ccx.state, Some(revertData.as_ref()), ccx.depth(), false, false, None, *count)
588 }
589}
590
591impl Cheatcode for expectRevert_8Call {
592 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
593 let Self { revertData, count } = self;
594 expect_revert(ccx.state, Some(revertData), ccx.depth(), false, false, None, *count)
595 }
596}
597
598impl Cheatcode for expectRevert_9Call {
599 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
600 let Self { reverter, count } = self;
601 expect_revert(ccx.state, None, ccx.depth(), false, false, Some(*reverter), *count)
602 }
603}
604
605impl Cheatcode for expectRevert_10Call {
606 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
607 let Self { revertData, reverter, count } = self;
608 expect_revert(
609 ccx.state,
610 Some(revertData.as_ref()),
611 ccx.depth(),
612 false,
613 false,
614 Some(*reverter),
615 *count,
616 )
617 }
618}
619
620impl Cheatcode for expectRevert_11Call {
621 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
622 let Self { revertData, reverter, count } = self;
623 expect_revert(
624 ccx.state,
625 Some(revertData),
626 ccx.depth(),
627 false,
628 false,
629 Some(*reverter),
630 *count,
631 )
632 }
633}
634
635impl Cheatcode for expectPartialRevert_0Call {
636 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
637 let Self { revertData } = self;
638 expect_revert(ccx.state, Some(revertData.as_ref()), ccx.depth(), false, true, None, 1)
639 }
640}
641
642impl Cheatcode for expectPartialRevert_1Call {
643 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
644 let Self { revertData, reverter } = self;
645 expect_revert(
646 ccx.state,
647 Some(revertData.as_ref()),
648 ccx.depth(),
649 false,
650 true,
651 Some(*reverter),
652 1,
653 )
654 }
655}
656
657impl Cheatcode for _expectCheatcodeRevert_0Call {
658 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
659 expect_revert(ccx.state, None, ccx.depth(), true, false, None, 1)
660 }
661}
662
663impl Cheatcode for _expectCheatcodeRevert_1Call {
664 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
665 let Self { revertData } = self;
666 expect_revert(ccx.state, Some(revertData.as_ref()), ccx.depth(), true, false, None, 1)
667 }
668}
669
670impl Cheatcode for _expectCheatcodeRevert_2Call {
671 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
672 let Self { revertData } = self;
673 expect_revert(ccx.state, Some(revertData), ccx.depth(), true, false, None, 1)
674 }
675}
676
677impl Cheatcode for expectSafeMemoryCall {
678 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
679 let Self { min, max } = *self;
680 expect_safe_memory(ccx.state, min, max, ccx.depth().try_into()?)
681 }
682}
683
684impl Cheatcode for stopExpectSafeMemoryCall {
685 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
686 let Self {} = self;
687 ccx.state.allowed_mem_writes.remove(&ccx.depth().try_into()?);
688 Ok(Default::default())
689 }
690}
691
692impl Cheatcode for expectSafeMemoryCallCall {
693 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
694 let Self { min, max } = *self;
695 expect_safe_memory(ccx.state, min, max, (ccx.depth() + 1).try_into()?)
696 }
697}
698
699impl RevertParameters for ExpectedRevert {
700 fn reverter(&self) -> Option<Address> {
701 self.reverter
702 }
703
704 fn reason(&self) -> Option<&[u8]> {
705 self.reason.as_ref().map(|b| &***b)
706 }
707
708 fn partial_match(&self) -> bool {
709 self.partial_match
710 }
711}
712
713impl ExpectedRevert {
714 pub(crate) const fn needs_processing(
721 &self,
722 cheatcode_call: bool,
723 call_failed: bool,
724 depth: usize,
725 internal_expect_revert: bool,
726 ) -> bool {
727 let went_deeper = self.max_depth > self.depth;
728 match self.kind {
729 ExpectedRevertKind::Default => {
730 if cheatcode_call {
732 return false;
733 }
734 if call_failed {
736 return true;
737 }
738 if !internal_expect_revert && went_deeper {
740 return true;
741 }
742 if depth == 0 {
744 return true;
745 }
746 !internal_expect_revert
749 }
750 ExpectedRevertKind::Cheatcode { pending_processing } => {
753 cheatcode_call && !pending_processing
754 }
755 }
756 }
757}
758
759fn expect_call(
763 state: &mut CheatcodesCore,
764 target: &Address,
765 calldata: &Bytes,
766 scheme: Option<ExpectedCallScheme>,
767 mut expected: ExpectedCallData,
768) -> Result {
769 let expecteds = state.expected_calls.entry(*target).or_default();
770
771 if let Some(value) = expected.value
772 && value > U256::ZERO
773 {
774 let positive_value_cost_stipend = 2300;
777 if let Some(gas) = &mut expected.gas {
778 *gas += positive_value_cost_stipend;
779 }
780 if let Some(min_gas) = &mut expected.min_gas {
781 *min_gas += positive_value_cost_stipend;
782 }
783 }
784
785 match expecteds.entry((calldata.clone(), scheme)) {
786 Entry::Occupied(mut entry) => {
787 ensure!(
788 expected.call_type == ExpectedCallType::NonCount,
789 "counted expected calls can only bet set once"
790 );
791 let (existing, _) = entry.get_mut();
792 ensure!(
793 existing.call_type == ExpectedCallType::NonCount,
794 "cannot overwrite a counted expectCall with a non-counted expectCall"
795 );
796 existing.count += 1;
797 }
798 Entry::Vacant(entry) => {
799 entry.insert((expected, 0));
800 }
801 }
802
803 Ok(Default::default())
804}
805
806pub(crate) fn observe_call(
808 expected_calls_for_target: &mut ExpectedCallsForTarget,
809 input: &[u8],
810 value: Option<U256>,
811 gas_limit: u64,
812 scheme: ExpectedCallScheme,
813) {
814 for ((calldata, expected_scheme), (expected, actual_count)) in expected_calls_for_target {
816 if calldata.len() <= input.len() &&
819 input.get(..calldata.len()) == Some(calldata.as_ref()) &&
821 expected.value.is_none_or(|expected_value| Some(expected_value) == value) &&
823 expected.gas.is_none_or(|gas| gas == gas_limit) &&
825 expected.min_gas.is_none_or(|min_gas| min_gas <= gas_limit) &&
827 expected_scheme.is_none_or(|expected_scheme| expected_scheme == scheme)
829 {
830 *actual_count += 1;
831 }
832 }
833}
834
835pub(crate) fn first_unmet_call(tracker: &ExpectedCallTracker, succeeded: bool) -> Option<String> {
840 let (address, calldata, scheme, expected, actual_count) = tracker
841 .iter()
842 .flat_map(|(address, calldatas)| {
843 calldatas.iter().map(move |((calldata, scheme), (expected, actual_count))| {
844 (address, calldata, scheme, expected, actual_count)
845 })
846 })
847 .filter(|(_, _, _, expected, actual_count)| match expected.call_type {
848 ExpectedCallType::Count => expected.count != **actual_count,
850 ExpectedCallType::NonCount => expected.count > **actual_count,
852 })
853 .min_by_key(|(address, calldata, scheme, ..)| {
854 (*address, *calldata, call_scheme_rank(**scheme))
855 })?;
856
857 let ExpectedCallData { gas, min_gas, value, count, .. } = expected;
858 let expected_values = [
859 Some(format!("data {}", hex::encode_prefixed(calldata))),
860 value.as_ref().map(|v| format!("value {v}")),
861 gas.map(|g| format!("gas {g}")),
862 min_gas.map(|g| format!("minimum gas {g}")),
863 scheme.map(|scheme| format!("call type {scheme:?}")),
864 ]
865 .into_iter()
866 .flatten()
867 .join(", ");
868 let but = if succeeded {
869 let s = if *actual_count == 1 { "" } else { "s" };
870 format!("was called {actual_count} time{s}")
871 } else {
872 "the call reverted instead; \
873 ensure you're testing the happy path when using `expectCall`"
874 .to_string()
875 };
876 let s = if *count == 1 { "" } else { "s" };
877 Some(format!(
878 "expected call to {address} with {expected_values} \
879 to be called {count} time{s}, but {but}"
880 ))
881}
882
883const fn call_scheme_rank(scheme: Option<ExpectedCallScheme>) -> u8 {
884 match scheme {
885 None => 0,
886 Some(ExpectedCallScheme::Call) => 1,
887 Some(ExpectedCallScheme::CallCode) => 2,
888 Some(ExpectedCallScheme::DelegateCall) => 3,
889 Some(ExpectedCallScheme::StaticCall) => 4,
890 }
891}
892
893fn expect_emit<FEN: FoundryEvmNetwork>(
894 state: &mut Cheatcodes<FEN>,
895 depth: usize,
896 checks: [bool; 5],
897 address: Option<Address>,
898 anonymous: bool,
899 count: u64,
900) -> Result {
901 let expected_emit = ExpectedEmit {
902 depth,
903 checks,
904 address,
905 found: false,
906 log: None,
907 anonymous,
908 count,
909 mismatch_error: None,
910 };
911 if let Some(found_emit_pos) = state.expected_emits.iter().position(|(emit, _)| emit.found) {
912 state.expected_emits.insert(found_emit_pos, (expected_emit, Default::default()));
915 } else {
916 state.expected_emits.push_back((expected_emit, Default::default()));
918 }
919
920 Ok(Default::default())
921}
922
923fn expect_create<FEN: FoundryEvmNetwork>(
924 state: &mut Cheatcodes<FEN>,
925 bytecode: Bytes,
926 deployer: Address,
927 create_scheme: CreateScheme,
928) -> Result {
929 let expected_create = ExpectedCreate { bytecode, deployer, create_scheme };
930 state.expected_creates.push(expected_create);
931
932 Ok(Default::default())
933}
934
935fn expect_revert<FEN: FoundryEvmNetwork>(
936 state: &mut Cheatcodes<FEN>,
937 reason: Option<&[u8]>,
938 depth: usize,
939 cheatcode: bool,
940 partial_match: bool,
941 reverter: Option<Address>,
942 count: u64,
943) -> Result {
944 ensure!(
945 state.expected_revert.is_none(),
946 "you must call another function prior to expecting a second revert"
947 );
948 state.expected_revert = Some(ExpectedRevert {
949 reason: reason.map(Bytes::copy_from_slice),
950 depth,
951 kind: if cheatcode {
952 ExpectedRevertKind::Cheatcode { pending_processing: true }
953 } else {
954 ExpectedRevertKind::Default
955 },
956 partial_match,
957 reverter,
958 reverted_by: None,
959 max_depth: depth,
960 count,
961 actual_count: 0,
962 });
963 Ok(Default::default())
964}
965
966fn expect_safe_memory<FEN: FoundryEvmNetwork>(
967 state: &mut Cheatcodes<FEN>,
968 start: u64,
969 end: u64,
970 depth: u64,
971) -> Result {
972 ensure!(start < end, "memory range start ({start}) is greater than end ({end})");
973 #[expect(clippy::single_range_in_vec_init)] let offsets = state.allowed_mem_writes.entry(depth).or_insert_with(|| vec![0..0x60]);
975 offsets.push(start..end);
976 Ok(Default::default())
977}
978
979pub(crate) fn observe_create(
983 expected_creates: &mut Vec<ExpectedCreate>,
984 deployer: Address,
985 create_scheme: impl Fn() -> CreateScheme,
986 bytecode: &Bytes,
987) {
988 if let Some((index, _)) = expected_creates.iter().find_position(|expected_create| {
989 expected_create.deployer == deployer
990 && expected_create.create_scheme.eq(create_scheme())
991 && expected_create.bytecode == *bytecode
992 }) {
993 expected_creates.swap_remove(index);
994 }
995}
996
997pub(crate) fn first_unmet_create(expected_creates: &[ExpectedCreate]) -> Option<String> {
999 let expected_create = expected_creates.first()?;
1000 Some(format!(
1001 "expected {} call by address {} for bytecode {} but not found",
1002 expected_create.create_scheme,
1003 hex::encode_prefixed(expected_create.deployer),
1004 hex::encode_prefixed(&expected_create.bytecode),
1005 ))
1006}
1007
1008#[cfg(test)]
1009mod tests {
1010 use super::*;
1011 use alloy_primitives::{address, bytes};
1012
1013 const TARGET: Address = address!("0x5615dEB798BB3E4dFa0139dFa1b3D433Cc23b72f");
1014
1015 fn expected(
1016 value: Option<U256>,
1017 gas: Option<u64>,
1018 min_gas: Option<u64>,
1019 count: u64,
1020 call_type: ExpectedCallType,
1021 ) -> ExpectedCallData {
1022 ExpectedCallData { value, gas, min_gas, count, call_type }
1023 }
1024
1025 fn tracker(
1026 calldata: Bytes,
1027 scheme: Option<ExpectedCallScheme>,
1028 data: ExpectedCallData,
1029 ) -> ExpectedCallTracker {
1030 let mut tracker = ExpectedCallTracker::default();
1031 tracker.entry(TARGET).or_default().insert((calldata, scheme), (data, 0));
1032 tracker
1033 }
1034
1035 fn seen(
1036 tracker: &ExpectedCallTracker,
1037 calldata: &Bytes,
1038 scheme: Option<ExpectedCallScheme>,
1039 ) -> u64 {
1040 tracker[&TARGET][&(calldata.clone(), scheme)].1
1041 }
1042
1043 fn observe(tracker: &mut ExpectedCallTracker, input: &[u8], value: Option<U256>, gas: u64) {
1044 observe_call(
1045 tracker.get_mut(&TARGET).unwrap(),
1046 input,
1047 value,
1048 gas,
1049 ExpectedCallScheme::Call,
1050 );
1051 }
1052
1053 #[test]
1054 fn observe_call_matches_calldata_prefix() {
1055 let selector = bytes!("771602f7");
1056 let full = bytes!("771602f7aabb");
1057 let mut t = tracker(
1058 selector.clone(),
1059 None,
1060 expected(None, None, None, 1, ExpectedCallType::NonCount),
1061 );
1062 t.entry(TARGET).or_default().insert(
1063 (full.clone(), None),
1064 (expected(None, None, None, 1, ExpectedCallType::NonCount), 0),
1065 );
1066
1067 observe(&mut t, &full, None, 0);
1068 observe(&mut t, &selector, None, 0);
1069 observe(&mut t, &bytes!("12345678"), None, 0);
1070
1071 assert_eq!(seen(&t, &selector, None), 2);
1072 assert_eq!(seen(&t, &full, None), 1);
1073 }
1074
1075 #[test]
1076 fn observe_call_filters_value() {
1077 let calldata = bytes!("c290d691");
1078 let mut t = tracker(
1079 calldata.clone(),
1080 None,
1081 expected(Some(U256::from(1)), None, None, 1, ExpectedCallType::NonCount),
1082 );
1083
1084 observe(&mut t, &calldata, Some(U256::from(2)), 0);
1085 observe(&mut t, &calldata, None, 0);
1086 assert_eq!(seen(&t, &calldata, None), 0);
1087
1088 observe(&mut t, &calldata, Some(U256::from(1)), 0);
1089 assert_eq!(seen(&t, &calldata, None), 1);
1090
1091 let mut zero = tracker(
1093 calldata.clone(),
1094 None,
1095 expected(Some(U256::ZERO), None, None, 1, ExpectedCallType::NonCount),
1096 );
1097 observe(&mut zero, &calldata, None, 0);
1098 assert_eq!(seen(&zero, &calldata, None), 0);
1099 observe(&mut zero, &calldata, Some(U256::ZERO), 0);
1100 assert_eq!(seen(&zero, &calldata, None), 1);
1101
1102 let mut any = tracker(
1104 calldata.clone(),
1105 None,
1106 expected(None, None, None, 1, ExpectedCallType::NonCount),
1107 );
1108 observe(&mut any, &calldata, Some(U256::from(5)), 0);
1109 assert_eq!(seen(&any, &calldata, None), 1);
1110 }
1111
1112 #[test]
1113 fn observe_call_filters_gas_and_min_gas() {
1114 let calldata = bytes!("771602f7");
1115 let mut gas = tracker(
1116 calldata.clone(),
1117 None,
1118 expected(None, Some(25_000), None, 1, ExpectedCallType::NonCount),
1119 );
1120 observe(&mut gas, &calldata, None, 24_999);
1121 observe(&mut gas, &calldata, None, 25_001);
1122 assert_eq!(seen(&gas, &calldata, None), 0);
1123 observe(&mut gas, &calldata, None, 25_000);
1124 assert_eq!(seen(&gas, &calldata, None), 1);
1125
1126 let mut min_gas = tracker(
1127 calldata.clone(),
1128 None,
1129 expected(None, None, Some(50_000), 1, ExpectedCallType::NonCount),
1130 );
1131 observe(&mut min_gas, &calldata, None, 49_999);
1132 assert_eq!(seen(&min_gas, &calldata, None), 0);
1133 observe(&mut min_gas, &calldata, None, 50_000);
1134 observe(&mut min_gas, &calldata, None, 60_000);
1135 assert_eq!(seen(&min_gas, &calldata, None), 2);
1136 }
1137
1138 #[test]
1139 fn observe_call_filters_scheme() {
1140 let calldata = bytes!("771602f7");
1141 let mut t = tracker(
1142 calldata.clone(),
1143 Some(ExpectedCallScheme::DelegateCall),
1144 expected(None, None, None, 1, ExpectedCallType::NonCount),
1145 );
1146
1147 observe_call(t.get_mut(&TARGET).unwrap(), &calldata, None, 0, ExpectedCallScheme::Call);
1148 assert_eq!(seen(&t, &calldata, Some(ExpectedCallScheme::DelegateCall)), 0);
1149
1150 observe_call(
1151 t.get_mut(&TARGET).unwrap(),
1152 &calldata,
1153 None,
1154 0,
1155 ExpectedCallScheme::DelegateCall,
1156 );
1157 assert_eq!(seen(&t, &calldata, Some(ExpectedCallScheme::DelegateCall)), 1);
1158 }
1159
1160 #[test]
1161 fn first_unmet_call_compares_counts() {
1162 let calldata = bytes!("771602f7");
1163 let mut count =
1164 tracker(calldata.clone(), None, expected(None, None, None, 2, ExpectedCallType::Count));
1165 let mut non_count =
1166 tracker(calldata, None, expected(None, None, None, 2, ExpectedCallType::NonCount));
1167
1168 for seen in [1, 3] {
1169 count.get_mut(&TARGET).unwrap().values_mut().next().unwrap().1 = seen;
1170 assert!(first_unmet_call(&count, true).is_some(), "count with {seen} calls");
1171 }
1172 count.get_mut(&TARGET).unwrap().values_mut().next().unwrap().1 = 2;
1173 assert_eq!(first_unmet_call(&count, true), None);
1174
1175 non_count.get_mut(&TARGET).unwrap().values_mut().next().unwrap().1 = 1;
1176 assert!(first_unmet_call(&non_count, true).is_some());
1177 for seen in [2, 3] {
1178 non_count.get_mut(&TARGET).unwrap().values_mut().next().unwrap().1 = seen;
1179 assert_eq!(first_unmet_call(&non_count, true), None, "non-count with {seen} calls");
1180 }
1181 }
1182
1183 #[test]
1184 fn first_unmet_call_reports_smallest_unmet_key() {
1185 let low = address!("0000000000000000000000000000000000000001");
1186 let high = address!("0000000000000000000000000000000000000002");
1187 let ordered = [
1188 (low, bytes!("01"), None, ""),
1189 (low, bytes!("01"), Some(ExpectedCallScheme::Call), ", call type Call"),
1190 (low, bytes!("01"), Some(ExpectedCallScheme::CallCode), ", call type CallCode"),
1191 (low, bytes!("01"), Some(ExpectedCallScheme::DelegateCall), ", call type DelegateCall"),
1192 (low, bytes!("01"), Some(ExpectedCallScheme::StaticCall), ", call type StaticCall"),
1193 (low, bytes!("02"), None, ""),
1194 (high, bytes!("00"), None, ""),
1195 (high, bytes!("01"), None, ""),
1196 ];
1197
1198 for offset in 0..ordered.len() {
1199 let mut t = ExpectedCallTracker::default();
1200 t.entry(Address::ZERO).or_default().insert(
1202 (Bytes::new(), None),
1203 (expected(None, None, None, 1, ExpectedCallType::NonCount), 1),
1204 );
1205 for index in (0..ordered.len()).rev() {
1206 let (address, calldata, scheme, _) = &ordered[(index + offset) % ordered.len()];
1207 t.entry(*address).or_default().insert(
1208 (calldata.clone(), *scheme),
1209 (expected(None, None, None, 1, ExpectedCallType::NonCount), 0),
1210 );
1211 }
1212
1213 for (address, calldata, scheme, suffix) in &ordered {
1214 assert_eq!(
1215 first_unmet_call(&t, true).unwrap(),
1216 format!(
1217 "expected call to {address} with data {}{suffix} to be called 1 time, \
1218 but was called 0 times",
1219 hex::encode_prefixed(calldata),
1220 ),
1221 );
1222 t.get_mut(address).unwrap().remove(&(calldata.clone(), *scheme));
1223 }
1224 assert_eq!(first_unmet_call(&t, true), None);
1225 }
1226 }
1227
1228 #[test]
1229 fn first_unmet_call_message() {
1230 let calldata = bytes!("771602f7");
1231 let mut t = tracker(
1232 calldata.clone(),
1233 Some(ExpectedCallScheme::DelegateCall),
1234 expected(Some(U256::from(1)), Some(2), Some(3), 2, ExpectedCallType::Count),
1235 );
1236 t.get_mut(&TARGET).unwrap().values_mut().next().unwrap().1 = 1;
1237
1238 assert_eq!(
1239 first_unmet_call(&t, true).unwrap(),
1240 "expected call to 0x5615dEB798BB3E4dFa0139dFa1b3D433Cc23b72f with data 0x771602f7, \
1241 value 1, gas 2, minimum gas 3, call type DelegateCall to be called 2 times, \
1242 but was called 1 time"
1243 );
1244 assert_eq!(
1245 first_unmet_call(&t, false).unwrap(),
1246 "expected call to 0x5615dEB798BB3E4dFa0139dFa1b3D433Cc23b72f with data 0x771602f7, \
1247 value 1, gas 2, minimum gas 3, call type DelegateCall to be called 2 times, \
1248 but the call reverted instead; ensure you're testing the happy path when using \
1249 `expectCall`"
1250 );
1251
1252 let single =
1253 tracker(calldata, None, expected(None, None, None, 1, ExpectedCallType::NonCount));
1254 assert_eq!(
1255 first_unmet_call(&single, true).unwrap(),
1256 "expected call to 0x5615dEB798BB3E4dFa0139dFa1b3D433Cc23b72f with data 0x771602f7 \
1257 to be called 1 time, but was called 0 times"
1258 );
1259 }
1260
1261 #[test]
1262 fn observe_create_converts_the_scheme_only_for_a_matching_deployer() {
1263 let bytecode = bytes!("6080");
1264 let mut expected_creates = vec![ExpectedCreate {
1265 deployer: Address::ZERO,
1266 bytecode: bytecode.clone(),
1267 create_scheme: CreateScheme::Create,
1268 }];
1269
1270 observe_create(&mut expected_creates, TARGET, || unreachable!(), &bytecode);
1271 assert_eq!(expected_creates.len(), 1);
1272
1273 observe_create(&mut expected_creates, Address::ZERO, || CreateScheme::Create, &bytecode);
1274 assert!(expected_creates.is_empty());
1275 }
1276
1277 #[test]
1278 fn internal_expect_revert_waits_for_failure_before_root() {
1279 let expected_revert = ExpectedRevert {
1280 reason: None,
1281 depth: 1,
1282 kind: ExpectedRevertKind::Default,
1283 partial_match: false,
1284 reverter: None,
1285 reverted_by: None,
1286 max_depth: 1,
1287 count: 1,
1288 actual_count: 0,
1289 };
1290
1291 assert!(expected_revert.needs_processing(false, true, 1, true));
1292 assert!(!expected_revert.needs_processing(false, false, 1, true));
1293 }
1294}