bat-cli 0.30.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
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
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
//! 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::{ArrowEnd, ConnectorStyle, MiroClient};

pub struct MapOptions {
    /// Write a PNG of the map here instead of drawing it, so a layout can be judged without
    /// a board. Every change to how the arrows run used to cost a deployment to look at.
    pub preview: Option<String>,
    /// 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,
    /// `new X(...)`: this contract DEPLOYS that one. A fact nothing else on the map carries —
    /// a factory is why its product exists at all, and the address came from here rather than
    /// from a constructor argument.
    Creates,
    /// 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::Creates => "creates",
            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 prepared = prepare(&metadata, &options)?;
    let edges = prepared.edges.clone();
    mark("working out the relations, laying out and rendering", &mut phase);

    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 alone = unconnected(&metadata, &prepared.edges);
    if !alone.is_empty() {
        println!();
        println!(
            "{} deployable contract(s) with no relation at all — no box on the map:",
            alone.len()
        );
        for name in &alone {
            println!("  {name}");
        }
    }
    let created_elsewhere = vendored_creations(&metadata);
    if !created_elsewhere.is_empty() {
        println!();
        println!(
            "{} `new` of code this repository does not own — not drawn:",
            created_elsewhere.len()
        );
        for line in &created_elsewhere {
            println!("  {line}");
        }
    }
    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}");
        }
    }
    println!();
    for line in prepared.estimate() {
        println!("  {line}");
    }
    let calls = prepared.calls;

    if let Some(path) = options.preview.as_deref() {
        preview(&prepared, path)?;
    }
    if options.dry_run {
        prepared.discard();
        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 (left, top) =
        crate::batbelt::miro::layout::ColumnLayout::new().open_left(&obstacles, prepared.width);
    let outcome = draw(&client, prepared, left, top).await;
    mark("drawing it", &mut phase);
    let (retries, waits) = client.stats();
    println!(
        "    {:>6.1}s  in total  ({} API call(s), {retries} retr(ies), {waits} budget wait(s))",
        started.elapsed().as_secs_f64(),
        calls.total()
    );
    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";
/// Widest a lane sits from the one beside it: five stroke widths, the deploy's ratio.
const LANE_PITCH: f64 = 80.0;
/// The invisible square a leg lands on, as the deploy sizes it.
const MARKER_SIZE: f64 = 8.0;
/// One legend row per kind of relation: call, creates, wired, unresolved, outside.
const LEGEND_ROWS: usize = 5;

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::Creates => ("#8e44ad", ConnectorStroke::Solid),
        Relation::WiresAtConstruction => ("#8fd14f", ConnectorStroke::Solid),
        Relation::Unresolved => ("#f24726", ConnectorStroke::Dashed),
        Relation::Boundary => ("#ff8c00", ConnectorStroke::Dotted),
    }
}

/// Where every arrow runs: its lanes, its corridors and its legs, decided with nothing on the
/// board.
///
/// In `prepare` and not in `draw`, because the call count comes from here — an arrow that
/// skips `s` columns is `2s + 2` markers and `2s + 3` legs, and an estimate that assumes one
/// lane per arrow is an estimate that lies the moment the picture needs a corridor.
fn route_arrows(
    edges: &[Edge],
    layout: &crate::batbelt::miro::layout::GraphLayout,
) -> Vec<(crate::batbelt::evm::miro::auto_deploy::PlannedLaneArrow, ConnectorStyle)> {
    // Every arrow through lanes of its own, one per gutter it crosses, turning through the
    // corridor each skipped column reserves. Box to box with Miro routing was a tangle; one
    // lane hop with the horizontal leg crossing the picture was a smaller tangle. A relation
    // between distant columns has to travel in the gaps, which is what the corridors are.
    use crate::batbelt::evm::miro::auto_deploy::{plan_lane_chain, LaneEnd};
    use crate::batbelt::miro::layout::{assign_lanes, LANE_PITCH};

    // Which gutters each arrow crosses, and the y it enters and leaves each one at. The
    // corridor heights come from the layout, which reserved them when it bent the edge.
    let mut crossing: BTreeMap<usize, Vec<((usize, usize), f64, f64)>> = BTreeMap::new();
    let mut routed: Vec<(usize, &Edge, Vec<usize>, Vec<f64>, (f64, f64), (f64, f64))> = Vec::new();
    for (index, edge) in edges.iter().enumerate() {
        let (Some(from), Some(to)) = (layout.node(&edge.from), layout.node(&edge.to)) else {
            continue;
        };
        let (near, far) = (to.layer, from.layer);
        if far <= near {
            continue;
        }
        let corridors: Vec<f64> = layout
            .routes
            .get(index)
            .map(|bends| bends.iter().map(|(_, y)| *y).collect())
            .unwrap_or_default();
        // One gutter per step from the caller's column down to the callee's.
        let gutters: Vec<usize> = (near..far).rev().collect();
        let mut enters = from.y;
        for (step, gutter) in gutters.iter().enumerate() {
            let leaves = corridors.get(step).copied().unwrap_or(to.y);
            crossing
                .entry(*gutter)
                .or_default()
                .push(((index, step), enters, leaves));
            enters = leaves;
        }
        routed.push((
            index,
            edge,
            gutters,
            corridors,
            (from.x - from.width / 2.0, from.y),
            (to.x + to.width / 2.0, to.y),
        ));
    }

    // The lane grid, per gutter: every arrow crossing it on one grid measured from the callee
    // column's edge, ordered so two arrows that need not cross do not.
    let mut lane_of: BTreeMap<(usize, usize), f64> = BTreeMap::new();
    for (gutter, arrows) in &crossing {
        let near = layout
            .nodes
            .iter()
            .filter(|node| node.layer == *gutter)
            .map(|node| node.x + node.width / 2.0)
            .fold(f64::MIN, f64::max);
        let far = layout
            .nodes
            .iter()
            .filter(|node| node.layer == gutter + 1)
            .map(|node| node.x - node.width / 2.0)
            .fold(f64::MAX, f64::min);
        if !near.is_finite() || !far.is_finite() {
            continue;
        }
        for (key, x) in assign_lanes(arrows, near, far, LANE_PITCH) {
            lane_of.insert(key, x);
        }
    }

    let mut planned: Vec<(crate::batbelt::evm::miro::auto_deploy::PlannedLaneArrow, ConnectorStyle)> =
        Vec::new();
    for (index, edge, gutters, corridors, start, end) in routed {
        let lanes: Vec<f64> = gutters
            .iter()
            .enumerate()
            .filter_map(|(step, _)| lane_of.get(&(index, step)).copied())
            .collect();
        if lanes.is_empty() {
            continue;
        }
        let (colour, stroke) = stroke_of(edge.relation);
        planned.push((
            plan_lane_chain(
                &LaneEnd::Point { x: start.0, y: start.1 },
                &LaneEnd::Point { x: end.0, y: end.1 },
                &lanes,
                &corridors,
            ),
            ConnectorStyle {
                stroke_color: colour.to_string(),
                stroke_width: EDGE_WIDTH.to_string(),
                stroke,
                caption: None,
                arrow: ArrowEnd::End,
            },
        ));
    }

    planned
}

/// Draw the planned map into a local PNG: boxes, their names' positions, and every leg of
/// every arrow exactly where the board would put them.
///
/// It is the same plan the drawing transcribes, so what this shows is what would be drawn —
/// which is the point. Judging a layout by deploying it costs a minute and a board full of
/// frames nobody wants.
pub fn preview(prepared: &PreparedMap, path: &str) -> Result<(), EvmMiroError> {
    use crate::batbelt::evm::miro::auto_deploy::{draw_line, LaneSide};
    use image::{Rgba, RgbaImage};

    let scale = (2_600.0 / prepared.width).min(1.0);
    let width = (prepared.width * scale).round().max(1.0) as u32;
    let height = (prepared.height * scale).round().max(1.0) as u32;
    let mut canvas = RgbaImage::from_pixel(width, height, Rgba([250, 250, 250, 255]));
    let at = |x: f64, y: f64| ((x * scale) as i64, (y * scale) as i64);

    // The boxes, as outlines: what matters here is where they are, not what they say.
    for node in &prepared.layout.nodes {
        let (left, top) = at(node.x - node.width / 2.0, node.y - node.height / 2.0);
        let (right, bottom) = at(node.x + node.width / 2.0, node.y + node.height / 2.0);
        let edge = Rgba([40, 40, 40, 255]);
        draw_line(&mut canvas, (left, top), (right, top), edge);
        draw_line(&mut canvas, (right, top), (right, bottom), edge);
        draw_line(&mut canvas, (right, bottom), (left, bottom), edge);
        draw_line(&mut canvas, (left, bottom), (left, top), edge);
    }

    // Every leg of every arrow, in its own colour, from the markers the plan places.
    for (arrow, style) in &prepared.arrows {
        let colour = parse_colour(&style.stroke_color);
        for (from, _, to, _, _) in &arrow.legs {
            let point = |side: &LaneSide| match side {
                LaneSide::Marker(index) => arrow.points.get(*index).copied(),
                LaneSide::Item(_) => None,
            };
            let (Some((from_x, from_y)), Some((to_x, to_y))) = (point(from), point(to)) else {
                continue;
            };
            draw_line(&mut canvas, at(from_x, from_y), at(to_x, to_y), colour);
        }
    }

    canvas
        .save(path)
        .map_err(|error| {
            Report::new(EvmMiroError).attach_printable(format!("cannot write {path}: {error}"))
        })?;
    println!("  preview written to {}", path.bold());
    Ok(())
}

/// `#rrggbb` as a pixel. A colour this tool did not write is not worth failing over, so an
/// unparseable one is drawn grey.
fn parse_colour(hex: &str) -> image::Rgba<u8> {
    let channel = |range: std::ops::Range<usize>| {
        hex.get(range)
            .and_then(|part| u8::from_str_radix(part, 16).ok())
            .unwrap_or(128)
    };
    image::Rgba([channel(1..3), channel(3..5), channel(5..7), 255])
}

/// Measure and render the map. Local: no client, no board.
pub fn prepare(metadata: &EvmBatMetadata, options: &MapOptions) -> Result<PreparedMap, EvmMiroError> {
    use crate::batbelt::path::BatFolder;

    let all = relations(metadata);
    let edges = drawn_edges(&all, options.with_boundaries);
    if edges.is_empty() {
        return Err(Report::new(EvmMiroError)
            .attach_printable("no relations between contracts — run `bat-cli sonar` first"));
    }
    let layout = layout_map(&edges);

    BatFolder::Figures.create_folder().change_context(EvmMiroError)?;
    let destination = BatFolder::Figures.get_path(true).change_context(EvmMiroError)?;
    let render_lines = |lines: Vec<String>, name: &str| -> Result<Option<_>, EvmMiroError> {
        if lines.is_empty() {
            return Ok(None);
        }
        crate::batbelt::evm::miro::storage::render(&lines, &destination, name, 0, &[])
            .map(Some)
            .map_err(|report| report.change_context(EvmMiroError))
    };
    let matrix = render_lines(matrix(&edges), "map_matrix")?;
    // From ALL the relations, not only the drawn ones: what leaves the code is the panel's
    // whole subject, and it is worth knowing whether or not it has a box.
    let outside = render_lines(outside_panel(&all), "map_outside")?;

    // The frame is the diagram, with the two panels to its right: their widths are the reason
    // this value exists at all, because a frame created before they are measured is a frame
    // created at the wrong size.
    let beside_width = matrix
        .as_ref()
        .map(|rendered| rendered.width)
        .unwrap_or(0.0)
        .max(outside.as_ref().map(|rendered| rendered.width).unwrap_or(0.0));
    let beside_height = matrix.as_ref().map(|rendered| rendered.height).unwrap_or(0.0)
        + outside.as_ref().map(|rendered| rendered.height).unwrap_or(0.0)
        + if matrix.is_some() && outside.is_some() { MAP_MARGIN } else { 0.0 };
    let width = layout.frame_width
        + if beside_width > 0.0 { MAP_MARGIN + beside_width } else { 0.0 };
    let height = layout.frame_height.max(beside_height + MAP_MARGIN * 2.0);

    // Counted from the arrows as they will actually be drawn, chains included, plus the
    // legend's own boxes — which the first estimate forgot, and an estimate that forgets is
    // worse than none.
    let arrows = route_arrows(&edges, &layout);
    let calls = ApiCalls {
        frame: 1,
        boxes: layout.nodes.len() + LEGEND_ROWS,
        images: matrix.is_some() as usize + outside.is_some() as usize,
        markers: arrows.iter().map(|(arrow, _)| arrow.points.len()).sum(),
        connectors: arrows.iter().map(|(arrow, _)| arrow.legs.len()).sum(),
    };

    Ok(PreparedMap {
        edges,
        layout,
        arrows,
        matrix,
        outside,
        width,
        height,
        calls,
    })
}

impl PreparedMap {
    /// Throw away the renders without drawing them — a dry run, or a failure before the frame
    /// exists.
    pub fn discard(&self) {
        for rendered in [self.matrix.as_ref(), self.outside.as_ref()].into_iter().flatten() {
            let _ = std::fs::remove_file(&rendered.png_path);
        }
    }

    /// What a real run would cost, in the terminal, before it costs it.
    pub fn estimate(&self) -> Vec<String> {
        vec![
            format!(
                "frame: {} × {} board units, {} boxes, {} relations, {} panel(s)",
                self.width.round(),
                self.height.round(),
                self.layout.nodes.len(),
                self.edges.len(),
                self.calls.images
            ),
            format!(
                "API calls: 1 frame + {} boxes + {} images + {} markers + {} connectors = {}",
                self.calls.boxes,
                self.calls.images,
                self.calls.markers,
                self.calls.connectors,
                self.calls.total()
            ),
            format!(
                "           {:.1}s at Miro's ceiling of 16.7 writes a second, if nothing else limits it",
                self.calls.seconds_at_the_ceiling()
            ),
            "placement: needs the board, which a dry run does not read".to_string(),
        ]
    }
}

/// The deployable contracts that have no relation at all, and so no box.
///
/// A contract nothing calls and that calls nothing is not a contract the map can place — but
/// it IS part of the system, and a map that simply omits it is a map the reader trusts more
/// than it deserves. Listed in the report instead.
pub fn unconnected(metadata: &EvmBatMetadata, edges: &[Edge]) -> Vec<String> {
    use crate::batbelt::evm::types::EvmContractType;
    let drawn: BTreeSet<&str> = edges
        .iter()
        .flat_map(|edge| [edge.from.as_str(), edge.to.as_str()])
        .collect();
    metadata
        .contracts
        .iter()
        .filter(|contract| {
            !contract.vendored
                && matches!(contract.contract_type, EvmContractType::Contract)
                && !drawn.contains(contract.name.as_str())
        })
        .map(|contract| contract.name.clone())
        .collect()
}

/// `new X(...)` of code this repository does not own.
///
/// A factory that deploys somebody else's contract is worth a line even though the thing it
/// deploys gets no box: it is still the system creating an address at runtime.
pub fn vendored_creations(metadata: &EvmBatMetadata) -> Vec<String> {
    let mut found: BTreeSet<String> = BTreeSet::new();
    for contract in metadata.contracts.iter().filter(|c| !c.vendored) {
        for function in &contract.functions {
            for callee in callees_of(metadata, &function.metadata_id) {
                let Some(name) = callee.strip_suffix(".constructor") else {
                    continue;
                };
                let vendored = metadata
                    .contract_in_scope(name, &contract.file_path)
                    .map(|target| target.vendored)
                    .unwrap_or(true);
                if vendored {
                    found.insert(format!("{}.{} creates {name}", contract.name, function.name));
                }
            }
        }
    }
    found.into_iter().collect()
}

/// Everything the drawing needs, measured and rendered, with nothing on the board yet.
///
/// The same split `storage` and `effects` have, and for the same two reasons: the frame has to
/// be created at its final size, which the matrix and the panel decide, and a failure must
/// leave nothing half-drawn. It also lets `--dry-run` say what a real run would cost, because
/// the call count is arithmetic over this value and not something only the drawing knows.
pub struct PreparedMap {
    edges: Vec<Edge>,
    layout: crate::batbelt::miro::layout::GraphLayout,
    /// Every arrow's markers and legs, decided here so the drawing only transcribes them.
    arrows: Vec<(crate::batbelt::evm::miro::auto_deploy::PlannedLaneArrow, ConnectorStyle)>,
    /// Rendered beside the diagram: the matrix, and what lies outside the repository.
    matrix: Option<crate::batbelt::evm::miro::storage::Rendered>,
    outside: Option<crate::batbelt::evm::miro::storage::Rendered>,
    pub width: f64,
    pub height: f64,
    pub calls: ApiCalls,
}

/// What a real run will ask of Miro, counted before it asks.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct ApiCalls {
    pub frame: usize,
    pub boxes: usize,
    pub images: usize,
    pub markers: usize,
    pub connectors: usize,
}

impl ApiCalls {
    pub fn total(&self) -> usize {
        self.frame + self.boxes + self.images + self.markers + self.connectors
    }

    /// How long that many writes take at Miro's own ceiling.
    ///
    /// The budget is 100 000 credits a minute and a level-2 write costs 100, so 16.7 writes a
    /// second is the wall nothing gets past — the deploy measured 16.2 with 24 permits and no
    /// retries, which is that wall. Anything slower than this estimate is latency or an error,
    /// and that is what makes the number worth printing.
    pub fn seconds_at_the_ceiling(&self) -> f64 {
        self.total() as f64 / 16.7
    }
}

/// The adjacency MATRIX of the map, as lines of text.
///
/// The thing a node-link diagram is worst at: "is there an edge between these two" and "who is
/// reached by the most" are a sweep of a row and a column here, and no amount of arrows makes
/// them that. It is also the half that still works at eighty contracts, where the diagram does
/// not. Rows are callers, columns are the same contracts in the same order, so the two halves
/// of the frame can be read against each other.
pub fn matrix(edges: &[Edge]) -> Vec<String> {
    let mut names: Vec<&str> = edges
        .iter()
        .flat_map(|edge| [edge.from.as_str(), edge.to.as_str()])
        .collect();
    names.sort();
    names.dedup();
    if names.len() < 3 {
        return Vec::new();
    }

    let mark = |from: &str, to: &str| -> &'static str {
        match edges
            .iter()
            .find(|edge| edge.from == from && edge.to == to)
            .map(|edge| edge.relation)
        {
            Some(Relation::Calls) => "●",
            Some(Relation::Creates) => "◆",
            Some(Relation::WiresAtConstruction) => "○",
            Some(Relation::Unresolved) => "?",
            Some(Relation::Boundary) => "▲",
            None => "·",
        }
    };

    // Columns are numbered, because thirteen contract names across the top is a header wider
    // than the whole diagram beside it. The number is the row's own, so a reader goes from a
    // column back to its name without a legend.
    let widest = names.iter().map(|name| name.len()).max().unwrap_or(0);
    let mut lines = vec![
        "who talks to whom — a row is a caller, a column is the same list".to_string(),
        "● calls   ◆ creates   ○ wired at construction   ? unresolved   ▲ leaves the code"
            .to_string(),
        String::new(),
    ];
    let header: String = (1..=names.len())
        .map(|index| format!("{:>3}", index))
        .collect();
    lines.push(format!("{:width$}   {header}", "", width = widest + 3));
    for (index, from) in names.iter().enumerate() {
        let row: String = names
            .iter()
            .map(|to| format!("{:>3}", mark(from, to)))
            .collect();
        let out = edges.iter().filter(|edge| &edge.from == from).count();
        let into = edges.iter().filter(|edge| &edge.to == from).count();
        lines.push(format!(
            "{:>2} {:width$}   {row}   → {out}, ← {into}",
            index + 1,
            from,
            width = widest,
        ));
    }
    lines
}

/// What the system touches that has no source in this repository, as lines of text.
///
/// A panel and not boxes: these are not contracts of this audit, they are its edge, and giving
/// them the same shape as the code under review is how a reader starts believing the ERC-20
/// they cannot read is part of the system they can.
pub fn outside_panel(edges: &[Edge]) -> Vec<String> {
    let mut reached: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
    for edge in edges.iter().filter(|edge| edge.relation == Relation::Boundary) {
        reached
            .entry(edge.to.as_str())
            .or_default()
            .insert(edge.from.as_str());
    }
    if reached.is_empty() {
        return Vec::new();
    }
    let mut lines = vec![
        format!("outside this repository ({})", reached.len()),
        "no source here, so what they do with the call is unknown".to_string(),
        String::new(),
    ];
    for (name, callers) in reached {
        lines.push(format!(
            "  {name:<26} ← {}",
            callers.into_iter().collect::<Vec<_>>().join(", ")
        ));
    }
    lines
}

/// 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.
/// The edges that get a box and an arrow: the outside is a panel, not part of the diagram,
/// unless the auditor asked for it.
fn drawn_edges(edges: &[Edge], with_boundaries: bool) -> Vec<Edge> {
    edges
        .iter()
        .filter(|edge| with_boundaries || edge.relation != Relation::Boundary)
        .cloned()
        .collect()
}

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());

    // Laid out TWICE, and the second time is the point. The first tells us which column each
    // contract lands in; from that we can count how many arrows cross each gutter, and a
    // gutter has to be wide enough to hold them all a full pitch apart. Squeezing the lanes
    // instead is how a picture stops saying which arrow is which — so the gutter widens and
    // the layout is asked again. It is pure, so asking twice costs nothing but arithmetic, and
    // the second answer differs only in x.
    let config = |gutter_x: f64| LayoutConfig {
        padding_x: MAP_MARGIN,
        // Room for the legend, which sits in the corner the layout would otherwise start in:
        // one box of a row's height per relation kind.
        padding_y: MAP_MARGIN + (NODE_HEIGHT + 60.0) * LEGEND_ROWS as f64,
        gutter_x,
        // Boxes of a map are a name each, a fraction of the height of a screenshot, so the
        // deploy's gap between them leaves six rows crammed into the top of the frame while
        // every arrow queues through the same strip of middle. Spread vertically, an arrow has
        // room to travel at its own height.
        gutter_y: NODE_HEIGHT * 1.5,
        ..Default::default()
    };
    let first = layout_graph(&root, &nodes, &laid_edges, config(LayoutConfig::default().gutter_x));
    let busiest = busiest_gutter(edges, &first);
    let wanted = crate::batbelt::miro::layout::gutter_for(busiest);
    if wanted <= LayoutConfig::default().gutter_x {
        return first;
    }
    layout_graph(&root, &nodes, &laid_edges, config(wanted))
}

/// How many arrows cross the busiest gutter.
///
/// An edge between columns `a` and `b` passes through every gutter between them, so a gutter's
/// load is not "the edges that end here" — that undercount is what let twelve arrows share a
/// gutter sized for one.
fn busiest_gutter(edges: &[Edge], layout: &crate::batbelt::miro::layout::GraphLayout) -> usize {
    let mut per_gutter: BTreeMap<usize, usize> = BTreeMap::new();
    for edge in edges {
        let (Some(from), Some(to)) = (layout.node(&edge.from), layout.node(&edge.to)) else {
            continue;
        };
        let (low, high) = (from.layer.min(to.layer), from.layer.max(to.layer));
        for gutter in low..high {
            *per_gutter.entry(gutter).or_default() += 1;
        }
    }
    per_gutter.into_values().max().unwrap_or(0)
}

/// Put the map on the board: one box per contract, one arrow per relation.
async fn draw(
    client: &MiroClient,
    prepared: PreparedMap,
    left: f64,
    top: f64,
) -> Result<(), EvmMiroError> {
    let PreparedMap {
        edges,
        layout,
        arrows: prepared_arrows,
        matrix,
        outside,
        width: frame_width,
        height: frame_height,
        ..
    } = prepared;
    let edges = edges.as_slice();

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

    // The two panels, to the right of the diagram: the matrix, and what lies outside the
    // repository. They go up WITH the boxes — their only reference is the frame, and an image
    // upload is the longest call here, so starting it first means its latency overlaps the
    // rest instead of trailing it.
    let mut uploading = tokio::task::JoinSet::new();
    let panel_left = layout.frame_width + MAP_MARGIN;
    let mut panel_top = MAP_MARGIN;
    for rendered in [matrix.as_ref(), outside.as_ref()].into_iter().flatten() {
        let (x, y) = (
            panel_left + rendered.width / 2.0,
            panel_top + rendered.height / 2.0,
        );
        panel_top += rendered.height + MAP_MARGIN;
        let client = client.clone();
        let frame_id = frame_id.clone();
        let png = rendered.png_path.clone();
        let width = rendered.width;
        uploading.spawn(async move {
            let item = client
                .create_image_in_frame(&png, &frame_id, "map", x, y, width)
                .await;
            let _ = std::fs::remove_file(&png);
            item
        });
    }

    // 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::Creates,
        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);
    }
    while let Some(joined) = uploading.join_next().await {
        joined
            .map_err(|error| Report::new(EvmMiroError).attach_printable(error.to_string()))?
            .change_context(EvmMiroError)?;
    }
    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();
    // Every arrow through a LANE of its own, drawn by the deploy's own `draw_lane_arrow`:
    // three straight legs between markers we place, so Miro is never asked to route. Box to
    // box with Miro routing was what turned eighteen relations into a tangle nobody could
    // read — and the design doc has said since the first deployment that a crossing is only
    // removed by changing where things are, never by a cleverer line.
    //
    // The lanes in one gutter are ordered by where the arrow ENDS, the deploy's rule: arrows
    // that need not cross then do not.
    use crate::batbelt::evm::miro::auto_deploy::LaneSide;
    let planned = prepared_arrows;

    let planned_names: Vec<String> = planned
        .iter()
        .enumerate()
        .map(|(index, _)| {
            edges
                .get(index)
                .map(|edge| format!("{} → {}", edge.from, edge.to))
                .unwrap_or_default()
        })
        .collect();
    let mut skipped: Vec<String> = Vec::new();

    // Every marker of every arrow, together.
    for (index, (arrow, _)) in planned.iter().enumerate() {
        for (point, (x, y)) in arrow.points.iter().enumerate() {
            let client = client.clone();
            let frame_id = frame_id.clone();
            let (x, y) = (*x, *y);
            drawing.spawn(async move {
                client
                    .create_anchor_marker(&frame_id, x, y, MARKER_SIZE)
                    .await
                    .map(|id| (index, point, id))
                    .map_err(|report| report.change_context(EvmMiroError))
            });
        }
    }
    // Every marker is awaited, whatever happens to any of them. Returning on the first failure
    // aborts the requests still in flight: items get created that nothing reports, and the
    // frame's URL is never printed, so the auditor is left with a half-drawn frame and no idea
    // what is on it. A failure here costs its own arrow and says so by name.
    let mut markers: BTreeMap<(usize, usize), String> = BTreeMap::new();
    let mut failures: Vec<String> = Vec::new();
    while let Some(joined) = drawing.join_next().await {
        match joined {
            Ok(Ok((index, point, id))) => {
                markers.insert((index, point), id);
            }
            Ok(Err(report)) => failures.push(format!("marker: {}", report.current_context())),
            Err(error) => failures.push(format!("marker: {error}")),
        }
    }

    // Then every leg of every arrow, together: each one's two ends already exist.
    for (index, (arrow, style)) in planned.iter().enumerate() {
        for (from_side, from_anchor, to_side, to_anchor, head) in &arrow.legs {
            let resolve = |side: &LaneSide| match side {
                LaneSide::Marker(point) => markers.get(&(index, *point)).cloned(),
                LaneSide::Item(id) => Some(id.clone()),
            };
            let (Some(from_id), Some(to_id)) = (resolve(from_side), resolve(to_side)) else {
                // Its marker failed, so this leg has nowhere to land. Named rather than
                // dropped: a missing arrow the reader is not told about is a map that lies.
                skipped.push(format!(
                    "{} → {}",
                    planned_names.get(index).map(String::as_str).unwrap_or("?"),
                    "a leg whose marker failed"
                ));
                continue;
            };
            let mut leg = style.clone();
            leg.arrow = if *head { ArrowEnd::End } else { ArrowEnd::None };
            let (from_anchor, to_anchor) = (*from_anchor, *to_anchor);
            let client = client.clone();
            drawing.spawn(async move {
                client
                    .create_connector(&from_id, from_anchor, &to_id, to_anchor, leg)
                    .await
                    .map(|id| (0usize, 0usize, id))
                    .map_err(|report| report.change_context(EvmMiroError))
            });
        }
    }
    let mut legs = 0usize;
    while let Some(joined) = drawing.join_next().await {
        match joined {
            Ok(Ok(_)) => legs += 1,
            Ok(Err(report)) => failures.push(format!("leg: {}", report.current_context())),
            Err(error) => failures.push(format!("leg: {error}")),
        }
    }
    for line in skipped.iter().chain(failures.iter()) {
        println!("    {} {line}", "skipped:".yellow());
    }
    println!(
        "    {} {} relation(s) drawn, {legs} leg(s)",
        "✓".green(),
        planned.len()
    );
    println!("  {}", client.frame_url(&frame_id).blue());
    if !failures.is_empty() {
        return Err(Report::new(EvmMiroError).attach_printable(format!(
            "{} item(s) of this map could not be drawn — the frame above has the rest",
            failures.len()
        )));
    }
    Ok(())
}

/// Every relation between contracts, one per pair and kind — the outside included.
///
/// What LEAVES the repository is always worked out, because the panel beside the diagram is
/// made of it; whether it also gets a box is `drawn_edges`'s decision and the auditor's flag.
///
/// 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) -> 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 hosted_by = hosts(metadata);
    // A library or an abstract base is not a node: its code runs as the contract that uses it,
    // which is what `hosts` works out. It is not a destination either — calling `MathLib.wad`
    // executes in the CALLER's address, so an arrow to it would be an arrow a contract draws
    // to itself.
    let folded: BTreeSet<&str> = metadata
        .contracts
        .iter()
        .filter(|contract| {
            !contract.vendored
                && matches!(
                    contract.contract_type,
                    crate::batbelt::evm::types::EvmContractType::Library
                        | crate::batbelt::evm::types::EvmContractType::Abstract
                )
        })
        .map(|contract| contract.name.as_str())
        .collect();

    let mut found: BTreeSet<Edge> = BTreeSet::new();
    for contract in metadata.contracts.iter().filter(|c| !c.vendored) {
        if ignored(&contract.name, &contract.file_path) || folded.contains(contract.name.as_str())
        {
            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. Neither is a call into a library, which is
            // the same thing said differently — that code runs here.
            if to.is_empty() || to == contract.name || folded.contains(to) {
                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)),
                // The outside is always KNOWN — it is what the panel is made of — and the
                // flag decides only whether it also gets a box in the diagram. Dropping it
                // here is how the panel came out empty without the flag.
                TypeTarget::Outside(name) => Some((name, Relation::Boundary)),
                TypeTarget::NotAContract => None,
            }
        };

        // What this contract's code IS: itself, plus every library and abstract base whose
        // functions run as it. A library has no address and no state — its call leaves the
        // host's address — so drawing it as a node invents an actor that does not exist. The
        // folding lives HERE and nowhere else: the entry-point graph still draws every
        // library function as its own screenshot, which is what the auditor reads there.
        let mut sources: Vec<&ContractMetadata> = vec![contract];
        sources.extend(
            hosted_by
                .get(contract.name.as_str())
                .into_iter()
                .flatten()
                .filter_map(|name| {
                    metadata
                        .contract_in_scope(name, &contract.file_path)
                        .or_else(|| metadata.contracts.iter().find(|c| &c.name == name))
                }),
        );

        for function in sources.iter().flat_map(|source| source.functions.iter()) {
            // `new X(...)`, which the scan records as a callee named `X.constructor`. Resolved
            // through the CALLER's file, never by name alone: `lib/` holds three `ProxyAdmin`s
            // and the import graph is what says which one this is.
            for created in created_by(metadata, contract, &function.metadata_id) {
                record(&created, Relation::Creates);
            }
            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 sources.iter().flat_map(|source| wired_at_construction(source)) {
            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()
}

/// Which deployable contracts a library's or an abstract base's code runs as.
///
/// A library has no address: its call leaves the host contract's address, so on a map of who
/// talks to whom the library is not a party. `hosts` answers "whose code is this", from the
/// `Lib.fn` callees the scan recorded and from inheritance, iterated to a FIXPOINT so a
/// library reached only through another library still reaches the contract at the end of the
/// chain.
///
/// Returns host name → the libraries and bases it hosts.
fn hosts(metadata: &EvmBatMetadata) -> BTreeMap<String, BTreeSet<String>> {
    use crate::batbelt::evm::types::EvmContractType;

    let folded: BTreeMap<&str, &ContractMetadata> = metadata
        .contracts
        .iter()
        .filter(|contract| {
            !contract.vendored
                && matches!(
                    contract.contract_type,
                    EvmContractType::Library | EvmContractType::Abstract
                )
        })
        .map(|contract| (contract.name.as_str(), contract))
        .collect();
    if folded.is_empty() {
        return BTreeMap::new();
    }

    // Who uses what, one hop: a contract uses a library when it calls `Lib.fn`, and a base
    // when it declares it.
    let mut uses: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    for contract in metadata.contracts.iter().filter(|c| !c.vendored) {
        let mut used: BTreeSet<String> = contract
            .base_contracts
            .iter()
            .filter(|base| folded.contains_key(base.as_str()))
            .cloned()
            .collect();
        for function in &contract.functions {
            for callee in callees_of(metadata, &function.metadata_id) {
                if let Some((receiver, _)) = callee.split_once('.') {
                    if folded.contains_key(receiver) {
                        used.insert(receiver.to_string());
                    }
                }
            }
        }
        uses.insert(contract.name.clone(), used);
    }

    // To a fixpoint: a host inherits what its libraries use. Bounded by the number of
    // contracts, because each pass can only add, and a pass that adds nothing is the end.
    let mut hosted: BTreeMap<String, BTreeSet<String>> = uses
        .iter()
        .filter(|(name, _)| !folded.contains_key(name.as_str()))
        .map(|(name, used)| (name.clone(), used.clone()))
        .collect();
    for _ in 0..metadata.contracts.len().max(1) {
        let mut grew = false;
        for set in hosted.values_mut() {
            let reached: BTreeSet<String> = set
                .iter()
                .filter_map(|library| uses.get(library))
                .flatten()
                .cloned()
                .collect();
            for name in reached {
                grew |= set.insert(name);
            }
        }
        if !grew {
            break;
        }
    }
    hosted
}

/// The callee names the scan recorded for one function, as written (`Lib.fn`, `X.constructor`).
fn callees_of<'a>(metadata: &'a EvmBatMetadata, function_id: &str) -> &'a [String] {
    metadata
        .function_dependencies
        .iter()
        .find(|dependency| dependency.function_metadata_id == function_id)
        .map(|dependency| dependency.callees.as_slice())
        .unwrap_or(&[])
}

/// The deployable contracts one function creates with `new X(...)`.
///
/// The scan writes those as a callee named `X.constructor`. `X` is resolved through the
/// CALLER's file — `lib/` vendors three `ProxyAdmin`s, and the import graph is the only thing
/// that says which one a name means here. A `new` of vendored or unknown code is not a
/// relation on this map; it is listed with the untyped receivers instead.
fn created_by(
    metadata: &EvmBatMetadata,
    caller: &ContractMetadata,
    function_id: &str,
) -> Vec<String> {
    callees_of(metadata, function_id)
        .iter()
        .filter_map(|callee| callee.strip_suffix(".constructor"))
        .filter_map(|name| metadata.contract_in_scope(name, &caller.file_path))
        .filter(|target| !target.vendored)
        .map(|target| target.name.clone())
        .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::{drawn_edges, 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)),
            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(&drawn_edges(&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)),
            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)),
            vec![("AscendCoreToken".to_string(), "ERC20".to_string(), Relation::Boundary)]
        );
        assert!(drawn_edges(&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(&drawn_edges(&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);
    }
}

#[cfg(test)]
mod folding_test {
    use super::{hosts, Relation};
    use crate::batbelt::evm::metadata::bat_metadata::{
        ContractMetadata, EvmBatMetadata, FunctionDependency,
    };
    use crate::batbelt::evm::types::EvmContractType;

    /// The map only ever reads a handful of fields; the rest of a scanned contract is noise
    /// here, and writing it out would hide what each test is actually about.
    fn contract(name: &str, kind: EvmContractType, bases: &[&str]) -> ContractMetadata {
        let mut built: ContractMetadata =
            serde_json::from_str(&format!(
                r#"{{"metadata_id":"{name}","name":"{name}","file_path":"./src/{name}.sol",
                    "contract_type":"{kind:?}","base_contracts":[],"functions":[],
                    "state_variables":[],"events":[],"modifiers":[],"line":1}}"#
            ))
            .expect("fixture parses");
        built.base_contracts = bases.iter().map(|base| base.to_string()).collect();
        built
    }

    fn with_function(mut contract: ContractMetadata, id: &str) -> ContractMetadata {
        let function = serde_json::from_str(&format!(
            r#"{{"metadata_id":"{id}","name":"f","contract_name":"{}","visibility":"Internal",
                "mutability":"NonPayable","modifiers":[],"params":[],"returns":[],"line":1,
                "end_line":2,"is_constructor":false}}"#,
            contract.name
        ))
        .expect("fixture parses");
        contract.functions.push(function);
        contract
    }

    fn metadata(contracts: Vec<ContractMetadata>, deps: Vec<(&str, &str)>) -> EvmBatMetadata {
        let mut built: EvmBatMetadata = serde_json::from_str(
            r#"{"contracts":[],"entry_points":[],"function_dependencies":[],"interfaces":[],
                "file_items":[]}"#,
        )
        .expect("an empty scan");
        built.contracts = contracts;
        built.function_dependencies = deps
            .into_iter()
            .map(|(id, callee)| FunctionDependency {
                function_metadata_id: id.to_string(),
                callees: vec![callee.to_string()],
            })
            .collect();
        built
    }

    /// A library used by one contract is that contract's code, and `hosts` says so.
    #[test]
    fn a_library_is_hosted_by_the_contract_that_uses_it() {
        let built = metadata(
            vec![
                with_function(contract("Vault", EvmContractType::Contract, &[]), "vault_f"),
                contract("MathLib", EvmContractType::Library, &[]),
            ],
            vec![("vault_f", "MathLib.wadMul")],
        );
        let hosted = hosts(&built);
        assert!(hosted["Vault"].contains("MathLib"));
        assert!(!hosted.contains_key("MathLib"), "a library hosts nobody");
    }

    /// A library reached only through another library still reaches the contract at the end:
    /// the fixpoint is what makes `FLAMMStore` → `FLAMMFlowLib` → `FLAMM` work.
    #[test]
    fn hosting_is_transitive() {
        let built = metadata(
            vec![
                with_function(contract("FLAMM", EvmContractType::Contract, &[]), "flamm_f"),
                with_function(contract("FlowLib", EvmContractType::Library, &[]), "flow_f"),
                contract("StoreLib", EvmContractType::Library, &[]),
            ],
            vec![("flamm_f", "FlowLib.run"), ("flow_f", "StoreLib.read")],
        );
        let hosted = hosts(&built);
        assert!(hosted["FLAMM"].contains("FlowLib"));
        assert!(hosted["FLAMM"].contains("StoreLib"), "reached through FlowLib");
    }

    /// An abstract base folds the same way, through inheritance.
    #[test]
    fn an_abstract_base_is_hosted_by_what_inherits_it() {
        let built = metadata(
            vec![
                contract("Router", EvmContractType::Contract, &["Pausable"]),
                contract("Pausable", EvmContractType::Abstract, &[]),
            ],
            vec![],
        );
        assert!(hosts(&built)["Router"].contains("Pausable"));
    }

    /// `Creates` sits between a call and construction wiring: a pair that is both called and
    /// created keeps the call, and a pair only created keeps `creates`.
    #[test]
    fn a_created_and_called_pair_keeps_the_call() {
        assert!(Relation::Calls < Relation::Creates);
        assert!(Relation::Creates < Relation::WiresAtConstruction);
    }
}

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

    fn edge(from: &str, to: &str, relation: Relation) -> Edge {
        Edge {
            from: from.to_string(),
            to: to.to_string(),
            relation,
        }
    }

    /// The matrix says, for every pair, what kind of relation they have — and its row and
    /// column sums are the answer to "who is reached by the most", which is the question a
    /// node-link drawing is worst at.
    #[test]
    fn the_matrix_marks_each_pair_and_counts_both_ways() {
        let edges = vec![
            edge("A", "C", Relation::Calls),
            edge("B", "C", Relation::Creates),
            edge("A", "B", Relation::WiresAtConstruction),
        ];
        let lines = matrix(&edges);
        let row_a = lines.iter().find(|line| line.contains(" A ")).expect("A's row");
        assert!(row_a.contains('●'), "A calls C");
        assert!(row_a.contains('○'), "A wires B");
        assert!(row_a.ends_with("→ 2, ← 0"), "A reaches two and is reached by none: {row_a}");
        let row_c = lines.iter().find(|line| line.contains(" C ")).expect("C's row");
        assert!(row_c.ends_with("→ 0, ← 2"), "C is the one everything points at: {row_c}");
    }

    /// Under three contracts a matrix says nothing a glance at the diagram does not.
    #[test]
    fn a_tiny_system_gets_no_matrix() {
        assert!(matrix(&[edge("A", "B", Relation::Calls)]).is_empty());
    }

    /// The panel is what leaves the repository, with who reaches it — and nothing else.
    #[test]
    fn the_panel_lists_what_leaves_and_who_reaches_it() {
        let edges = vec![
            edge("Vault", "IERC20", Relation::Boundary),
            edge("Router", "IERC20", Relation::Boundary),
            edge("Vault", "Oracle", Relation::Calls),
        ];
        let lines = outside_panel(&edges);
        let erc20 = lines.iter().find(|line| line.contains("IERC20")).expect("the line");
        assert!(erc20.contains("Router") && erc20.contains("Vault"), "both callers: {erc20}");
        assert!(!lines.iter().any(|line| line.contains("Oracle")), "a call in scope is not outside");
    }

    /// Nothing leaves, no panel: an empty box saying "none" is furniture, not information.
    #[test]
    fn nothing_leaving_is_no_panel() {
        assert!(outside_panel(&[edge("A", "B", Relation::Calls)]).is_empty());
    }
}