bat-cli 0.28.0

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
//! Which contracts talk to which, on one frame.
//!
//! The question this answers is the one a reader cannot get from reading functions: a function
//! calls here and there, and after forty of them you still do not know that three different
//! contracts write to the same one, or that a contract you thought was a leaf is wired into
//! five others at construction. `deploy` shows one entry point in full depth; this shows the
//! system's shape and nothing else.
//!
//! An edge is a RELATION, not a count. One call is a relation; forty calls are the same
//! relation, and how many there are is a question for the entry point's own diagram. What the
//! edge does carry is its KIND — an ordinary call, an address fixed at construction, or a
//! binding nobody has resolved yet — because those are three different facts about the system.

use std::collections::{BTreeMap, BTreeSet};

use colored::Colorize;
use error_stack::{Report, Result, ResultExt};

use crate::batbelt::evm::metadata::bat_metadata::{ContractMetadata, EvmBatMetadata};
use crate::batbelt::evm::miro::auto_deploy::matches_ignore;
use crate::batbelt::evm::miro::EvmMiroError;
use crate::batbelt::miro::client::MiroClient;

pub struct MapOptions {
    /// Print the relations and stop, touching no board.
    pub dry_run: bool,
    /// Draw the contracts with no source in this repository too — the system's edge.
    pub with_boundaries: bool,
}

/// What kind of relation one contract has with another.
///
/// Ordered by how sure we are of it, which is also the order they are drawn in: a call the
/// scan pinned, then an address fixed at construction, then a binding that is still a guess.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Relation {
    /// A call whose target this scan pinned to one contract.
    Calls,
    /// An address this contract fixes when it is built — `immutable vault = …` in a
    /// constructor. It is a relation even if no call to it survived the pruning: it says the
    /// two are wired together.
    WiresAtConstruction,
    /// A call on an interface with more than one implementer and no `bat-cli resolve` for it.
    /// Drawn dashed: there IS a relation here, and its far end is not known.
    Unresolved,
    /// A call leaving the audited code: a contract with no source in this repository.
    Boundary,
}

impl Relation {
    fn label(self) -> &'static str {
        match self {
            Self::Calls => "calls",
            Self::WiresAtConstruction => "wires at construction",
            Self::Unresolved => "unresolved binding",
            Self::Boundary => "leaves the code",
        }
    }
}

/// `from` → `to`, and what kind of relation it is. One per pair and kind, never one per call.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Edge {
    pub from: String,
    pub to: String,
    pub relation: Relation,
}

pub async fn run(options: MapOptions) -> Result<(), EvmMiroError> {
    // Timed out loud. "It takes a while" is not something to guess about: each phase says how
    // long it took, so the next question is about a number instead of a feeling.
    let started = std::time::Instant::now();
    let mut mark = |what: &str, since: &mut std::time::Instant| {
        println!("    {:>6.1}s  {what}", since.elapsed().as_secs_f64());
        *since = std::time::Instant::now();
    };
    let mut phase = started;
    let metadata = EvmBatMetadata::read_metadata().change_context(EvmMiroError)?;
    mark("reading the metadata", &mut phase);
    // A scan from before the `vendored` flag marks nothing as vendored, so `lib/` — forge-std,
    // OpenZeppelin, the test harnesses — is "in scope" and the map is a map of the test
    // framework. That is not a map with a few extra boxes; it is the wrong picture, and the
    // only honest answer is to stop and say what to run.
    if let Some(count) = predates_vendored(&metadata) {
        return Err(Report::new(EvmMiroError).attach_printable(format!(
            "this scan predates the `vendored` flag: {count} contract(s) under lib/ are marked \
             as in scope — run `bat-cli sonar` to rescan before drawing the map"
        )));
    }
    let edges = relations(&metadata, options.with_boundaries);
    mark("working out the relations", &mut phase);
    if edges.is_empty() {
        return Err(Report::new(EvmMiroError)
            .attach_printable("no relations between contracts — run `bat-cli sonar` first"));
    }

    for line in report(&edges) {
        println!("{line}");
    }
    // An interface declared in this repository that nothing in scope says it implements is
    // drawn as the outside — which is right for `IMirrorFactory` and wrong for an
    // `IListingLaunchpad` that `ListingDesk` implements without `is`. The source cannot tell
    // the two apart; the auditor can, and the line says how to record it.
    let undeclared = undeclared_interfaces(&metadata);
    if !undeclared.is_empty() {
        println!();
        println!(
            "{} interface(s) of this repository nothing in scope declares to implement — \
             treated as outside the code:",
            undeclared.len()
        );
        for name in &undeclared {
            println!("  {name:<28} if a contract here implements it: bat-cli resolve {name} <Contract>");
        }
    }
    // Calls the scan could not type as a contract are not on the map, and a map that leaves
    // something out without saying so is a map the reader trusts more than it deserves.
    let untyped = untyped_receivers(&metadata);
    if !untyped.is_empty() {
        println!();
        println!(
            "{} call(s) whose receiver the scan could not type as a contract — not drawn:",
            untyped.len()
        );
        for line in &untyped {
            println!("  {line}");
        }
    }
    if options.dry_run {
        return Ok(());
    }

    let client = MiroClient::new_refreshed().await.change_context(EvmMiroError)?;
    mark("opening the Miro session", &mut phase);
    let board = client.list_frames().await.change_context(EvmMiroError)?;
    mark(&format!("reading the board ({} frames)", board.len()), &mut phase);
    // To the LEFT of everything. The deployments march rightwards, so a map put on that side
    // ends up wedged between two groups it has nothing to do with, and stays there as the
    // board grows. The left edge is the one side nothing else claims.
    //
    // Nothing is replaced: a second `map` is a second frame, and where it belongs on the board
    // is the auditor's call, not this tool's.
    let obstacles: Vec<crate::batbelt::miro::layout::Rect> = board
        .iter()
        .map(|frame| crate::batbelt::miro::layout::Rect {
            x: frame.x,
            y: frame.y,
            width: frame.width,
            height: frame.height,
        })
        .collect();
    // Measured first, because opening on the left means knowing how wide the thing is.
    let layout = layout_map(&edges);
    mark("laying it out", &mut phase);
    let (left, top) =
        crate::batbelt::miro::layout::ColumnLayout::new().open_left(&obstacles, layout.frame_width);
    let outcome = draw(&client, &edges, layout, left, top).await;
    mark("drawing it", &mut phase);
    println!("    {:>6.1}s  in total", started.elapsed().as_secs_f64());
    outcome
}

/// Size of a contract's box, and the room left around the drawing.
/// Sized for the NAME, not for a frame: a box that fits `StakingQuoteOracle` at a readable
/// size and no more. The first version gave every contract a 2600×700 box with 72-point text
/// in it, so the map was mostly empty box and the arrows between them were hairlines.
const NODE_HEIGHT: f64 = 320.0;
const NODE_FONT: usize = 120;
/// Roughly the width one character takes at that font, plus room on both sides.
const NODE_CHAR: f64 = 70.0;
const NODE_PAD: f64 = 160.0;
const MAP_MARGIN: f64 = 600.0;
/// Thick enough to read at the zoom where the whole map fits, which is the only zoom it is
/// for. Miro refuses anything from 24 up.
const EDGE_WIDTH: &str = "16";

fn node_width(name: &str) -> f64 {
    name.chars().count() as f64 * NODE_CHAR + NODE_PAD * 2.0
}

/// Colours: a call the scan pinned, an address fixed at construction, a binding still unknown,
/// and a call leaving the audited code. They are the board palette's, not the code palette's,
/// because these are arrows between boxes against white.
fn stroke_of(relation: Relation) -> (&'static str, crate::batbelt::miro::client::ConnectorStroke) {
    use crate::batbelt::miro::client::ConnectorStroke;
    match relation {
        Relation::Calls => ("#2d9bf0", ConnectorStroke::Solid),
        Relation::WiresAtConstruction => ("#8fd14f", ConnectorStroke::Solid),
        Relation::Unresolved => ("#f24726", ConnectorStroke::Dashed),
        Relation::Boundary => ("#ff8c00", ConnectorStroke::Dotted),
    }
}

/// Lay the map out: one box per contract, the deploy's own engine, callers above callees.
///
/// Pure, and done before anything is placed, because where the map goes on the board depends
/// on how wide it is — it opens to the LEFT of everything, and that edge can only be found
/// once the width is known.
fn layout_map(edges: &[Edge]) -> crate::batbelt::miro::layout::GraphLayout {
    use crate::batbelt::miro::layout::{layout_graph, LayoutConfig, LayoutEdge, LayoutNode};

    let mut names: Vec<String> = edges
        .iter()
        .flat_map(|edge| [edge.from.clone(), edge.to.clone()])
        .collect();
    names.sort();
    names.dedup();
    let nodes: Vec<LayoutNode> = names
        .iter()
        .map(|name| LayoutNode {
            id: name.clone(),
            width: node_width(name),
            height: NODE_HEIGHT,
        })
        .collect();
    // REVERSED for the layout, and only for the layout. A contract whose address everyone
    // takes in their constructor exists before any of them, and the auditor reads the system
    // the way it is built: what must exist first goes leftmost and the tree grows rightwards.
    // Feeding the engine callee → caller is what puts `Treasury` on the left instead of at
    // the end of the drawing. The arrows still say what they say — A calls B — because that
    // is the fact; it is the PLACEMENT that follows the hierarchy.
    let laid_edges: Vec<LayoutEdge> = edges
        .iter()
        .map(|edge| LayoutEdge {
            from: edge.to.clone(),
            to: edge.from.clone(),
            from_line_fraction: 0.5,
        })
        .collect();

    // The root is what nothing depends on from the left: the contract everything else needs.
    let depends_on_something: BTreeSet<&str> = edges.iter().map(|edge| edge.from.as_str()).collect();
    let root = names
        .iter()
        .find(|name| !depends_on_something.contains(name.as_str()))
        .cloned()
        .unwrap_or_else(|| names[0].clone());

    layout_graph(
        &root,
        &nodes,
        &laid_edges,
        LayoutConfig {
            padding_x: MAP_MARGIN,
            // Room for the legend, which sits in the corner the layout would otherwise start
            // in: four boxes of a row's height each.
            padding_y: MAP_MARGIN + (NODE_HEIGHT + 60.0) * 4.0,
            ..Default::default()
        },
    )
}

/// Put the map on the board: one box per contract, one arrow per relation.
async fn draw(
    client: &MiroClient,
    edges: &[Edge],
    layout: crate::batbelt::miro::layout::GraphLayout,
    left: f64,
    top: f64,
) -> Result<(), EvmMiroError> {
    use crate::batbelt::miro::client::{ArrowEnd, ConnectorStyle, RelativeAnchor};

    let frame_id = client
        .create_frame(
            "map: who talks to whom",
            left + layout.frame_width / 2.0,
            top + layout.frame_height / 2.0,
            layout.frame_width,
            layout.frame_height,
            None,
        )
        .await
        .change_context(EvmMiroError)?;

    // The legend, in the frame's own top-left corner. Four colours are four facts, and a
    // reader who has to ask what green means is reading a picture that does not say what it
    // knows. One box per relation kind, filled with that relation's colour.
    let mut legend = tokio::task::JoinSet::new();
    for (index, relation) in [
        Relation::Calls,
        Relation::WiresAtConstruction,
        Relation::Unresolved,
        Relation::Boundary,
    ]
    .into_iter()
    .enumerate()
    {
        let (colour, _) = stroke_of(relation);
        let text = relation.label();
        let width = node_width(text);
        let client = client.clone();
        let frame_id = frame_id.clone();
        let y = MAP_MARGIN / 2.0 + index as f64 * (NODE_HEIGHT + 60.0);
        legend.spawn(async move {
            client
                .create_label(
                    text,
                    MAP_MARGIN / 2.0 + width / 2.0,
                    y,
                    width,
                    NODE_HEIGHT,
                    NODE_FONT,
                    colour,
                    Some(&frame_id),
                )
                .await
        });
    }
    while let Some(joined) = legend.join_next().await {
        joined
            .map_err(|error| Report::new(EvmMiroError).attach_printable(error.to_string()))?
            .change_context(EvmMiroError)?;
    }

    // The boxes first, all at once: nothing can be connected before both of its ends exist.
    let mut placing = tokio::task::JoinSet::new();
    for placed in &layout.nodes {
        let client = client.clone();
        let frame_id = frame_id.clone();
        let name = placed.id.clone();
        let (x, y) = (placed.x, placed.y);
        placing.spawn(async move {
            client
                .create_label(
                    &name,
                    x,
                    y,
                    node_width(&name),
                    NODE_HEIGHT,
                    NODE_FONT,
                    "#ffffff",
                    Some(&frame_id),
                )
                .await
                .map(|id| (name, id))
        });
    }
    let mut boxes: BTreeMap<String, String> = BTreeMap::new();
    while let Some(joined) = placing.join_next().await {
        let (name, id) = joined
            .map_err(|error| Report::new(EvmMiroError).attach_printable(error.to_string()))?
            .change_context(EvmMiroError)?;
        boxes.insert(name, id);
    }
    println!("    {} {} contract(s) drawn", "✓".green(), boxes.len());

    // Then the arrows, also together. Box to box, with Miro routing them: unlike a call graph
    // inside a frame, there is no exact line to land on here — the relation is the whole fact.
    let mut drawing = tokio::task::JoinSet::new();
    for edge in edges {
        let (Some(from), Some(to)) = (boxes.get(&edge.from), boxes.get(&edge.to)) else {
            continue;
        };
        let (colour, stroke) = stroke_of(edge.relation);
        let client = client.clone();
        let (from, to) = (from.clone(), to.clone());
        drawing.spawn(async move {
            client
                .create_connector(
                    // Out of the RIGHT edge and into the LEFT one: the layout runs left to
                    // right, and leaving from the bottom made every arrow take a detour
                    // around its own box before it could head anywhere.
                    &from,
                    RelativeAnchor::new(1.0, 0.5),
                    &to,
                    RelativeAnchor::new(0.0, 0.5),
                    ConnectorStyle {
                        stroke_color: colour.to_string(),
                        stroke_width: EDGE_WIDTH.to_string(),
                        stroke,
                        caption: None,
                        arrow: ArrowEnd::End,
                    },
                )
                .await
        });
    }
    let mut drawn = 0usize;
    while let Some(joined) = drawing.join_next().await {
        joined
            .map_err(|error| Report::new(EvmMiroError).attach_printable(error.to_string()))?
            .change_context(EvmMiroError)?;
        drawn += 1;
    }
    println!("    {} {drawn} relation(s) drawn", "✓".green());
    println!("  {}", client.frame_url(&frame_id).blue());
    Ok(())
}

/// Every relation between contracts, one per pair and kind.
///
/// Three sources, which is the point: a call the scan pinned by type, a binding it refused to
/// pin, and the addresses a constructor fixes. The third is the one an auditor cannot get by
/// reading a call graph at all — a contract can be wired to another it never calls in the
/// paths that survived pruning, and that wiring is still a fact about the system.
pub fn relations(metadata: &EvmBatMetadata, with_boundaries: bool) -> Vec<Edge> {
    let in_scope: BTreeSet<&str> = metadata
        .contracts
        .iter()
        .filter(|contract| !contract.vendored)
        .map(|contract| contract.name.as_str())
        .collect();
    let ignored = |name: &str, path: &str| {
        metadata
            .ignored_contracts
            .iter()
            .any(|pattern| matches_ignore(pattern, name, path))
    };

    let mut found: BTreeSet<Edge> = BTreeSet::new();
    for contract in metadata.contracts.iter().filter(|c| !c.vendored) {
        if ignored(&contract.name, &contract.file_path) {
            continue;
        }
        let mut record = |to: &str, relation: Relation| {
            // A contract talking to itself is not a relation worth a line on a map: it is what
            // the contract's own deployment shows.
            if to.is_empty() || to == contract.name {
                return;
            }
            found.insert(Edge {
                from: contract.name.clone(),
                to: to.to_string(),
                relation,
            });
        };

        // One rule for every kind of relation: what the type NAME means at runtime decides
        // where the arrow lands, and `with_boundaries` only decides whether an arrow that
        // leaves the code is drawn at all.
        let aim = |type_name: &str, relation: Relation| -> Option<(String, Relation)> {
            match classify_type(metadata, type_name) {
                TypeTarget::Contract(target) => Some((target, relation)),
                TypeTarget::Open(name) => Some((name, Relation::Unresolved)),
                TypeTarget::Outside(name) if with_boundaries => Some((name, Relation::Boundary)),
                TypeTarget::Outside(_) | TypeTarget::NotAContract => None,
            }
        };

        for function in &contract.functions {
            for call in &function.resolved_calls {
                if in_scope.contains(call.contract.as_str()) {
                    record(&call.contract, Relation::Calls);
                }
            }
            let typed = function
                .unresolved_calls
                .iter()
                .map(|call| call.inferred_type.as_str())
                .chain(
                    function
                        .unknown_external_calls
                        .iter()
                        .map(|call| call.inferred_type.as_str()),
                );
            for type_name in typed {
                if let Some((to, relation)) = aim(type_name, Relation::Calls) {
                    record(&to, relation);
                }
            }
        }

        for wired in wired_at_construction(contract) {
            if let Some((to, relation)) = aim(&wired, Relation::WiresAtConstruction) {
                record(&to, relation);
            }
        }
    }

    // A pair that both calls and is wired keeps the call: the stronger fact wins, and two
    // arrows between the same two boxes is the noise this map exists to avoid.
    let mut best: BTreeMap<(String, String), Relation> = BTreeMap::new();
    for edge in found {
        best.entry((edge.from.clone(), edge.to.clone()))
            .and_modify(|existing| *existing = (*existing).min(edge.relation))
            .or_insert(edge.relation);
    }
    best.into_iter()
        .map(|((from, to), relation)| Edge { from, to, relation })
        .collect()
}

/// The contracts whose address this one fixes when it is built.
///
/// An `immutable` of a contract type, or a state variable of one assigned in the constructor,
/// is the system's wiring written down: `YieldRouter` holds `vault`, `venue`, `oracle` and
/// `distributor` from the moment it exists. The type is the relation — what the variable is
/// called tells you nothing a map can draw.
fn wired_at_construction(contract: &ContractMetadata) -> Vec<String> {
    let constructor_writes: BTreeSet<&str> = contract
        .functions
        .iter()
        .filter(|function| function.is_constructor)
        .flat_map(|function| function.storage_writes.iter())
        .map(|write| write.split(['.', '[']).next().unwrap_or(write))
        .collect();

    contract
        .state_variables
        .iter()
        .filter(|variable| {
            // Fixed at construction: an immutable (which can be assigned nowhere else) or a
            // variable the constructor assigns.
            variable.is_immutable || constructor_writes.contains(variable.name.as_str())
        })
        // The raw type, which `classify_type` then reads: an interface collapses into its
        // implementer, a struct or an `address` is not a relation at all. Deciding that here
        // by the first letter being a capital is what let `Limits` and `CurveStep[]` onto
        // the map as contracts.
        .map(|variable| variable.type_name.trim().to_string())
        .collect()
}

/// What a type name stands for on the map.
#[derive(Debug, Clone, PartialEq, Eq)]
enum TypeTarget {
    /// A deployable contract in scope — the box an arrow can land on.
    Contract(String),
    /// An interface with several deployable implementers and no resolution: a relation whose
    /// far end is a question for the auditor, never a guess.
    Open(String),
    /// Code that is not in this repository: an interface nothing in scope implements, or an
    /// instance of somebody else's contract (`ERC20 mirror`) held by address.
    Outside(String),
    /// A struct, an enum, a type alias, a mapping, or nothing at all — not a relation.
    NotAContract,
}

/// What a type NAME means at runtime. An interface is not a thing on the board: it is the
/// shape of a call, and the contract at the other end is what the reader is looking for.
/// `IAscendLaunchpad` and `AscendLaunchpad` were two boxes for one contract, which made the
/// system look bigger than it is and left the reader deciding which of the two to believe.
///
/// Collapsed when the answer is a FACT: a resolution the auditor recorded, or exactly one
/// DEPLOYABLE contract in scope declaring the interface as a base. Only deployable ones
/// count, because `IListingLaunchpad is IAscendLaunchpad` also "declares it as a base" and an
/// interface extending an interface was enough to make the count two and block the collapse.
/// Several deployable implementers and no resolution stays open — that is a question, and the
/// map says so.
///
/// An interface is IN SCOPE — the scan stores it like any other contract — and that is why
/// "is it in scope" cannot be the question here: answering yes for `IAscendLaunchpad` is how
/// the map drew the interface beside the contract that implements it. And a VENDORED contract
/// used as a type is not collapsible either: `ERC20 mirror` is an instance of somebody else's
/// token at another address, and the fact that `AscendCoreToken is ERC20` says nothing about
/// which token `mirror` is. Folding it into its in-scope child made a real boundary vanish as
/// a self-call.
fn classify_type(metadata: &EvmBatMetadata, type_name: &str) -> TypeTarget {
    use crate::batbelt::evm::types::EvmContractType;

    let Some(name) = contract_type_name(type_name) else {
        return TypeTarget::NotAContract;
    };
    let copies: Vec<&ContractMetadata> =
        metadata.contracts.iter().filter(|c| c.name == name).collect();
    if copies.is_empty() {
        return TypeTarget::NotAContract;
    }
    // Reading the kind off ANY copy is enough: three vendored `IERC20`s are all interfaces.
    // What matters is whether some copy is in scope and what kind of thing the name is.
    let is_interface = copies
        .iter()
        .any(|c| c.contract_type == EvmContractType::Interface);
    let in_scope = copies.iter().find(|c| !c.vendored);
    let deployable_in_scope = in_scope
        .is_some_and(|c| c.contract_type == EvmContractType::Contract);

    if deployable_in_scope {
        return TypeTarget::Contract(name.to_string());
    }
    if let Some(recorded) = metadata.resolutions.get(name) {
        if metadata.contracts.iter().any(|c| !c.vendored && c.name == *recorded) {
            return TypeTarget::Contract(recorded.clone());
        }
    }
    // Collapsible: an interface (wherever it lives) or an abstract contract of this project.
    // A vendored abstract or concrete contract is neither — it is an address of their code.
    let collapsible = is_interface
        || in_scope.is_some_and(|c| c.contract_type == EvmContractType::Abstract);
    if !collapsible {
        return TypeTarget::Outside(name.to_string());
    }
    let mut implementers = metadata
        .contracts
        .iter()
        .filter(|c| !c.vendored && c.contract_type == EvmContractType::Contract)
        .filter(|c| c.base_contracts.iter().any(|base| base == name));
    match (implementers.next(), implementers.next()) {
        (Some(only), None) => TypeTarget::Contract(only.name.clone()),
        (Some(_), Some(_)) => TypeTarget::Open(name.to_string()),
        (None, _) if is_interface => TypeTarget::Outside(name.to_string()),
        // An abstract contract of this project that nothing deployable derives from: there is
        // no box for it and no outside either, so it is a question.
        (None, _) => TypeTarget::Open(name.to_string()),
    }
}

/// The contract name a declared type can stand for, or `None` when the type cannot name a
/// contract at all: a mapping, an elementary type, or nothing.
///
/// `CurveStep[]` is an array of whatever `CurveStep` is, so the brackets are stripped; a
/// `mapping(Id => PendingUint192)` is storage, not an address, and is never a relation.
fn contract_type_name(type_name: &str) -> Option<&str> {
    let mut name = type_name.trim();
    if name.is_empty() || name.starts_with("mapping(") {
        return None;
    }
    while let Some(open) = name.rfind('[') {
        if !name.ends_with(']') {
            break;
        }
        name = name[..open].trim_end();
    }
    // `uint256`, `address`, `bytes32`: a contract name starts with a capital.
    name.chars()
        .next()
        .filter(|first| first.is_ascii_uppercase())
        .map(|_| name)
}

/// Calls whose receiver the scan could not type as a contract — an empty type, a struct
/// field it could not follow — one line each, so the report can say what the map leaves out.
pub fn untyped_receivers(metadata: &EvmBatMetadata) -> Vec<String> {
    let mut lines: BTreeSet<String> = BTreeSet::new();
    for contract in metadata.contracts.iter().filter(|c| !c.vendored) {
        for function in &contract.functions {
            let calls = function
                .unresolved_calls
                .iter()
                .map(|call| (&call.receiver, &call.method, &call.inferred_type))
                .chain(
                    function
                        .unknown_external_calls
                        .iter()
                        .map(|call| (&call.receiver, &call.method, &call.inferred_type)),
                );
            for (receiver, method, inferred_type) in calls {
                if classify_type(metadata, inferred_type) == TypeTarget::NotAContract {
                    let shown = if inferred_type.is_empty() {
                        "untyped".to_string()
                    } else {
                        inferred_type.clone()
                    };
                    lines.insert(format!(
                        "{}.{}: {receiver}.{method} ({shown})",
                        contract.name, function.name
                    ));
                }
            }
        }
    }
    lines.into_iter().collect()
}

/// Interfaces of this repository that some in-scope contract calls or holds, and that no
/// deployable contract declares as a base and no resolution binds.
///
/// Each one is classified as the outside, and for most of them that is the truth — an
/// interface file in `src/interfaces/` describing a protocol deployed elsewhere. But a contract
/// may implement an interface without `is IFace`, and then the map has just drawn a call into
/// this project's own code as a call out of it. Listing them is the difference between a
/// wrong map and a map with a question on it.
pub fn undeclared_interfaces(metadata: &EvmBatMetadata) -> Vec<String> {
    use crate::batbelt::evm::types::EvmContractType;
    let own_interfaces: BTreeSet<&str> = metadata
        .contracts
        .iter()
        .filter(|c| !c.vendored && c.contract_type == EvmContractType::Interface)
        .map(|c| c.name.as_str())
        .collect();
    let mut found: BTreeSet<String> = BTreeSet::new();
    for contract in metadata.contracts.iter().filter(|c| !c.vendored) {
        let referenced = contract
            .functions
            .iter()
            .flat_map(|function| {
                function
                    .unresolved_calls
                    .iter()
                    .map(|call| call.inferred_type.clone())
                    .chain(
                        function
                            .unknown_external_calls
                            .iter()
                            .map(|call| call.inferred_type.clone()),
                    )
            })
            .chain(wired_at_construction(contract));
        for type_name in referenced {
            if let TypeTarget::Outside(name) = classify_type(metadata, &type_name) {
                if own_interfaces.contains(name.as_str()) {
                    found.insert(name);
                }
            }
        }
    }
    found.into_iter().collect()
}

/// How many contracts a scan without the `vendored` flag left in scope under `lib/`, or
/// `None` when the scan knows what is vendored.
///
/// The flag was added after the first scans shipped, and `serde(default)` reads its absence
/// as "nothing is vendored" — which is also, exactly, what a project with no dependencies
/// looks like. The two are told apart by the paths: a contract under a `lib/` segment with
/// `vendored == false` can only come from a scan that never set the flag.
pub fn predates_vendored(metadata: &EvmBatMetadata) -> Option<usize> {
    if metadata.contracts.iter().any(|contract| contract.vendored) {
        return None;
    }
    let under_lib = metadata
        .contracts
        .iter()
        .filter(|contract| {
            contract
                .file_path
                .split('/')
                .any(|segment| segment == "lib")
        })
        .count();
    (under_lib > 0).then_some(under_lib)
}

/// The relations as lines, grouped by the contract they leave from.
pub fn report(edges: &[Edge]) -> Vec<String> {
    let mut lines = vec![
        format!(
            "{} relation(s) between contracts — one per pair, whatever the number of calls",
            edges.len()
        ),
        String::new(),
    ];
    let mut current = String::new();
    for edge in edges {
        if edge.from != current {
            current = edge.from.clone();
            lines.push(current.clone());
        }
        lines.push(format!("  → {:<28} {}", edge.to, edge.relation.label()));
    }

    // Who the system turns around: the contracts most things point at.
    let mut incoming: BTreeMap<&str, usize> = BTreeMap::new();
    for edge in edges {
        *incoming.entry(edge.to.as_str()).or_default() += 1;
    }
    let mut ranked: Vec<(&str, usize)> = incoming.into_iter().collect();
    ranked.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
    lines.push(String::new());
    lines.push("reached by the most contracts:".to_string());
    for (name, count) in ranked.iter().take(5) {
        lines.push(format!("  {name:<28} {count} contract(s) talk to it"));
    }
    lines
}

#[cfg(test)]
mod map_test {
    use super::{Edge, Relation};

    /// A pair that both calls and is wired is ONE edge: the call, which is the stronger fact.
    #[test]
    fn the_stronger_relation_wins_a_pair() {
        assert!(Relation::Calls < Relation::WiresAtConstruction);
        assert!(Relation::WiresAtConstruction < Relation::Unresolved);
    }

    /// Edges sort by their source, which is what makes the report read as one block per
    /// contract.
    #[test]
    fn edges_group_by_their_source() {
        let mut edges = vec![
            Edge { from: "B".into(), to: "C".into(), relation: Relation::Calls },
            Edge { from: "A".into(), to: "C".into(), relation: Relation::Calls },
            Edge { from: "A".into(), to: "B".into(), relation: Relation::Calls },
        ];
        edges.sort();
        assert_eq!(edges[0].from, "A");
        assert_eq!(edges[0].to, "B");
        assert_eq!(edges[2].from, "B");
    }

    use super::{classify_type, predates_vendored, relations, undeclared_interfaces, TypeTarget};
    use crate::batbelt::evm::metadata::bat_metadata::{
        ContractMetadata, EvmBatMetadata, FunctionMetadata, UnresolvedCall,
    };
    use crate::batbelt::evm::types::{
        EvmContractType, EvmFileItem, EvmFileItemKind, EvmMutability, EvmVisibility,
        StorageVariable,
    };

    fn contract(
        name: &str,
        kind: EvmContractType,
        bases: &[&str],
        vendored: bool,
    ) -> ContractMetadata {
        ContractMetadata {
            metadata_id: name.to_string(),
            name: name.to_string(),
            using_libraries: Vec::new(),
            file_path: format!("./{}/{name}.sol", if vendored { "lib/dep/src" } else { "src" }),
            contract_type: kind,
            base_contracts: bases.iter().map(|b| b.to_string()).collect(),
            functions: Vec::new(),
            state_variables: Vec::new(),
            events: Vec::new(),
            modifiers: Vec::new(),
            line: 1,
            vendored,
        }
    }

    /// A function making one call on a receiver of the given interface type.
    fn calling(inferred_type: &str) -> FunctionMetadata {
        FunctionMetadata {
            metadata_id: format!("f_{inferred_type}"),
            name: "poke".to_string(),
            contract_name: String::new(),
            visibility: EvmVisibility::External,
            mutability: EvmMutability::NonPayable,
            modifiers: Vec::new(),
            params: Vec::new(),
            returns: Vec::new(),
            line: 1,
            end_line: 2,
            is_constructor: false,
            is_stub: false,
            storage_writes: Vec::new(),
            storage_write_sites: Vec::new(),
            unresolved_calls: vec![UnresolvedCall {
                receiver: "target".to_string(),
                method: "poke".to_string(),
                inferred_type: inferred_type.to_string(),
                candidates: Vec::new(),
                assigned_in: Vec::new(),
            }],
            unknown_external_calls: Vec::new(),
            resolved_calls: Vec::new(),
        }
    }

    fn immutable(type_name: &str) -> StorageVariable {
        StorageVariable {
            name: type_name.to_lowercase(),
            type_name: type_name.to_string(),
            visibility: EvmVisibility::Internal,
            is_constant: false,
            is_immutable: true,
            line: 3,
        }
    }

    fn pairs(edges: &[Edge]) -> Vec<(String, String, Relation)> {
        edges
            .iter()
            .map(|edge| (edge.from.clone(), edge.to.clone(), edge.relation))
            .collect()
    }

    /// `IListingLaunchpad is IAscendLaunchpad` declares the interface as a base too, and
    /// counting it made two implementers out of one: the collapse was blocked and the
    /// interface was drawn beside the contract that implements it. Only a deployable
    /// contract implements anything.
    #[test]
    fn an_interface_extending_an_interface_does_not_block_the_collapse() {
        let mut caller = contract("AscendCtoReceiver", EvmContractType::Contract, &[], false);
        caller.functions.push(calling("IAscendLaunchpad"));
        let metadata = EvmBatMetadata {
            contracts: vec![
                caller,
                contract("AscendLaunchpad", EvmContractType::Contract, &["IAscendLaunchpad"], false),
                contract("IAscendLaunchpad", EvmContractType::Interface, &[], false),
                contract("IListingLaunchpad", EvmContractType::Interface, &["IAscendLaunchpad"], false),
            ],
            ..Default::default()
        };
        assert_eq!(
            classify_type(&metadata, "IAscendLaunchpad"),
            TypeTarget::Contract("AscendLaunchpad".to_string())
        );
        assert_eq!(
            pairs(&relations(&metadata, true)),
            vec![("AscendCtoReceiver".to_string(), "AscendLaunchpad".to_string(), Relation::Calls)]
        );
    }

    /// Two deployable implementers and no resolution is a question, drawn as one.
    #[test]
    fn two_deployable_implementers_stay_an_open_question() {
        let mut caller = contract("Router", EvmContractType::Contract, &[], false);
        caller.functions.push(calling("IVault"));
        let metadata = EvmBatMetadata {
            contracts: vec![
                caller,
                contract("IVault", EvmContractType::Interface, &[], false),
                contract("VaultA", EvmContractType::Contract, &["IVault"], false),
                contract("VaultB", EvmContractType::Contract, &["IVault"], false),
            ],
            ..Default::default()
        };
        assert_eq!(classify_type(&metadata, "IVault"), TypeTarget::Open("IVault".to_string()));
        assert_eq!(
            pairs(&relations(&metadata, false)),
            vec![("Router".to_string(), "IVault".to_string(), Relation::Unresolved)]
        );
    }

    /// `Limits limits`, `CurveStep[] steps` and a mapping are state, not relations. They got
    /// onto the map because "starts with a capital letter" was the whole test for a contract.
    #[test]
    fn a_struct_typed_immutable_is_not_a_relation() {
        let mut vault = contract("AscendYieldVault", EvmContractType::Contract, &[], false);
        vault.state_variables.extend([
            immutable("Limits"),
            immutable("CurveStep[]"),
            immutable("mapping(Id => PendingUint192)"),
            immutable("PriceFeed"),
        ]);
        let metadata = EvmBatMetadata {
            contracts: vec![vault, contract("PriceFeed", EvmContractType::Contract, &[], false)],
            file_items: vec![EvmFileItem {
                name: "Limits".to_string(),
                kind: EvmFileItemKind::Struct,
                file_path: "./src/AscendYieldVault.sol".to_string(),
                line: 5,
                end_line: 9,
                vendored: false,
                owner: "AscendYieldVault".to_string(),
            }],
            ..Default::default()
        };
        assert_eq!(classify_type(&metadata, "Limits"), TypeTarget::NotAContract);
        assert_eq!(classify_type(&metadata, "CurveStep[]"), TypeTarget::NotAContract);
        assert_eq!(classify_type(&metadata, "mapping(Id => PendingUint192)"), TypeTarget::NotAContract);
        // With boundaries on, which is where the structs used to leak through as "outside".
        assert_eq!(
            pairs(&relations(&metadata, true)),
            vec![(
                "AscendYieldVault".to_string(),
                "PriceFeed".to_string(),
                Relation::WiresAtConstruction
            )]
        );
    }

    /// `ERC20 mirror` is an instance of somebody else's token at another address, and
    /// `AscendCoreToken is ERC20` says nothing about which token. The derives-from rule used
    /// to fold it into `AscendCoreToken` itself, where the self-call filter dropped it: a real
    /// boundary, gone without a word. A vendored contract type is the outside, never a box.
    #[test]
    fn a_vendored_contract_type_is_the_outside_not_its_in_scope_child() {
        let mut token = contract("AscendCoreToken", EvmContractType::Contract, &["ERC20"], false);
        token.state_variables.push(immutable("ERC20"));
        let metadata = EvmBatMetadata {
            contracts: vec![token, contract("ERC20", EvmContractType::Abstract, &["IERC20"], true)],
            ..Default::default()
        };
        assert_eq!(classify_type(&metadata, "ERC20"), TypeTarget::Outside("ERC20".to_string()));
        assert_eq!(
            pairs(&relations(&metadata, true)),
            vec![("AscendCoreToken".to_string(), "ERC20".to_string(), Relation::Boundary)]
        );
        assert!(relations(&metadata, false).is_empty());
    }

    /// An in-scope ABSTRACT contract used as a type still collapses into the one deployable
    /// contract that derives from it — that is this project's code, with an address.
    #[test]
    fn an_in_scope_abstract_type_collapses_into_its_deployable_child() {
        let metadata = EvmBatMetadata {
            contracts: vec![
                contract("BaseVault", EvmContractType::Abstract, &[], false),
                contract("Vault", EvmContractType::Contract, &["BaseVault"], false),
            ],
            ..Default::default()
        };
        assert_eq!(classify_type(&metadata, "BaseVault"), TypeTarget::Contract("Vault".to_string()));
    }

    /// An interface of this repository that nothing declares to implement is the outside by
    /// the rule — and may be a contract implementing it without `is`. The map cannot know,
    /// so it names the interface and the command that settles it; a recorded resolution
    /// settles it.
    #[test]
    fn an_own_interface_nothing_declares_is_named_as_a_question() {
        let mut caller = contract("AscendCtoReceiver", EvmContractType::Contract, &[], false);
        caller.functions.push(calling("IListingLaunchpad"));
        let mut metadata = EvmBatMetadata {
            contracts: vec![
                caller,
                contract("ListingDesk", EvmContractType::Contract, &["ReentrancyGuard"], false),
                contract("IListingLaunchpad", EvmContractType::Interface, &[], false),
                // A vendored interface nothing implements is the outside with no question.
                contract("IMirrorFactory", EvmContractType::Interface, &[], true),
            ],
            ..Default::default()
        };
        metadata.contracts[0].functions.push(calling("IMirrorFactory"));
        assert_eq!(undeclared_interfaces(&metadata), vec!["IListingLaunchpad".to_string()]);

        metadata
            .resolutions
            .insert("IListingLaunchpad".to_string(), "ListingDesk".to_string());
        assert!(undeclared_interfaces(&metadata).is_empty());
        assert!(pairs(&relations(&metadata, false)).contains(&(
            "AscendCtoReceiver".to_string(),
            "ListingDesk".to_string(),
            Relation::Calls
        )));
    }

    /// A scan from before the flag marks nothing vendored and still has `lib/` in it. That is
    /// a map of forge-std, and the tool refuses rather than draws it.
    #[test]
    fn a_scan_before_the_vendored_flag_is_refused() {
        let mut stale = EvmBatMetadata {
            contracts: vec![
                contract("Vault", EvmContractType::Contract, &[], false),
                contract("Test", EvmContractType::Abstract, &[], false),
            ],
            ..Default::default()
        };
        stale.contracts[1].file_path = "./lib/forge-std/src/Test.sol".to_string();
        assert_eq!(predates_vendored(&stale), Some(1));

        // The same paths with the flag set is a scan that knows.
        let mut current = stale.clone();
        current.contracts[1].vendored = true;
        assert_eq!(predates_vendored(&current), None);

        // And a project with no `lib/` at all legitimately has nothing vendored.
        let bare = EvmBatMetadata {
            contracts: vec![contract("Vault", EvmContractType::Contract, &[], false)],
            ..Default::default()
        };
        assert_eq!(predates_vendored(&bare), None);
    }
}