bat-cli 0.22.5

Blockchain Auditor Toolkit (BAT)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
use error_stack::{Report, ResultExt};
use serde::{Deserialize, Serialize};
use std::{error::Error, fmt, fs};

use crate::batbelt::evm::types::{
    AccessControlType, EvmContract, EvmContractType, EvmEvent, EvmFileItem, EvmModifierDef,
    EvmMutability, EvmParam, EvmVisibility, StorageVariable,
};

#[derive(Debug)]
pub struct EvmMetadataError;

impl fmt::Display for EvmMetadataError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("EvmMetadata error")
    }
}

impl Error for EvmMetadataError {}

pub type EvmMetadataResult<T> = error_stack::Result<T, EvmMetadataError>;

const EVM_METADATA_FILE: &str = "BatMetadata.json";

/// EVM-specific BatMetadata structure (separate from SVM metadata).
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct EvmBatMetadata {
    pub contracts: Vec<ContractMetadata>,
    pub entry_points: Vec<EntryPointMetadata>,
    pub function_dependencies: Vec<FunctionDependency>,
    pub interfaces: Vec<InterfaceMetadata>,
    #[serde(default)]
    pub file_items: Vec<EvmFileItem>,
    #[serde(default)]
    pub miro: MiroMetadataRef,
    /// AI-supplied resolutions for the runtime-dynamic interface→implementation
    /// bindings that static analysis cannot pin (see `unresolved_calls`): interface
    /// type name → the concrete in-scope contract it points to in this deployment.
    /// The deploy graph follows these to reach downstream storage writers. Preserved
    /// across `sonar` regeneration (like `miro`); written by `bat-cli resolve`.
    #[serde(default)]
    pub resolutions: std::collections::HashMap<String, String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContractMetadata {
    pub metadata_id: String,
    pub name: String,
    pub file_path: String,
    pub contract_type: EvmContractType,
    pub base_contracts: Vec<String>,
    pub functions: Vec<FunctionMetadata>,
    pub state_variables: Vec<StorageVariable>,
    pub events: Vec<EvmEvent>,
    pub modifiers: Vec<EvmModifierDef>,
    pub line: usize,
    /// true if the contract comes from lib/ (external dependency)
    #[serde(default)]
    pub external: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FunctionMetadata {
    pub metadata_id: String,
    pub name: String,
    pub contract_name: String,
    pub visibility: EvmVisibility,
    pub mutability: EvmMutability,
    pub modifiers: Vec<String>,
    pub params: Vec<EvmParam>,
    pub returns: Vec<EvmParam>,
    pub line: usize,
    #[serde(default)]
    pub end_line: usize,
    pub is_constructor: bool,
    /// True when the function has no real implementation: a bodyless declaration
    /// (interface / abstract method) or an empty `{}` body (an unoverridden
    /// `virtual` stub). Nothing to screenshot, so the diagram skips it — the
    /// concrete implementation is drawn via its own (resolved) call.
    #[serde(default)]
    pub is_stub: bool,
    /// Storage locations this function writes (state vars / storage-pointer
    /// paths). Empty for a function that mutates no storage. Drives the
    /// "writes storage" marker on the diagram.
    #[serde(default)]
    pub storage_writes: Vec<String>,
    /// The same storage writes, each with the FILE line (1-based) it happens on,
    /// so a diagram can point at the exact statement inside the function, not just
    /// mark the whole function. Empty for a function that mutates no storage.
    #[serde(default)]
    pub storage_write_sites: Vec<StorageWriteSite>,
    /// External calls that could NOT be statically resolved to a unique in-scope
    /// function — a call on an interface-typed receiver whose concrete target is a
    /// runtime property. An AI resolves these against the wiring to complete the
    /// cross-contract storage-change picture; each carries best-effort candidates.
    #[serde(default)]
    pub unresolved_calls: Vec<UnresolvedCall>,
    /// Calls on an interface-typed receiver with NO in-scope implementer — the
    /// target contract's source is not in the repo (e.g. an ERC-20 passed by
    /// address). We cannot know which storage they touch, only that a non-view one
    /// MIGHT mutate the callee's state. The diagram flags these lines as an
    /// unverified external state-change boundary.
    #[serde(default)]
    pub unknown_external_calls: Vec<ExternalUnknownCall>,
}

/// A call whose target contract has no in-scope source: an interface-typed
/// receiver (`inferred_type`) that nothing in the repo implements. The concrete
/// storage effect is unknowable statically.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExternalUnknownCall {
    pub receiver: String,
    pub method: String,
    #[serde(default)]
    pub inferred_type: String,
}

/// A single storage write located in the source: the lvalue path and the file
/// line (1-based) it sits on.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StorageWriteSite {
    pub name: String,
    pub line: usize,
}

/// An external call whose concrete target static analysis cannot pin down (the
/// receiver is an interface-typed variable — the implementation is bound at
/// runtime). Surfaced so an AI can resolve it from the deploy/wiring.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnresolvedCall {
    /// The call receiver as written, e.g. `positionManager`, `$.borrowerOps`.
    pub receiver: String,
    /// The method invoked, e.g. `adjustPosition`.
    pub method: String,
    /// The receiver's declared type when known (an interface, e.g.
    /// `IBorrowerOperations`); empty when it couldn't be typed (a struct field or
    /// local — resolved in a later phase).
    #[serde(default)]
    pub inferred_type: String,
    /// In-scope concrete contracts that plausibly implement this call (implementers
    /// of `inferred_type` that define `method`, else any in-scope contract defining
    /// `method`). The AI picks the real one from the wiring.
    #[serde(default)]
    pub candidates: Vec<String>,
    /// Functions (`Contract.function`) that WRITE this call's receiver — where its
    /// concrete address is wired. Reading these tells the AI which candidate is the
    /// real one. Empty when the receiver isn't a tracked storage location.
    #[serde(default)]
    pub assigned_in: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EntryPointMetadata {
    pub metadata_id: String,
    pub name: String,
    pub contract_name: String,
    pub function_metadata_id: String,
    pub access_control: Vec<AccessControlType>,
    pub storage_reads: Vec<String>,
    pub storage_writes: Vec<String>,
    pub external_calls: Vec<String>,
    pub events_emitted: Vec<String>,
    pub modifiers: Vec<String>,
    pub dependencies: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FunctionDependency {
    pub function_metadata_id: String,
    pub callees: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InterfaceMetadata {
    pub name: String,
    pub implemented_by: Vec<String>,
    pub functions: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct MiroMetadataRef {
    pub frames: Vec<MiroFrameRef>,
    /// State of the automatic deployment (`miro evm-auto-deploy`).
    #[serde(default)]
    pub auto: AutoDeployState,
}

/// Everything the automatic deployment needs to stay incremental.
///
/// Keeping the allocator state here is what lets us place frames without ever
/// asking Miro where there is free space: the board is scanned once, when the
/// region is reserved, and never again.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AutoDeployState {
    pub region: Option<ShelfState>,
    #[serde(default)]
    pub frames: Vec<AutoDeployedFrame>,
}

/// Serializable snapshot of the shelf allocator cursor.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShelfState {
    pub origin_x: f64,
    pub origin_y: f64,
    pub cursor_x: f64,
    pub cursor_y: f64,
    pub row_height: f64,
    pub row_max_width: f64,
    pub gutter: f64,
}

impl ShelfState {
    pub fn to_allocator(&self) -> crate::batbelt::miro::layout::ShelfAllocator {
        crate::batbelt::miro::layout::ShelfAllocator {
            origin_x: self.origin_x,
            origin_y: self.origin_y,
            cursor_x: self.cursor_x,
            cursor_y: self.cursor_y,
            row_height: self.row_height,
            row_max_width: self.row_max_width,
            gutter: self.gutter,
        }
    }
}

impl From<&crate::batbelt::miro::layout::ShelfAllocator> for ShelfState {
    fn from(allocator: &crate::batbelt::miro::layout::ShelfAllocator) -> Self {
        Self {
            origin_x: allocator.origin_x,
            origin_y: allocator.origin_y,
            cursor_x: allocator.cursor_x,
            cursor_y: allocator.cursor_y,
            row_height: allocator.row_height,
            row_max_width: allocator.row_max_width,
            gutter: allocator.gutter,
        }
    }
}

/// One entry point's frame, with every item it owns, so a re-deploy can update
/// instead of duplicating.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutoDeployedFrame {
    pub entry_point: String,
    pub frame_id: String,
    pub frame_url: String,
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
    /// `(graph node id, miro image id)`
    pub images: Vec<(String, String)>,
    pub connector_ids: Vec<String>,
    /// Invisible shapes used as connector endpoints, one per call site.
    #[serde(default)]
    pub marker_ids: Vec<String>,
    /// Red rectangles marking storage-writing nodes, so a recycle deletes them too.
    #[serde(default)]
    pub border_ids: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MiroFrameRef {
    pub entry_point_name: String,
    pub frame_id: String,
    pub frame_url: String,
    #[serde(default)]
    pub images_deployed: bool,
    #[serde(default)]
    pub entry_point_image_id: String,
    #[serde(default)]
    pub validations_image_id: String,
    #[serde(default)]
    pub dependency_image_ids: Vec<String>,
}

impl EvmBatMetadata {
    pub fn read_metadata() -> EvmMetadataResult<Self> {
        let content = fs::read_to_string(EVM_METADATA_FILE).map_err(|e| {
            Report::new(EvmMetadataError)
                .attach_printable(format!("Cannot read {}: {}", EVM_METADATA_FILE, e))
        })?;
        let metadata: Self = serde_json::from_str(&content).map_err(|e| {
            Report::new(EvmMetadataError)
                .attach_printable(format!("Cannot parse {}: {}", EVM_METADATA_FILE, e))
        })?;
        Ok(metadata)
    }

    pub fn save_metadata(&self) -> EvmMetadataResult<()> {
        let content = serde_json::to_string_pretty(self).map_err(|e| {
            Report::new(EvmMetadataError)
                .attach_printable(format!("Cannot serialize metadata: {}", e))
        })?;
        fs::write(EVM_METADATA_FILE, content).map_err(|e| {
            Report::new(EvmMetadataError)
                .attach_printable(format!("Cannot write {}: {}", EVM_METADATA_FILE, e))
        })?;
        Ok(())
    }

    pub fn create_empty() -> EvmMetadataResult<()> {
        let metadata = Self::default();
        metadata.save_metadata()
    }

    /// Atomically read, modify, and save EVM metadata.
    pub fn update_metadata<F>(f: F) -> EvmMetadataResult<()>
    where
        F: FnOnce(&mut EvmBatMetadata),
    {
        let mut metadata = Self::read_metadata()?;
        f(&mut metadata);
        metadata.save_metadata()
    }

    /// Get miro frame ref by entry point name.
    pub fn get_miro_frame_by_ep_name(&self, ep_name: &str) -> Option<&MiroFrameRef> {
        self.miro
            .frames
            .iter()
            .find(|f| f.entry_point_name == ep_name)
    }

    pub fn get_contract_by_name(&self, name: &str) -> Option<&ContractMetadata> {
        self.contracts.iter().find(|c| c.name == name)
    }

    pub fn get_function_by_id(&self, id: &str) -> Option<&FunctionMetadata> {
        self.contracts
            .iter()
            .flat_map(|c| c.functions.iter())
            .find(|f| f.metadata_id == id)
    }

    pub fn get_entry_point_by_name(&self, name: &str) -> Option<&EntryPointMetadata> {
        self.entry_points.iter().find(|ep| ep.name == name)
    }

    /// Build metadata from parsed contracts and file-level items.
    /// Preserves existing Miro metadata if present.
    pub fn from_contracts(contracts: Vec<EvmContract>, file_items: Vec<EvmFileItem>) -> Self {
        let mut metadata = Self::default();
        // Preserve existing Miro metadata across sonar re-runs.
        // Extract only the "miro" field from raw JSON to avoid losing frames
        // when other struct fields change between versions.
        if let Ok(content) = fs::read_to_string(EVM_METADATA_FILE) {
            if let Ok(json) = serde_json::from_str::<serde_json::Value>(&content) {
                if let Some(miro_val) = json.get("miro") {
                    if let Ok(miro) = serde_json::from_value::<MiroMetadataRef>(miro_val.clone()) {
                        metadata.miro = miro;
                    }
                }
                // Preserve AI-supplied interface resolutions across regeneration.
                if let Some(res_val) = json.get("resolutions") {
                    if let Ok(res) = serde_json::from_value::<
                        std::collections::HashMap<String, String>,
                    >(res_val.clone())
                    {
                        metadata.resolutions = res;
                    }
                }
            }
        }
        metadata.file_items = file_items;

        // Per contract: its own storage-variable names (excluding constants /
        // immutables, which don't live in storage) and its base contracts — so a
        // function's writes to inherited state variables resolve too.
        let mut own_state_vars: std::collections::HashMap<String, Vec<String>> =
            std::collections::HashMap::new();
        let mut contract_bases: std::collections::HashMap<String, Vec<String>> =
            std::collections::HashMap::new();
        for c in &contracts {
            let names: Vec<String> = c
                .storage_variables
                .iter()
                .filter(|v| !v.is_constant && !v.is_immutable)
                .map(|v| v.name.clone())
                .collect();
            own_state_vars.insert(c.name.clone(), names);
            contract_bases.insert(c.name.clone(), c.base_contracts.clone());
        }

        // Cross-contract call resolution lookups (Phase 1):
        //  - known contract names (a `Contract.method` call is already resolved),
        //  - impl_map: interface/base name → contracts declaring `is <name>`,
        //  - method_map: method name → concrete contracts that define it,
        //  - own_var_types: contract → (state-var name → declared type).
        let contract_names: std::collections::HashSet<String> =
            contracts.iter().map(|c| c.name.clone()).collect();
        let is_interface: std::collections::HashSet<String> = contracts
            .iter()
            .filter(|c| c.contract_type == EvmContractType::Interface)
            .map(|c| c.name.clone())
            .collect();
        // Vendored (`lib/`) contracts — a call resolving only to these (SafeERC20,
        // mocks, OZ tokens) is not an in-scope storage change worth chasing.
        let external_contracts: std::collections::HashSet<String> = contracts
            .iter()
            .filter(|c| c.external)
            .map(|c| c.name.clone())
            .collect();
        let mut impl_map: std::collections::HashMap<String, Vec<String>> =
            std::collections::HashMap::new();
        let mut method_map: std::collections::HashMap<String, Vec<String>> =
            std::collections::HashMap::new();
        let mut own_var_types: std::collections::HashMap<
            String,
            std::collections::HashMap<String, String>,
        > = std::collections::HashMap::new();
        // Per contract: single-return function → its return type (for accessor calls
        // like `_s()` whose result is a storage struct, used to type `_s().field`).
        let mut own_fn_returns: std::collections::HashMap<
            String,
            std::collections::HashMap<String, String>,
        > = std::collections::HashMap::new();
        for c in &contracts {
            for b in &c.base_contracts {
                impl_map.entry(b.clone()).or_default().push(c.name.clone());
            }
            if c.contract_type != EvmContractType::Interface {
                for f in &c.functions {
                    method_map
                        .entry(f.name.clone())
                        .or_default()
                        .push(c.name.clone());
                }
            }
            let vt: std::collections::HashMap<String, String> = c
                .storage_variables
                .iter()
                .map(|v| (v.name.clone(), v.type_name.clone()))
                .collect();
            own_var_types.insert(c.name.clone(), vt);
            let fr: std::collections::HashMap<String, String> = c
                .functions
                .iter()
                .filter(|f| f.returns.len() == 1)
                .map(|f| (f.name.clone(), f.returns[0].type_name.clone()))
                .collect();
            own_fn_returns.insert(c.name.clone(), fr);
        }

        // struct name → (field name → declared type), for typing `$.field` receivers.
        let mut struct_fields: std::collections::HashMap<
            String,
            std::collections::HashMap<String, String>,
        > = std::collections::HashMap::new();
        for c in &contracts {
            for s in &c.structs {
                let fields: std::collections::HashMap<String, String> = s
                    .fields
                    .iter()
                    .map(|f| (f.name.clone(), f.type_name.clone()))
                    .collect();
                struct_fields.insert(s.name.clone(), fields);
            }
        }

        // Callee graph, built from the same single parse per function (no separate pass).
        let mut all_deps: Vec<FunctionDependency> = Vec::new();

        for contract in &contracts {
            let contract_id = format!("{}_{}", contract.file_path, contract.name);

            // State-variable name → type, visible to this contract (own + inherited).
            let mut var_types: std::collections::HashMap<String, String> =
                std::collections::HashMap::new();
            {
                let mut seen: std::collections::HashSet<String> =
                    std::collections::HashSet::new();
                let mut stack = vec![contract.name.clone()];
                while let Some(name) = stack.pop() {
                    if !seen.insert(name.clone()) {
                        continue;
                    }
                    if let Some(vt) = own_var_types.get(&name) {
                        for (k, v) in vt {
                            var_types.entry(k.clone()).or_insert_with(|| v.clone());
                        }
                    }
                    if let Some(bases) = contract_bases.get(&name) {
                        stack.extend(bases.iter().cloned());
                    }
                }
            }

            // Function return types visible to this contract (own + inherited),
            // for typing accessor-call receivers like `_s().field`.
            let mut fn_returns: std::collections::HashMap<String, String> =
                std::collections::HashMap::new();
            {
                let mut seen: std::collections::HashSet<String> =
                    std::collections::HashSet::new();
                let mut stack = vec![contract.name.clone()];
                while let Some(name) = stack.pop() {
                    if !seen.insert(name.clone()) {
                        continue;
                    }
                    if let Some(fr) = own_fn_returns.get(&name) {
                        for (k, v) in fr {
                            fn_returns.entry(k.clone()).or_insert_with(|| v.clone());
                        }
                    }
                    if let Some(bases) = contract_bases.get(&name) {
                        stack.extend(bases.iter().cloned());
                    }
                }
            }

            // State variables visible to every function in this contract.
            let mut state_vars: Vec<String> = Vec::new();
            let mut seen_contracts: std::collections::HashSet<String> =
                std::collections::HashSet::new();
            resolve_state_vars(
                &contract.name,
                &own_state_vars,
                &contract_bases,
                &mut seen_contracts,
                &mut state_vars,
            );

            let mut functions: Vec<FunctionMetadata> = Vec::new();
            for f in &contract.functions {
                let func_id = format!("{}_{}_{}", contract.file_path, contract.name, f.name);
                // Parameters passed as `storage` references (e.g. a library's
                // `execute(CvammStorage storage $, …)`) are storage pointers too.
                let storage_params: Vec<String> = f
                    .params
                    .iter()
                    .filter(|p| p.storage_location.as_deref() == Some("storage"))
                    .map(|p| p.name.clone())
                    .collect();
                // ONE parse per function: storage writes, external call targets,
                // local/param types AND callee names, all from a single AST walk.
                let analysis = crate::batbelt::evm::parser::call_resolver::analyze_body(
                    &f.body_source,
                    &state_vars,
                    &storage_params,
                );
                let storage_writes = analysis.storage_writes;
                // body_source starts at the function's first file line, so a
                // source-relative write line maps to a file line by that offset.
                let storage_write_sites = analysis
                    .storage_write_sites
                    .iter()
                    .map(|(name, src_line)| StorageWriteSite {
                        name: name.clone(),
                        line: f.line + src_line.saturating_sub(1),
                    })
                    .collect();
                // Receiver types visible here: state vars (inherited) + params + locals.
                let mut local_var_types = var_types.clone();
                for (n, t) in &analysis.local_types {
                    local_var_types.insert(n.clone(), t.clone());
                }
                let (unresolved_calls, unknown_external_calls) = compute_unresolved_calls(
                    &analysis.call_targets,
                    &local_var_types,
                    &struct_fields,
                    &fn_returns,
                    &contract_names,
                    &is_interface,
                    &external_contracts,
                    &impl_map,
                    &method_map,
                );
                all_deps.push(FunctionDependency {
                    function_metadata_id: func_id.clone(),
                    callees: analysis.call_names,
                });
                functions.push(FunctionMetadata {
                    metadata_id: func_id,
                    name: f.name.clone(),
                    contract_name: contract.name.clone(),
                    visibility: f.visibility.clone(),
                    mutability: f.mutability.clone(),
                    modifiers: f.modifiers.clone(),
                    params: f.params.clone(),
                    returns: f.returns.clone(),
                    line: f.line,
                    end_line: f.end_line,
                    is_constructor: f.is_constructor,
                    is_stub: is_stub_body(&f.body_source),
                    storage_writes,
                    storage_write_sites,
                    unresolved_calls,
                    unknown_external_calls,
                });
            }

            let contract_metadata = ContractMetadata {
                metadata_id: contract_id,
                name: contract.name.clone(),
                file_path: contract.file_path.clone(),
                contract_type: contract.contract_type.clone(),
                base_contracts: contract.base_contracts.clone(),
                functions,
                state_variables: contract.storage_variables.clone(),
                events: contract.events.clone(),
                modifiers: contract.modifiers.clone(),
                line: contract.line,
                external: contract.external,
            };

            metadata.contracts.push(contract_metadata);
        }
        metadata.function_dependencies = all_deps;

        // Build entry points from external/public functions (skip external/lib contracts)
        for contract in &metadata.contracts.clone() {
            if contract.external {
                continue;
            }
            if matches!(
                contract.contract_type,
                EvmContractType::Interface | EvmContractType::Library
            ) {
                continue;
            }

            // Detect overloaded function names within this contract
            let ep_functions: Vec<_> = contract
                .functions
                .iter()
                .filter(|f| {
                    matches!(
                        f.visibility,
                        EvmVisibility::External | EvmVisibility::Public
                    ) && !f.is_constructor
                })
                .collect();

            let mut name_counts: std::collections::HashMap<String, usize> =
                std::collections::HashMap::new();
            for func in &ep_functions {
                *name_counts.entry(func.name.clone()).or_insert(0) += 1;
            }

            for func in &ep_functions {
                // If overloaded, append param types to disambiguate
                let ep_name = if name_counts.get(&func.name).copied().unwrap_or(0) > 1 {
                    let param_types = func
                        .params
                        .iter()
                        .map(|p| p.type_name.clone())
                        .collect::<Vec<_>>()
                        .join(",");
                    format!("{}.{}({})", contract.name, func.name, param_types)
                } else {
                    format!("{}.{}", contract.name, func.name)
                };

                let ep = EntryPointMetadata {
                    metadata_id: format!("ep_{}", func.metadata_id),
                    name: ep_name,
                    contract_name: contract.name.clone(),
                    function_metadata_id: func.metadata_id.clone(),
                    access_control: detect_access_control(&func.modifiers),
                    storage_reads: vec![],
                    storage_writes: func.storage_writes.clone(),
                    external_calls: vec![],
                    events_emitted: vec![],
                    modifiers: func.modifiers.clone(),
                    dependencies: vec![],
                };
                metadata.entry_points.push(ep);
            }
        }

        metadata
    }
}

/// True when a function has no real implementation to screenshot: a bodyless
/// declaration (interface / abstract method — `body_source` is empty) or an
/// empty `{}` block (an unoverridden `virtual` stub).
fn is_stub_body(body_source: &str) -> bool {
    if body_source.trim().is_empty() {
        return true;
    }
    // The first `{` opens the body; if only whitespace sits before the matching
    // final `}`, the body is empty.
    if let (Some(open), Some(close)) = (body_source.find('{'), body_source.rfind('}')) {
        if open < close && body_source[open + 1..close].trim().is_empty() {
            return true;
        }
    }
    false
}

/// Collect a contract's effective storage-variable names: its own plus every
/// inherited one, walking base contracts transitively (guarded against cycles).
fn resolve_state_vars(
    name: &str,
    own: &std::collections::HashMap<String, Vec<String>>,
    bases: &std::collections::HashMap<String, Vec<String>>,
    seen: &mut std::collections::HashSet<String>,
    out: &mut Vec<String>,
) {
    if !seen.insert(name.to_string()) {
        return;
    }
    if let Some(vars) = own.get(name) {
        out.extend(vars.iter().cloned());
    }
    if let Some(base_names) = bases.get(name) {
        for base in base_names {
            resolve_state_vars(base, own, bases, seen, out);
        }
    }
}

/// Drop the "noise" from every function's `unresolved_calls`: an interface call is
/// only worth resolving if it can REACH a storage write. We taint every function
/// that can reach a write — over the static call graph PLUS the unresolved→candidate
/// edges, seeded by the direct writers — then keep an unresolved call only when one
/// of its candidates is tainted. So `stable.balanceOf` (a read whose candidates never
/// mutate) is dropped, while `$.borrowerOps.adjustPosition` (which reaches a write
/// several hops down) is kept.
pub fn prune_unresolved_noise(metadata: &mut EvmBatMetadata) {
    use std::collections::{HashMap, HashSet};
    // Lookups from the metadata (no re-parsing: reuse `function_dependencies`).
    let contract_names: HashSet<String> =
        metadata.contracts.iter().map(|c| c.name.clone()).collect();
    let contract_file: HashMap<String, String> = metadata
        .contracts
        .iter()
        .map(|c| (c.name.clone(), c.file_path.clone()))
        .collect();
    let mut method_map: HashMap<String, Vec<String>> = HashMap::new();
    let mut bases: HashMap<String, Vec<String>> = HashMap::new();
    let mut caller_contract: HashMap<String, String> = HashMap::new();
    for c in &metadata.contracts {
        bases.insert(c.name.clone(), c.base_contracts.clone());
        for f in &c.functions {
            method_map
                .entry(f.name.clone())
                .or_default()
                .push(c.name.clone());
            caller_contract.insert(f.metadata_id.clone(), c.name.clone());
        }
    }
    let fid = |contract: &str, method: &str| -> Option<String> {
        contract_file
            .get(contract)
            .map(|fp| format!("{fp}_{contract}_{method}"))
    };

    // Edges: static callees (from function_dependencies) + unresolved candidates.
    let mut edges: HashMap<String, Vec<String>> = HashMap::new();
    for dep in &metadata.function_dependencies {
        let Some(cname) = caller_contract.get(&dep.function_metadata_id) else {
            continue;
        };
        let out = edges.entry(dep.function_metadata_id.clone()).or_default();
        for callee in &dep.callees {
            if let Some((tgt, method)) = callee.split_once('.') {
                if contract_names.contains(tgt) {
                    if let Some(id) = fid(tgt, method) {
                        out.push(id);
                    }
                }
                // `var.method` (interface) flows through unresolved candidates below.
            } else {
                // Internal call: the caller's contract or a base that defines it.
                let mut chain = vec![cname.clone()];
                if let Some(bs) = bases.get(cname) {
                    chain.extend(bs.iter().cloned());
                }
                for cand in chain {
                    if method_map.get(callee).is_some_and(|v| v.contains(&cand)) {
                        if let Some(id) = fid(&cand, callee) {
                            out.push(id);
                        }
                        break;
                    }
                }
            }
        }
    }
    // Seed = direct writers; add the unresolved→candidate edges.
    let mut taint: HashSet<String> = HashSet::new();
    for c in &metadata.contracts {
        for f in &c.functions {
            if !f.storage_writes.is_empty() {
                taint.insert(f.metadata_id.clone());
            }
            let out = edges.entry(f.metadata_id.clone()).or_default();
            for u in &f.unresolved_calls {
                for cand in &u.candidates {
                    if let Some(id) = fid(cand, &u.method) {
                        out.push(id);
                    }
                }
            }
        }
    }

    // Fixpoint by worklist over reverse edges (a caller taints when a callee does).
    let mut rev: HashMap<String, Vec<String>> = HashMap::new();
    for (caller, outs) in &edges {
        for o in outs {
            rev.entry(o.clone()).or_default().push(caller.clone());
        }
    }
    let mut work: Vec<String> = taint.iter().cloned().collect();
    while let Some(t) = work.pop() {
        if let Some(callers) = rev.get(&t) {
            for caller in callers.clone() {
                if taint.insert(caller.clone()) {
                    work.push(caller);
                }
            }
        }
    }

    // Keep an unresolved call only if a candidate can reach a write.
    for c in &mut metadata.contracts {
        for f in &mut c.functions {
            if f.unresolved_calls.is_empty() {
                continue;
            }
            f.unresolved_calls.retain(|u| {
                u.candidates
                    .iter()
                    .any(|cand| fid(cand, &u.method).is_some_and(|id| taint.contains(&id)))
            });
        }
    }

    // Wiring hint: which functions WRITE each call's receiver (where its concrete
    // address is set), so the AI can read those to pick the real candidate.
    let mut write_sites: HashMap<String, Vec<String>> = HashMap::new();
    for c in &metadata.contracts {
        for f in &c.functions {
            for w in &f.storage_writes {
                write_sites
                    .entry(w.clone())
                    .or_default()
                    .push(format!("{}.{}", c.name, f.name));
            }
        }
    }
    for c in &mut metadata.contracts {
        for f in &mut c.functions {
            for u in &mut f.unresolved_calls {
                if let Some(sites) = write_sites.get(&u.receiver) {
                    u.assigned_in = sites.clone();
                    u.assigned_in.sort();
                    u.assigned_in.dedup();
                }
            }
        }
    }
}

/// Compute the external calls a function makes that static analysis cannot pin to
/// a unique in-scope target — the AI-resolution work-list. A `receiver.method` call
/// is emitted when it is NOT already resolved to a single concrete contract via the
/// receiver's declared type; each carries best-effort candidates.
#[allow(clippy::too_many_arguments)]
fn compute_unresolved_calls(
    targets: &[(String, String)],
    var_types: &std::collections::HashMap<String, String>,
    struct_fields: &std::collections::HashMap<String, std::collections::HashMap<String, String>>,
    fn_returns: &std::collections::HashMap<String, String>,
    contract_names: &std::collections::HashSet<String>,
    is_interface: &std::collections::HashSet<String>,
    external_contracts: &std::collections::HashSet<String>,
    impl_map: &std::collections::HashMap<String, Vec<String>>,
    method_map: &std::collections::HashMap<String, Vec<String>>,
) -> (Vec<UnresolvedCall>, Vec<ExternalUnknownCall>) {
    let mut out: Vec<UnresolvedCall> = Vec::new();
    let mut external: Vec<ExternalUnknownCall> = Vec::new();
    let mut seen: std::collections::HashSet<(String, String)> = std::collections::HashSet::new();
    let mut seen_ext: std::collections::HashSet<(String, String)> = std::collections::HashSet::new();

    for (receiver, method) in targets {
        let (receiver, method) = (receiver.clone(), method.clone());
        // Internal dispatch, or a call by contract name (already resolved).
        if receiver == "this" || receiver == "super" || contract_names.contains(&receiver) {
            continue;
        }

        let inferred_type = receiver_type(&receiver, var_types, struct_fields, fn_returns);

        // Implementers of the receiver's declared interface type that define the
        // method — a STATIC, type-proven resolution.
        let typed_impls: Vec<String> = if inferred_type.is_empty() {
            Vec::new()
        } else {
            impl_map
                .get(&inferred_type)
                .map(|impls| {
                    impls
                        .iter()
                        .filter(|c| {
                            !is_interface.contains(*c)
                                && !external_contracts.contains(*c)
                                && method_map.get(&method).is_some_and(|v| v.contains(c))
                        })
                        .cloned()
                        .collect()
                })
                .unwrap_or_default()
        };
        // Exactly one type-proven implementer → unambiguous; the deploy graph follows
        // it. Not AI work.
        if typed_impls.len() == 1 {
            continue;
        }

        // An interface CAST of a runtime address (`IERC20Minimal(x).transfer(...)`,
        // rendered `IERC20Minimal()`) with NO type-proven in-scope implementer is a
        // generic external contract: nothing wires it to a specific in-scope address,
        // so a name-only method match (some unrelated contract that happens to define
        // `transfer`) is a false lead. Flag it as an external boundary, not a
        // resolvable call. A wired variable receiver (`$.borrowerOps`, `_s().CORE`)
        // is NOT a bare cast and keeps the name-inference path below.
        if typed_impls.is_empty()
            && receiver.ends_with("()")
            && is_interface.contains(&inferred_type)
        {
            if seen_ext.insert((receiver.clone(), method.clone())) {
                external.push(ExternalUnknownCall {
                    receiver,
                    method,
                    inferred_type,
                });
            }
            continue;
        }

        // Otherwise: candidates are the type-proven impls if any, else any in-scope
        // concrete contract defining the method (name-inferred, for the AI to confirm).
        let mut candidates: Vec<String> = if !typed_impls.is_empty() {
            typed_impls
        } else {
            method_map.get(&method).cloned().unwrap_or_default()
        };
        candidates.retain(|c| !is_interface.contains(c) && !external_contracts.contains(c));
        candidates.sort();
        candidates.dedup();

        // No plausible in-scope target. If the receiver is interface-typed, its
        // implementation lives outside the repo (e.g. an ERC-20 passed by address):
        // record it as an external unknown so the diagram can flag the line. A bare
        // untyped receiver (a builtin like `abi.encode`) is just noise — skip it.
        if candidates.is_empty() {
            // Only an INTERFACE-typed receiver with no in-scope implementer is a
            // real external contract we lack source for (e.g. IERC20). This excludes
            // value-type library calls (`uint256.mulDiv`), low-level `address.call`,
            // and builtins — none of which are an external contract boundary.
            if is_interface.contains(&inferred_type)
                && seen_ext.insert((receiver.clone(), method.clone()))
            {
                external.push(ExternalUnknownCall {
                    receiver,
                    method,
                    inferred_type,
                });
            }
            continue;
        }
        if seen.insert((receiver.clone(), method.clone())) {
            out.push(UnresolvedCall {
                receiver,
                method,
                inferred_type,
                candidates,
                assigned_in: Vec::new(),
            });
        }
    }
    (out, external)
}

/// The declared type of a call receiver expression: a bare variable (`positionManager`)
/// via `var_types`, or a one-level struct-pointer field (`$.borrowerOps`) via the base
/// variable's struct type and its field types. Empty when it can't be typed.
/// The declared type of a call-receiver expression, following a chain of field
/// accesses of ANY depth: `positionManager`, `$.borrowerOps`, `_s().CORE`,
/// `_s().CORE.owner`. The base is a variable (`var_types`), a cast `IFace()`, or an
/// accessor call `_s()` (its return type via `fn_returns`); each subsequent `.field`
/// steps through the struct's field types. Empty when it can't be typed.
fn receiver_type(
    receiver: &str,
    var_types: &std::collections::HashMap<String, String>,
    struct_fields: &std::collections::HashMap<String, std::collections::HashMap<String, String>>,
    fn_returns: &std::collections::HashMap<String, String>,
) -> String {
    // Strip a qualifier: `CvammStore.CvammStorage` → `CvammStorage`, so it matches the
    // struct/interface names our maps are keyed by.
    let unqualify = |t: &str| t.rsplit('.').next().unwrap_or(t).to_string();

    let mut segments = receiver.split('.');
    let base = match segments.next() {
        Some(b) => b.trim_end_matches("[]"),
        None => return String::new(),
    };
    // Resolve the base segment's type.
    let mut current: Option<String> = if let Some(callee) = base.strip_suffix("()") {
        if callee
            .chars()
            .next()
            .is_some_and(|c| c.is_ascii_uppercase())
            && callee.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
        {
            // A cast `IFace(addr)` → the cast target type.
            Some(callee.to_string())
        } else {
            // An accessor call `_s()` → its return type.
            fn_returns.get(callee).cloned()
        }
    } else if base.contains('(') {
        // A more complex call base we don't model.
        None
    } else {
        var_types.get(base).cloned()
    };

    // Walk each remaining `.field` through the struct's field types.
    for seg in segments {
        let field = seg.trim_end_matches("[]");
        current = current.and_then(|t| {
            struct_fields
                .get(&unqualify(&t))
                .and_then(|fields| fields.get(field))
                .cloned()
        });
        if current.is_none() {
            return String::new();
        }
    }
    current.map(|t| unqualify(&t)).unwrap_or_default()
}

fn detect_access_control(modifiers: &[String]) -> Vec<AccessControlType> {
    let mut result = Vec::new();

    for modifier in modifiers {
        match modifier.as_str() {
            "onlyOwner" => result.push(AccessControlType::OnlyOwner),
            "onlyRole" => result.push(AccessControlType::RoleBased {
                role: "DEFAULT_ADMIN_ROLE".to_string(),
            }),
            other => {
                if other.starts_with("only") {
                    result.push(AccessControlType::CustomModifier {
                        name: other.to_string(),
                    });
                }
            }
        }
    }

    if result.is_empty() {
        result.push(AccessControlType::None);
    }

    result
}